xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 148434217c040ea38dc844384f6ba68d9b325906)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 #include <sys/squeue_impl.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	uint_t		ird_flags;	/* see below */
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 #define	IRD_REPORT_TESTHIDDEN	0x01	/* include IRE_MARK_TESTHIDDEN routes */
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, certain multicast operations, most set ioctls,
236  * igmp/mld timers etc.
237  *
238  * Plumbing is a long sequence of operations involving message
239  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
240  * involved in plumbing operations. A natural model is to serialize these
241  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
242  * parallel without any interference. But various set ioctls on hme0 are best
243  * serialized, along with multicast join/leave operations, igmp/mld timer
244  * operations, and processing of DLPI control messages received from drivers
245  * on a per phyint basis.  This serialization is provided by the ipsq_t and
246  * primitives operating on this. Details can be found in ip_if.c above the
247  * core primitives operating on ipsq_t.
248  *
249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
251  * In addition ipif's and ill's referenced by the ire are also indirectly
252  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
253  * the ipif's address or netmask change as long as an ipif is refheld
254  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
255  * address of an ipif has to go through the ipsq_t. This ensures that only
256  * 1 such exclusive operation proceeds at any time on the ipif. It then
257  * deletes all ires associated with this ipif, and waits for all refcnts
258  * associated with this ipif to come down to zero. The address is changed
259  * only after the ipif has been quiesced. Then the ipif is brought up again.
260  * More details are described above the comment in ip_sioctl_flags.
261  *
262  * Packet processing is based mostly on IREs and are fully multi-threaded
263  * using standard Solaris MT techniques.
264  *
265  * There are explicit locks in IP to handle:
266  * - The ip_g_head list maintained by mi_open_link() and friends.
267  *
268  * - The reassembly data structures (one lock per hash bucket)
269  *
270  * - conn_lock is meant to protect conn_t fields. The fields actually
271  *   protected by conn_lock are documented in the conn_t definition.
272  *
273  * - ire_lock to protect some of the fields of the ire, IRE tables
274  *   (one lock per hash bucket). Refer to ip_ire.c for details.
275  *
276  * - ndp_g_lock and nce_lock for protecting NCEs.
277  *
278  * - ill_lock protects fields of the ill and ipif. Details in ip.h
279  *
280  * - ill_g_lock: This is a global reader/writer lock. Protects the following
281  *	* The AVL tree based global multi list of all ills.
282  *	* The linked list of all ipifs of an ill
283  *	* The <ipsq-xop> mapping
284  *	* <ill-phyint> association
285  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
286  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
287  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
288  *   writer for the actual duration of the insertion/deletion/change.
289  *
290  * - ill_lock:  This is a per ill mutex.
291  *   It protects some members of the ill_t struct; see ip.h for details.
292  *   It also protects the <ill-phyint> assoc.
293  *   It also protects the list of ipifs hanging off the ill.
294  *
295  * - ipsq_lock: This is a per ipsq_t mutex lock.
296  *   This protects some members of the ipsq_t struct; see ip.h for details.
297  *   It also protects the <ipsq-ipxop> mapping
298  *
299  * - ipx_lock: This is a per ipxop_t mutex lock.
300  *   This protects some members of the ipxop_t struct; see ip.h for details.
301  *
302  * - phyint_lock: This is a per phyint mutex lock. Protects just the
303  *   phyint_flags
304  *
305  * - ip_g_nd_lock: This is a global reader/writer lock.
306  *   Any call to nd_load to load a new parameter to the ND table must hold the
307  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
308  *   as reader.
309  *
310  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
311  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
312  *   uniqueness check also done atomically.
313  *
314  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
315  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
316  *   as a writer when adding or deleting elements from these lists, and
317  *   as a reader when walking these lists to send a SADB update to the
318  *   IPsec capable ills.
319  *
320  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
321  *   group list linked by ill_usesrc_grp_next. It also protects the
322  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
323  *   group is being added or deleted.  This lock is taken as a reader when
324  *   walking the list/group(eg: to get the number of members in a usesrc group).
325  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
326  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
327  *   example, it is not necessary to take this lock in the initial portion
328  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
329  *   operations are executed exclusively and that ensures that the "usesrc
330  *   group state" cannot change. The "usesrc group state" change can happen
331  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
332  *
333  * Changing <ill-phyint>, <ipsq-xop> assocications:
334  *
335  * To change the <ill-phyint> association, the ill_g_lock must be held
336  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
337  * must be held.
338  *
339  * To change the <ipsq-xop> association, the ill_g_lock must be held as
340  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
341  * This is only done when ills are added or removed from IPMP groups.
342  *
343  * To add or delete an ipif from the list of ipifs hanging off the ill,
344  * ill_g_lock (writer) and ill_lock must be held and the thread must be
345  * a writer on the associated ipsq.
346  *
347  * To add or delete an ill to the system, the ill_g_lock must be held as
348  * writer and the thread must be a writer on the associated ipsq.
349  *
350  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
351  * must be a writer on the associated ipsq.
352  *
353  * Lock hierarchy
354  *
355  * Some lock hierarchy scenarios are listed below.
356  *
357  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
358  * ill_g_lock -> ill_lock(s) -> phyint_lock
359  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
360  * ill_g_lock -> ip_addr_avail_lock
361  * conn_lock -> irb_lock -> ill_lock -> ire_lock
362  * ill_g_lock -> ip_g_nd_lock
363  *
364  * When more than 1 ill lock is needed to be held, all ill lock addresses
365  * are sorted on address and locked starting from highest addressed lock
366  * downward.
367  *
368  * IPsec scenarios
369  *
370  * ipsa_lock -> ill_g_lock -> ill_lock
371  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
372  * ipsec_capab_ills_lock -> ipsa_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IPsec notes :
417  *
418  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
419  * in front of the actual packet. For outbound datagrams, the M_CTL
420  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
421  * information used by the IPsec code for applying the right level of
422  * protection. The information initialized by IP in the ipsec_out_t
423  * is determined by the per-socket policy or global policy in the system.
424  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
425  * ipsec_info.h) which starts out with nothing in it. It gets filled
426  * with the right information if it goes through the AH/ESP code, which
427  * happens if the incoming packet is secure. The information initialized
428  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
429  * the policy requirements needed by per-socket policy or global policy
430  * is met or not.
431  *
432  * If there is both per-socket policy (set using setsockopt) and there
433  * is also global policy match for the 5 tuples of the socket,
434  * ipsec_override_policy() makes the decision of which one to use.
435  *
436  * For fully connected sockets i.e dst, src [addr, port] is known,
437  * conn_policy_cached is set indicating that policy has been cached.
438  * conn_in_enforce_policy may or may not be set depending on whether
439  * there is a global policy match or per-socket policy match.
440  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
441  * Once the right policy is set on the conn_t, policy cannot change for
442  * this socket. This makes life simpler for TCP (UDP ?) where
443  * re-transmissions go out with the same policy. For symmetry, policy
444  * is cached for fully connected UDP sockets also. Thus if policy is cached,
445  * it also implies that policy is latched i.e policy cannot change
446  * on these sockets. As we have the right policy on the conn, we don't
447  * have to lookup global policy for every outbound and inbound datagram
448  * and thus serving as an optimization. Note that a global policy change
449  * does not affect fully connected sockets if they have policy. If fully
450  * connected sockets did not have any policy associated with it, global
451  * policy change may affect them.
452  *
453  * IP Flow control notes:
454  * ---------------------
455  * Non-TCP streams are flow controlled by IP. The way this is accomplished
456  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
457  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
458  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
459  * functions.
460  *
461  * Per Tx ring udp flow control:
462  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
463  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
464  *
465  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
466  * To achieve best performance, outgoing traffic need to be fanned out among
467  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
468  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
469  * the address of connp as fanout hint to mac_tx(). Under flow controlled
470  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
471  * cookie points to a specific Tx ring that is blocked. The cookie is used to
472  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
473  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
474  * connp's. The drain list is not a single list but a configurable number of
475  * lists.
476  *
477  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
478  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
479  * which is equal to 128. This array in turn contains a pointer to idl_t[],
480  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
481  * list will point to the list of connp's that are flow controlled.
482  *
483  *                      ---------------   -------   -------   -------
484  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   |  ---------------   -------   -------   -------
487  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
488  * ----------------  |  ---------------   -------   -------   -------
489  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
490  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
491  *                   |  ---------------   -------   -------   -------
492  *                   .        .              .         .         .
493  *                   |  ---------------   -------   -------   -------
494  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
495  *                      ---------------   -------   -------   -------
496  *                      ---------------   -------   -------   -------
497  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
498  *                   |  ---------------   -------   -------   -------
499  *                   |  ---------------   -------   -------   -------
500  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
501  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
502  * ----------------  |        .              .         .         .
503  *                   |  ---------------   -------   -------   -------
504  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
505  *                      ---------------   -------   -------   -------
506  *     .....
507  * ----------------
508  * |idl_tx_list[n]|-> ...
509  * ----------------
510  *
511  * When mac_tx() returns a cookie, the cookie is used to hash into a
512  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
513  * called passing idl_tx_list. The connp gets inserted in a drain list
514  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
515  * the sockets (non stream based) and sets QFULL condition for conn_wq.
516  * connp->conn_direct_blocked will be set to indicate the blocked
517  * condition.
518  *
519  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
520  * A cookie is passed in the call to ill_flow_enable() that identifies the
521  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
522  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
523  * and goes through each of the drain list (q)enabling the conn_wq of the
524  * first conn in each of the drain list. This causes ip_wsrv to run for the
525  * conn. ip_wsrv drains the queued messages, and removes the conn from the
526  * drain list, if all messages were drained. It also qenables the next conn
527  * in the drain list to continue the drain process.
528  *
529  * In reality the drain list is not a single list, but a configurable number
530  * of lists. conn_drain_walk() in the IP module, qenables the first conn in
531  * each list. If the ip_wsrv of the next qenabled conn does not run, because
532  * the stream closes, ip_close takes responsibility to qenable the next conn
533  * in the drain list. conn_drain_insert and conn_drain_tail are the only
534  * functions that manipulate this drain list. conn_drain_insert is called in
535  * ip_wput context itself (as opposed to from ip_wsrv context for STREAMS
536  * case -- see below). The synchronization between drain insertion and flow
537  * control wakeup is handled by using idl_txl->txl_lock.
538  *
539  * Flow control using STREAMS:
540  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
541  * is used. On the send side, if the packet cannot be sent down to the
542  * driver by IP, because of a canput failure, IP does a putq on the conn_wq.
543  * This will cause ip_wsrv to run on the conn_wq. ip_wsrv in turn, inserts
544  * the conn in a list of conn's that need to be drained when the flow
545  * control condition subsides. The blocked connps are put in first member
546  * of ips_idl_tx_list[] array. Ultimately STREAMS backenables the ip_wsrv
547  * on the IP module. It calls conn_walk_drain() passing ips_idl_tx_list[0].
548  * ips_idl_tx_list[0] contains the drain lists of blocked conns. The
549  * conn_wq of the first conn in the drain lists is (q)enabled to run.
550  * ip_wsrv on this conn drains the queued messages, and removes the conn
551  * from the drain list, if all messages were drained. It also qenables the
552  * next conn in the drain list to continue the drain process.
553  *
554  * If the ip_wsrv of the next qenabled conn does not run, because the
555  * stream closes, ip_close takes responsibility to qenable the next conn in
556  * the drain list. The directly called ip_wput path always does a putq, if
557  * it cannot putnext. Thus synchronization problems are handled between
558  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
559  * functions that manipulate this drain list. Furthermore conn_drain_insert
560  * is called only from ip_wsrv for the STREAMS case, and there can be only 1
561  * instance of ip_wsrv running on a queue at any time. conn_drain_tail can
562  * be simultaneously called from both ip_wsrv and ip_close.
563  *
564  * IPQOS notes:
565  *
566  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
567  * and IPQoS modules. IPPF includes hooks in IP at different control points
568  * (callout positions) which direct packets to IPQoS modules for policy
569  * processing. Policies, if present, are global.
570  *
571  * The callout positions are located in the following paths:
572  *		o local_in (packets destined for this host)
573  *		o local_out (packets orginating from this host )
574  *		o fwd_in  (packets forwarded by this m/c - inbound)
575  *		o fwd_out (packets forwarded by this m/c - outbound)
576  * Hooks at these callout points can be enabled/disabled using the ndd variable
577  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
578  * By default all the callout positions are enabled.
579  *
580  * Outbound (local_out)
581  * Hooks are placed in ip_wput_ire and ipsec_out_process.
582  *
583  * Inbound (local_in)
584  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
585  * TCP and UDP fanout routines.
586  *
587  * Forwarding (in and out)
588  * Hooks are placed in ip_rput_forward.
589  *
590  * IP Policy Framework processing (IPPF processing)
591  * Policy processing for a packet is initiated by ip_process, which ascertains
592  * that the classifier (ipgpc) is loaded and configured, failing which the
593  * packet resumes normal processing in IP. If the clasifier is present, the
594  * packet is acted upon by one or more IPQoS modules (action instances), per
595  * filters configured in ipgpc and resumes normal IP processing thereafter.
596  * An action instance can drop a packet in course of its processing.
597  *
598  * A boolean variable, ip_policy, is used in all the fanout routines that can
599  * invoke ip_process for a packet. This variable indicates if the packet should
600  * to be sent for policy processing. The variable is set to B_TRUE by default,
601  * i.e. when the routines are invoked in the normal ip procesing path for a
602  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
603  * ip_policy is set to B_FALSE for all the routines called in these two
604  * functions because, in the former case,  we don't process loopback traffic
605  * currently while in the latter, the packets have already been processed in
606  * icmp_inbound.
607  *
608  * Zones notes:
609  *
610  * The partitioning rules for networking are as follows:
611  * 1) Packets coming from a zone must have a source address belonging to that
612  * zone.
613  * 2) Packets coming from a zone can only be sent on a physical interface on
614  * which the zone has an IP address.
615  * 3) Between two zones on the same machine, packet delivery is only allowed if
616  * there's a matching route for the destination and zone in the forwarding
617  * table.
618  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
619  * different zones can bind to the same port with the wildcard address
620  * (INADDR_ANY).
621  *
622  * The granularity of interface partitioning is at the logical interface level.
623  * Therefore, every zone has its own IP addresses, and incoming packets can be
624  * attributed to a zone unambiguously. A logical interface is placed into a zone
625  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
626  * structure. Rule (1) is implemented by modifying the source address selection
627  * algorithm so that the list of eligible addresses is filtered based on the
628  * sending process zone.
629  *
630  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
631  * across all zones, depending on their type. Here is the break-up:
632  *
633  * IRE type				Shared/exclusive
634  * --------				----------------
635  * IRE_BROADCAST			Exclusive
636  * IRE_DEFAULT (default routes)		Shared (*)
637  * IRE_LOCAL				Exclusive (x)
638  * IRE_LOOPBACK				Exclusive
639  * IRE_PREFIX (net routes)		Shared (*)
640  * IRE_CACHE				Exclusive
641  * IRE_IF_NORESOLVER (interface routes)	Exclusive
642  * IRE_IF_RESOLVER (interface routes)	Exclusive
643  * IRE_HOST (host routes)		Shared (*)
644  *
645  * (*) A zone can only use a default or off-subnet route if the gateway is
646  * directly reachable from the zone, that is, if the gateway's address matches
647  * one of the zone's logical interfaces.
648  *
649  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
650  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
651  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
652  * address of the zone itself (the destination). Since IRE_LOCAL is used
653  * for communication between zones, ip_wput_ire has special logic to set
654  * the right source address when sending using an IRE_LOCAL.
655  *
656  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
657  * ire_cache_lookup restricts loopback using an IRE_LOCAL
658  * between zone to the case when L2 would have conceptually looped the packet
659  * back, i.e. the loopback which is required since neither Ethernet drivers
660  * nor Ethernet hardware loops them back. This is the case when the normal
661  * routes (ignoring IREs with different zoneids) would send out the packet on
662  * the same ill as the ill with which is IRE_LOCAL is associated.
663  *
664  * Multiple zones can share a common broadcast address; typically all zones
665  * share the 255.255.255.255 address. Incoming as well as locally originated
666  * broadcast packets must be dispatched to all the zones on the broadcast
667  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
668  * since some zones may not be on the 10.16.72/24 network. To handle this, each
669  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
670  * sent to every zone that has an IRE_BROADCAST entry for the destination
671  * address on the input ill, see conn_wantpacket().
672  *
673  * Applications in different zones can join the same multicast group address.
674  * For IPv4, group memberships are per-logical interface, so they're already
675  * inherently part of a zone. For IPv6, group memberships are per-physical
676  * interface, so we distinguish IPv6 group memberships based on group address,
677  * interface and zoneid. In both cases, received multicast packets are sent to
678  * every zone for which a group membership entry exists. On IPv6 we need to
679  * check that the target zone still has an address on the receiving physical
680  * interface; it could have been removed since the application issued the
681  * IPV6_JOIN_GROUP.
682  */
683 
684 /*
685  * Squeue Fanout flags:
686  *	0: No fanout.
687  *	1: Fanout across all squeues
688  */
689 boolean_t	ip_squeue_fanout = 0;
690 
691 /*
692  * Maximum dups allowed per packet.
693  */
694 uint_t ip_max_frag_dups = 10;
695 
696 #define	IS_SIMPLE_IPH(ipha)						\
697 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
698 
699 /* RFC 1122 Conformance */
700 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
701 
702 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
703 
704 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
705 
706 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
707 		    cred_t *credp, boolean_t isv6);
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
709 		    ipha_t **);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
712 		    ip_stack_t *);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int, ip_stack_t *);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
723 		    ip_stack_t *);
724 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
725 		    zoneid_t zoneid, ip_stack_t *);
726 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
727 static void	icmp_redirect(ill_t *, mblk_t *);
728 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
729 		    ip_stack_t *);
730 
731 static void	ip_arp_news(queue_t *, mblk_t *);
732 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
733 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
734 char		*ip_dot_addr(ipaddr_t, char *);
735 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
736 int		ip_close(queue_t *, int);
737 static char	*ip_dot_saddr(uchar_t *, char *);
738 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, ill_t *, zoneid_t);
740 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
741 		    boolean_t, boolean_t, zoneid_t);
742 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
743 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
744 static void	ip_lrput(queue_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
747 		    ip_stack_t *);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
755     ipndp_t *, size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
762     ip_stack_t *);
763 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
764 			    ire_t *, ip_stack_t *);
765 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
766 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
767 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
768     ip_stack_t *);
769 static boolean_t ip_rput_fragment(ill_t *, ill_t *, mblk_t **, ipha_t *,
770     uint32_t *, uint16_t *);
771 int		ip_snmp_get(queue_t *, mblk_t *, int);
772 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
773 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
775 		    ip_stack_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
777 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
778 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
779 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
780 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
781 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
782 		    ip_stack_t *ipst);
783 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
784 		    ip_stack_t *ipst);
785 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
786 		    ip_stack_t *ipst);
787 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
788 		    ip_stack_t *ipst);
789 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
790 		    ip_stack_t *ipst);
791 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
792 		    ip_stack_t *ipst);
793 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
794 		    ip_stack_t *ipst);
795 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
796 		    ip_stack_t *ipst);
797 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
798 		    ip_stack_t *ipst);
799 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
800 		    ip_stack_t *ipst);
801 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
802 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
803 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
804 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
805 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
806 static boolean_t	ip_source_route_included(ipha_t *);
807 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
808 
809 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
810 		    zoneid_t, ip_stack_t *, conn_t *);
811 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *,
812 		    mblk_t *);
813 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
814 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
815 		    zoneid_t, ip_stack_t *);
816 
817 static void	conn_drain_init(ip_stack_t *);
818 static void	conn_drain_fini(ip_stack_t *);
819 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
820 
821 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
822 static void	conn_setqfull(conn_t *);
823 static void	conn_clrqfull(conn_t *);
824 
825 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
826 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
827 static void	ip_stack_fini(netstackid_t stackid, void *arg);
828 
829 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
830     zoneid_t);
831 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
832     void *dummy_arg);
833 
834 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
835 
836 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
837     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
838     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
839 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
840 
841 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
842 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
843     caddr_t, cred_t *);
844 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
845     cred_t *, boolean_t);
846 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
847     caddr_t cp, cred_t *cr);
848 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
849     cred_t *);
850 static int	ip_squeue_switch(int);
851 
852 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
853 static void	ip_kstat_fini(netstackid_t, kstat_t *);
854 static int	ip_kstat_update(kstat_t *kp, int rw);
855 static void	*icmp_kstat_init(netstackid_t);
856 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
857 static int	icmp_kstat_update(kstat_t *kp, int rw);
858 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
859 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
860 
861 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
862     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
863 
864 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
865     ipha_t *, ill_t *, boolean_t, boolean_t);
866 
867 static void ipobs_init(ip_stack_t *);
868 static void ipobs_fini(ip_stack_t *);
869 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
870 
871 /* How long, in seconds, we allow frags to hang around. */
872 #define	IP_FRAG_TIMEOUT		15
873 #define	IPV6_FRAG_TIMEOUT	60
874 
875 /*
876  * Threshold which determines whether MDT should be used when
877  * generating IP fragments; payload size must be greater than
878  * this threshold for MDT to take place.
879  */
880 #define	IP_WPUT_FRAG_MDT_MIN	32768
881 
882 /* Setable in /etc/system only */
883 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
884 
885 static long ip_rput_pullups;
886 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
887 
888 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
889 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
890 
891 int	ip_debug;
892 
893 #ifdef DEBUG
894 uint32_t ipsechw_debug = 0;
895 #endif
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
901 
902 /*
903  * XXX following really should only be in a header. Would need more
904  * header and .c clean up first.
905  */
906 extern optdb_obj_t	ip_opt_obj;
907 
908 ulong_t ip_squeue_enter_unbound = 0;
909 
910 /*
911  * Named Dispatch Parameter Table.
912  * All of these are alterable, within the min/max values given, at run time.
913  */
914 static ipparam_t	lcl_param_arr[] = {
915 	/* min	max	value	name */
916 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
917 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
918 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
919 	{  0,	1,	0,	"ip_respond_to_timestamp"},
920 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
921 	{  0,	1,	1,	"ip_send_redirects"},
922 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
923 	{  0,	10,	0,	"ip_mrtdebug"},
924 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
925 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
926 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
927 	{  1,	255,	255,	"ip_def_ttl" },
928 	{  0,	1,	0,	"ip_forward_src_routed"},
929 	{  0,	256,	32,	"ip_wroff_extra" },
930 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
931 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
932 	{  0,	1,	1,	"ip_path_mtu_discovery" },
933 	{  0,	240,	30,	"ip_ignore_delete_time" },
934 	{  0,	1,	0,	"ip_ignore_redirect" },
935 	{  0,	1,	1,	"ip_output_queue" },
936 	{  1,	254,	1,	"ip_broadcast_ttl" },
937 	{  0,	99999,	100,	"ip_icmp_err_interval" },
938 	{  1,	99999,	10,	"ip_icmp_err_burst" },
939 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
940 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
941 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
942 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
943 	{  0,	1,	1,	"icmp_accept_clear_messages" },
944 	{  0,	1,	1,	"igmp_accept_clear_messages" },
945 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
946 				"ip_ndp_delay_first_probe_time"},
947 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
948 				"ip_ndp_max_unicast_solicit"},
949 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
950 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
951 	{  0,	1,	0,	"ip6_forward_src_routed"},
952 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
953 	{  0,	1,	1,	"ip6_send_redirects"},
954 	{  0,	1,	0,	"ip6_ignore_redirect" },
955 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
956 
957 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
958 
959 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
960 
961 	{  0,	1,	1,	"pim_accept_clear_messages" },
962 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
963 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
964 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
965 	{  0,	15,	0,	"ip_policy_mask" },
966 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
967 	{  0,	255,	1,	"ip_multirt_ttl" },
968 	{  0,	1,	1,	"ip_multidata_outbound" },
969 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
970 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
971 	{  0,	1000,	1,	"ip_max_temp_defend" },
972 	{  0,	1000,	3,	"ip_max_defend" },
973 	{  0,	999999,	30,	"ip_defend_interval" },
974 	{  0,	3600000, 300000, "ip_dup_recovery" },
975 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
976 	{  0,	1,	1,	"ip_lso_outbound" },
977 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
978 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
979 	{ 68,	65535,	576,	"ip_pmtu_min" },
980 #ifdef DEBUG
981 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
982 #else
983 	{  0,	0,	0,	"" },
984 #endif
985 };
986 
987 /*
988  * Extended NDP table
989  * The addresses for the first two are filled in to be ips_ip_g_forward
990  * and ips_ipv6_forward at init time.
991  */
992 static ipndp_t	lcl_ndp_arr[] = {
993 	/* getf			setf		data			name */
994 #define	IPNDP_IP_FORWARDING_OFFSET	0
995 	{  ip_param_generic_get,	ip_forward_set,	NULL,
996 	    "ip_forwarding" },
997 #define	IPNDP_IP6_FORWARDING_OFFSET	1
998 	{  ip_param_generic_get,	ip_forward_set,	NULL,
999 	    "ip6_forwarding" },
1000 	{ ip_param_generic_get, ip_input_proc_set,
1001 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1002 	{ ip_param_generic_get, ip_int_set,
1003 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1004 #define	IPNDP_CGTP_FILTER_OFFSET	4
1005 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1006 	    "ip_cgtp_filter" },
1007 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1008 	    "ip_debug" },
1009 };
1010 
1011 /*
1012  * Table of IP ioctls encoding the various properties of the ioctl and
1013  * indexed based on the last byte of the ioctl command. Occasionally there
1014  * is a clash, and there is more than 1 ioctl with the same last byte.
1015  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1016  * ioctls are encoded in the misc table. An entry in the ndx table is
1017  * retrieved by indexing on the last byte of the ioctl command and comparing
1018  * the ioctl command with the value in the ndx table. In the event of a
1019  * mismatch the misc table is then searched sequentially for the desired
1020  * ioctl command.
1021  *
1022  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1023  */
1024 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1025 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1037 			MISC_CMD, ip_siocaddrt, NULL },
1038 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1039 			MISC_CMD, ip_siocdelrt, NULL },
1040 
1041 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1042 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1043 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1044 			IF_CMD, ip_sioctl_get_addr, NULL },
1045 
1046 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1047 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1048 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1049 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1050 
1051 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1052 			IPI_PRIV | IPI_WR,
1053 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1054 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1055 			IPI_MODOK | IPI_GET_CMD,
1056 			IF_CMD, ip_sioctl_get_flags, NULL },
1057 
1058 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 
1061 	/* copyin size cannot be coded for SIOCGIFCONF */
1062 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1063 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1064 
1065 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1066 			IF_CMD, ip_sioctl_mtu, NULL },
1067 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1068 			IF_CMD, ip_sioctl_get_mtu, NULL },
1069 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1070 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1071 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1072 			IF_CMD, ip_sioctl_brdaddr, NULL },
1073 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1074 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1075 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1076 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1077 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1078 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1079 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1080 			IF_CMD, ip_sioctl_metric, NULL },
1081 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 
1083 	/* See 166-168 below for extended SIOC*XARP ioctls */
1084 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1085 			ARP_CMD, ip_sioctl_arp, NULL },
1086 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1087 			ARP_CMD, ip_sioctl_arp, NULL },
1088 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1089 			ARP_CMD, ip_sioctl_arp, NULL },
1090 
1091 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1114 			MISC_CMD, if_unitsel, if_unitsel_restart },
1115 
1116 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 
1135 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1136 			IPI_PRIV | IPI_WR | IPI_MODOK,
1137 			IF_CMD, ip_sioctl_sifname, NULL },
1138 
1139 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 
1153 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1154 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1155 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1156 			IF_CMD, ip_sioctl_get_muxid, NULL },
1157 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1158 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1159 
1160 	/* Both if and lif variants share same func */
1161 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1162 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1163 	/* Both if and lif variants share same func */
1164 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1165 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1166 
1167 	/* copyin size cannot be coded for SIOCGIFCONF */
1168 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1169 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1170 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 
1188 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1189 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1190 			ip_sioctl_removeif_restart },
1191 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1192 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_addif, NULL },
1194 #define	SIOCLIFADDR_NDX 112
1195 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1197 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1198 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1199 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1200 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1201 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1202 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1203 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1204 			IPI_PRIV | IPI_WR,
1205 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1206 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1207 			IPI_GET_CMD | IPI_MODOK,
1208 			LIF_CMD, ip_sioctl_get_flags, NULL },
1209 
1210 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1212 
1213 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1214 			ip_sioctl_get_lifconf, NULL },
1215 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1216 			LIF_CMD, ip_sioctl_mtu, NULL },
1217 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1218 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1219 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1220 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1221 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1222 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1223 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1224 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1225 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1226 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1227 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1228 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1229 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1230 			LIF_CMD, ip_sioctl_metric, NULL },
1231 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1232 			IPI_PRIV | IPI_WR | IPI_MODOK,
1233 			LIF_CMD, ip_sioctl_slifname,
1234 			ip_sioctl_slifname_restart },
1235 
1236 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1237 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1238 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1239 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1240 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1241 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1242 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1243 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1244 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1245 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1246 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1247 			LIF_CMD, ip_sioctl_token, NULL },
1248 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1249 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1250 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1251 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1252 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1253 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1254 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1255 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1256 
1257 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1258 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1259 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1260 			LIF_CMD, ip_siocdelndp_v6, NULL },
1261 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1262 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1263 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1264 			LIF_CMD, ip_siocsetndp_v6, NULL },
1265 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1266 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1267 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1268 			MISC_CMD, ip_sioctl_tonlink, NULL },
1269 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1270 			MISC_CMD, ip_sioctl_tmysite, NULL },
1271 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1272 			TUN_CMD, ip_sioctl_tunparam, NULL },
1273 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1274 		    IPI_PRIV | IPI_WR,
1275 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1276 
1277 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1278 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1279 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1280 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1281 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1282 
1283 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1284 
1285 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1286 			LIF_CMD, ip_sioctl_get_binding, NULL },
1287 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1288 			IPI_PRIV | IPI_WR,
1289 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1290 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1291 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1292 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1293 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1294 
1295 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1296 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1298 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1299 
1300 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1301 
1302 	/* These are handled in ip_sioctl_copyin_setup itself */
1303 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1304 			MISC_CMD, NULL, NULL },
1305 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1306 			MISC_CMD, NULL, NULL },
1307 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1308 
1309 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1310 			ip_sioctl_get_lifconf, NULL },
1311 
1312 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1313 			XARP_CMD, ip_sioctl_arp, NULL },
1314 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1315 			XARP_CMD, ip_sioctl_arp, NULL },
1316 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1317 			XARP_CMD, ip_sioctl_arp, NULL },
1318 
1319 	/* SIOCPOPSOCKFS is not handled by IP */
1320 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1321 
1322 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1323 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1324 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1325 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1326 			ip_sioctl_slifzone_restart },
1327 	/* 172-174 are SCTP ioctls and not handled by IP */
1328 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1329 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1330 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1331 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1332 			IPI_GET_CMD, LIF_CMD,
1333 			ip_sioctl_get_lifusesrc, 0 },
1334 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1335 			IPI_PRIV | IPI_WR,
1336 			LIF_CMD, ip_sioctl_slifusesrc,
1337 			NULL },
1338 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1339 			ip_sioctl_get_lifsrcof, NULL },
1340 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1341 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1342 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1343 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1344 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1345 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1346 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1347 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1348 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1349 	/* SIOCSENABLESDP is handled by SDP */
1350 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1351 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1352 };
1353 
1354 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1355 
1356 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1357 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1358 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1359 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1360 		TUN_CMD, ip_sioctl_tunparam, NULL },
1361 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1362 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1363 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1364 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1365 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1366 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1367 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1368 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1369 		MISC_CMD, mrt_ioctl},
1370 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1371 		MISC_CMD, mrt_ioctl},
1372 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1373 		MISC_CMD, mrt_ioctl}
1374 };
1375 
1376 int ip_misc_ioctl_count =
1377     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1378 
1379 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1380 					/* Settable in /etc/system */
1381 /* Defined in ip_ire.c */
1382 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1383 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1384 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1385 
1386 static nv_t	ire_nv_arr[] = {
1387 	{ IRE_BROADCAST, "BROADCAST" },
1388 	{ IRE_LOCAL, "LOCAL" },
1389 	{ IRE_LOOPBACK, "LOOPBACK" },
1390 	{ IRE_CACHE, "CACHE" },
1391 	{ IRE_DEFAULT, "DEFAULT" },
1392 	{ IRE_PREFIX, "PREFIX" },
1393 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1394 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1395 	{ IRE_HOST, "HOST" },
1396 	{ 0 }
1397 };
1398 
1399 nv_t	*ire_nv_tbl = ire_nv_arr;
1400 
1401 /* Simple ICMP IP Header Template */
1402 static ipha_t icmp_ipha = {
1403 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1404 };
1405 
1406 struct module_info ip_mod_info = {
1407 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1408 	IP_MOD_LOWAT
1409 };
1410 
1411 /*
1412  * Duplicate static symbols within a module confuses mdb; so we avoid the
1413  * problem by making the symbols here distinct from those in udp.c.
1414  */
1415 
1416 /*
1417  * Entry points for IP as a device and as a module.
1418  * FIXME: down the road we might want a separate module and driver qinit.
1419  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1420  */
1421 static struct qinit iprinitv4 = {
1422 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1423 	&ip_mod_info
1424 };
1425 
1426 struct qinit iprinitv6 = {
1427 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1428 	&ip_mod_info
1429 };
1430 
1431 static struct qinit ipwinitv4 = {
1432 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1433 	&ip_mod_info
1434 };
1435 
1436 struct qinit ipwinitv6 = {
1437 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1438 	&ip_mod_info
1439 };
1440 
1441 static struct qinit iplrinit = {
1442 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1443 	&ip_mod_info
1444 };
1445 
1446 static struct qinit iplwinit = {
1447 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1448 	&ip_mod_info
1449 };
1450 
1451 /* For AF_INET aka /dev/ip */
1452 struct streamtab ipinfov4 = {
1453 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1454 };
1455 
1456 /* For AF_INET6 aka /dev/ip6 */
1457 struct streamtab ipinfov6 = {
1458 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1459 };
1460 
1461 #ifdef	DEBUG
1462 static boolean_t skip_sctp_cksum = B_FALSE;
1463 #endif
1464 
1465 /*
1466  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1467  * ip_rput_v6(), ip_output(), etc.  If the message
1468  * block already has a M_CTL at the front of it, then simply set the zoneid
1469  * appropriately.
1470  */
1471 mblk_t *
1472 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1473 {
1474 	mblk_t		*first_mp;
1475 	ipsec_out_t	*io;
1476 
1477 	ASSERT(zoneid != ALL_ZONES);
1478 	if (mp->b_datap->db_type == M_CTL) {
1479 		io = (ipsec_out_t *)mp->b_rptr;
1480 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1481 		io->ipsec_out_zoneid = zoneid;
1482 		return (mp);
1483 	}
1484 
1485 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1486 	if (first_mp == NULL)
1487 		return (NULL);
1488 	io = (ipsec_out_t *)first_mp->b_rptr;
1489 	/* This is not a secure packet */
1490 	io->ipsec_out_secure = B_FALSE;
1491 	io->ipsec_out_zoneid = zoneid;
1492 	first_mp->b_cont = mp;
1493 	return (first_mp);
1494 }
1495 
1496 /*
1497  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1498  */
1499 mblk_t *
1500 ip_copymsg(mblk_t *mp)
1501 {
1502 	mblk_t *nmp;
1503 	ipsec_info_t *in;
1504 
1505 	if (mp->b_datap->db_type != M_CTL)
1506 		return (copymsg(mp));
1507 
1508 	in = (ipsec_info_t *)mp->b_rptr;
1509 
1510 	/*
1511 	 * Note that M_CTL is also used for delivering ICMP error messages
1512 	 * upstream to transport layers.
1513 	 */
1514 	if (in->ipsec_info_type != IPSEC_OUT &&
1515 	    in->ipsec_info_type != IPSEC_IN)
1516 		return (copymsg(mp));
1517 
1518 	nmp = copymsg(mp->b_cont);
1519 
1520 	if (in->ipsec_info_type == IPSEC_OUT) {
1521 		return (ipsec_out_tag(mp, nmp,
1522 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1523 	} else {
1524 		return (ipsec_in_tag(mp, nmp,
1525 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1526 	}
1527 }
1528 
1529 /* Generate an ICMP fragmentation needed message. */
1530 static void
1531 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1532     ip_stack_t *ipst)
1533 {
1534 	icmph_t	icmph;
1535 	mblk_t *first_mp;
1536 	boolean_t mctl_present;
1537 
1538 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1539 
1540 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1541 		if (mctl_present)
1542 			freeb(first_mp);
1543 		return;
1544 	}
1545 
1546 	bzero(&icmph, sizeof (icmph_t));
1547 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1548 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1549 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1550 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1551 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1552 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1553 	    ipst);
1554 }
1555 
1556 /*
1557  * icmp_inbound deals with ICMP messages in the following ways.
1558  *
1559  * 1) It needs to send a reply back and possibly delivering it
1560  *    to the "interested" upper clients.
1561  * 2) It needs to send it to the upper clients only.
1562  * 3) It needs to change some values in IP only.
1563  * 4) It needs to change some values in IP and upper layers e.g TCP.
1564  *
1565  * We need to accomodate icmp messages coming in clear until we get
1566  * everything secure from the wire. If icmp_accept_clear_messages
1567  * is zero we check with the global policy and act accordingly. If
1568  * it is non-zero, we accept the message without any checks. But
1569  * *this does not mean* that this will be delivered to the upper
1570  * clients. By accepting we might send replies back, change our MTU
1571  * value etc. but delivery to the ULP/clients depends on their policy
1572  * dispositions.
1573  *
1574  * We handle the above 4 cases in the context of IPsec in the
1575  * following way :
1576  *
1577  * 1) Send the reply back in the same way as the request came in.
1578  *    If it came in encrypted, it goes out encrypted. If it came in
1579  *    clear, it goes out in clear. Thus, this will prevent chosen
1580  *    plain text attack.
1581  * 2) The client may or may not expect things to come in secure.
1582  *    If it comes in secure, the policy constraints are checked
1583  *    before delivering it to the upper layers. If it comes in
1584  *    clear, ipsec_inbound_accept_clear will decide whether to
1585  *    accept this in clear or not. In both the cases, if the returned
1586  *    message (IP header + 8 bytes) that caused the icmp message has
1587  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1588  *    sending up. If there are only 8 bytes of returned message, then
1589  *    upper client will not be notified.
1590  * 3) Check with global policy to see whether it matches the constaints.
1591  *    But this will be done only if icmp_accept_messages_in_clear is
1592  *    zero.
1593  * 4) If we need to change both in IP and ULP, then the decision taken
1594  *    while affecting the values in IP and while delivering up to TCP
1595  *    should be the same.
1596  *
1597  * 	There are two cases.
1598  *
1599  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1600  *	   failed), we will not deliver it to the ULP, even though they
1601  *	   are *willing* to accept in *clear*. This is fine as our global
1602  *	   disposition to icmp messages asks us reject the datagram.
1603  *
1604  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1605  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1606  *	   to deliver it to ULP (policy failed), it can lead to
1607  *	   consistency problems. The cases known at this time are
1608  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1609  *	   values :
1610  *
1611  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1612  *	     and Upper layer rejects. Then the communication will
1613  *	     come to a stop. This is solved by making similar decisions
1614  *	     at both levels. Currently, when we are unable to deliver
1615  *	     to the Upper Layer (due to policy failures) while IP has
1616  *	     adjusted ire_max_frag, the next outbound datagram would
1617  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1618  *	     will be with the right level of protection. Thus the right
1619  *	     value will be communicated even if we are not able to
1620  *	     communicate when we get from the wire initially. But this
1621  *	     assumes there would be at least one outbound datagram after
1622  *	     IP has adjusted its ire_max_frag value. To make things
1623  *	     simpler, we accept in clear after the validation of
1624  *	     AH/ESP headers.
1625  *
1626  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1627  *	     upper layer depending on the level of protection the upper
1628  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1629  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1630  *	     should be accepted in clear when the Upper layer expects secure.
1631  *	     Thus the communication may get aborted by some bad ICMP
1632  *	     packets.
1633  *
1634  * IPQoS Notes:
1635  * The only instance when a packet is sent for processing is when there
1636  * isn't an ICMP client and if we are interested in it.
1637  * If there is a client, IPPF processing will take place in the
1638  * ip_fanout_proto routine.
1639  *
1640  * Zones notes:
1641  * The packet is only processed in the context of the specified zone: typically
1642  * only this zone will reply to an echo request, and only interested clients in
1643  * this zone will receive a copy of the packet. This means that the caller must
1644  * call icmp_inbound() for each relevant zone.
1645  */
1646 static void
1647 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1648     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1649     ill_t *recv_ill, zoneid_t zoneid)
1650 {
1651 	icmph_t	*icmph;
1652 	ipha_t	*ipha;
1653 	int	iph_hdr_length;
1654 	int	hdr_length;
1655 	boolean_t	interested;
1656 	uint32_t	ts;
1657 	uchar_t	*wptr;
1658 	ipif_t	*ipif;
1659 	mblk_t *first_mp;
1660 	ipsec_in_t *ii;
1661 	timestruc_t now;
1662 	uint32_t ill_index;
1663 	ip_stack_t *ipst;
1664 
1665 	ASSERT(ill != NULL);
1666 	ipst = ill->ill_ipst;
1667 
1668 	first_mp = mp;
1669 	if (mctl_present) {
1670 		mp = first_mp->b_cont;
1671 		ASSERT(mp != NULL);
1672 	}
1673 
1674 	ipha = (ipha_t *)mp->b_rptr;
1675 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1676 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1677 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1678 		if (first_mp == NULL)
1679 			return;
1680 	}
1681 
1682 	/*
1683 	 * On a labeled system, we have to check whether the zone itself is
1684 	 * permitted to receive raw traffic.
1685 	 */
1686 	if (is_system_labeled()) {
1687 		if (zoneid == ALL_ZONES)
1688 			zoneid = tsol_packet_to_zoneid(mp);
1689 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1690 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1691 			    zoneid));
1692 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1693 			freemsg(first_mp);
1694 			return;
1695 		}
1696 	}
1697 
1698 	/*
1699 	 * We have accepted the ICMP message. It means that we will
1700 	 * respond to the packet if needed. It may not be delivered
1701 	 * to the upper client depending on the policy constraints
1702 	 * and the disposition in ipsec_inbound_accept_clear.
1703 	 */
1704 
1705 	ASSERT(ill != NULL);
1706 
1707 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1708 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1709 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1710 		/* Last chance to get real. */
1711 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1712 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1713 			freemsg(first_mp);
1714 			return;
1715 		}
1716 		/* Refresh iph following the pullup. */
1717 		ipha = (ipha_t *)mp->b_rptr;
1718 	}
1719 	/* ICMP header checksum, including checksum field, should be zero. */
1720 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1721 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1722 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1723 		freemsg(first_mp);
1724 		return;
1725 	}
1726 	/* The IP header will always be a multiple of four bytes */
1727 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1728 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1729 	    icmph->icmph_code));
1730 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1731 	/* We will set "interested" to "true" if we want a copy */
1732 	interested = B_FALSE;
1733 	switch (icmph->icmph_type) {
1734 	case ICMP_ECHO_REPLY:
1735 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1736 		break;
1737 	case ICMP_DEST_UNREACHABLE:
1738 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1739 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1740 		interested = B_TRUE;	/* Pass up to transport */
1741 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1742 		break;
1743 	case ICMP_SOURCE_QUENCH:
1744 		interested = B_TRUE;	/* Pass up to transport */
1745 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1746 		break;
1747 	case ICMP_REDIRECT:
1748 		if (!ipst->ips_ip_ignore_redirect)
1749 			interested = B_TRUE;
1750 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1751 		break;
1752 	case ICMP_ECHO_REQUEST:
1753 		/*
1754 		 * Whether to respond to echo requests that come in as IP
1755 		 * broadcasts or as IP multicast is subject to debate
1756 		 * (what isn't?).  We aim to please, you pick it.
1757 		 * Default is do it.
1758 		 */
1759 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1760 			/* unicast: always respond */
1761 			interested = B_TRUE;
1762 		} else if (CLASSD(ipha->ipha_dst)) {
1763 			/* multicast: respond based on tunable */
1764 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1765 		} else if (broadcast) {
1766 			/* broadcast: respond based on tunable */
1767 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1768 		}
1769 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1770 		break;
1771 	case ICMP_ROUTER_ADVERTISEMENT:
1772 	case ICMP_ROUTER_SOLICITATION:
1773 		break;
1774 	case ICMP_TIME_EXCEEDED:
1775 		interested = B_TRUE;	/* Pass up to transport */
1776 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1777 		break;
1778 	case ICMP_PARAM_PROBLEM:
1779 		interested = B_TRUE;	/* Pass up to transport */
1780 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1781 		break;
1782 	case ICMP_TIME_STAMP_REQUEST:
1783 		/* Response to Time Stamp Requests is local policy. */
1784 		if (ipst->ips_ip_g_resp_to_timestamp &&
1785 		    /* So is whether to respond if it was an IP broadcast. */
1786 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1787 			int tstamp_len = 3 * sizeof (uint32_t);
1788 
1789 			if (wptr +  tstamp_len > mp->b_wptr) {
1790 				if (!pullupmsg(mp, wptr + tstamp_len -
1791 				    mp->b_rptr)) {
1792 					BUMP_MIB(ill->ill_ip_mib,
1793 					    ipIfStatsInDiscards);
1794 					freemsg(first_mp);
1795 					return;
1796 				}
1797 				/* Refresh ipha following the pullup. */
1798 				ipha = (ipha_t *)mp->b_rptr;
1799 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1800 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1801 			}
1802 			interested = B_TRUE;
1803 		}
1804 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1805 		break;
1806 	case ICMP_TIME_STAMP_REPLY:
1807 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1808 		break;
1809 	case ICMP_INFO_REQUEST:
1810 		/* Per RFC 1122 3.2.2.7, ignore this. */
1811 	case ICMP_INFO_REPLY:
1812 		break;
1813 	case ICMP_ADDRESS_MASK_REQUEST:
1814 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1815 		    !broadcast) &&
1816 		    /* TODO m_pullup of complete header? */
1817 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1818 			interested = B_TRUE;
1819 		}
1820 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1821 		break;
1822 	case ICMP_ADDRESS_MASK_REPLY:
1823 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1824 		break;
1825 	default:
1826 		interested = B_TRUE;	/* Pass up to transport */
1827 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1828 		break;
1829 	}
1830 	/* See if there is an ICMP client. */
1831 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1832 		/* If there is an ICMP client and we want one too, copy it. */
1833 		mblk_t *first_mp1;
1834 
1835 		if (!interested) {
1836 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1837 			    ip_policy, recv_ill, zoneid);
1838 			return;
1839 		}
1840 		first_mp1 = ip_copymsg(first_mp);
1841 		if (first_mp1 != NULL) {
1842 			ip_fanout_proto(q, first_mp1, ill, ipha,
1843 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1844 		}
1845 	} else if (!interested) {
1846 		freemsg(first_mp);
1847 		return;
1848 	} else {
1849 		/*
1850 		 * Initiate policy processing for this packet if ip_policy
1851 		 * is true.
1852 		 */
1853 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1854 			ill_index = ill->ill_phyint->phyint_ifindex;
1855 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1856 			if (mp == NULL) {
1857 				if (mctl_present) {
1858 					freeb(first_mp);
1859 				}
1860 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1861 				return;
1862 			}
1863 		}
1864 	}
1865 	/* We want to do something with it. */
1866 	/* Check db_ref to make sure we can modify the packet. */
1867 	if (mp->b_datap->db_ref > 1) {
1868 		mblk_t	*first_mp1;
1869 
1870 		first_mp1 = ip_copymsg(first_mp);
1871 		freemsg(first_mp);
1872 		if (!first_mp1) {
1873 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1874 			return;
1875 		}
1876 		first_mp = first_mp1;
1877 		if (mctl_present) {
1878 			mp = first_mp->b_cont;
1879 			ASSERT(mp != NULL);
1880 		} else {
1881 			mp = first_mp;
1882 		}
1883 		ipha = (ipha_t *)mp->b_rptr;
1884 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1885 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1886 	}
1887 	switch (icmph->icmph_type) {
1888 	case ICMP_ADDRESS_MASK_REQUEST:
1889 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1890 		if (ipif == NULL) {
1891 			freemsg(first_mp);
1892 			return;
1893 		}
1894 		/*
1895 		 * outging interface must be IPv4
1896 		 */
1897 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1898 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1899 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1900 		ipif_refrele(ipif);
1901 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1902 		break;
1903 	case ICMP_ECHO_REQUEST:
1904 		icmph->icmph_type = ICMP_ECHO_REPLY;
1905 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1906 		break;
1907 	case ICMP_TIME_STAMP_REQUEST: {
1908 		uint32_t *tsp;
1909 
1910 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1911 		tsp = (uint32_t *)wptr;
1912 		tsp++;		/* Skip past 'originate time' */
1913 		/* Compute # of milliseconds since midnight */
1914 		gethrestime(&now);
1915 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1916 		    now.tv_nsec / (NANOSEC / MILLISEC);
1917 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1918 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1919 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1920 		break;
1921 	}
1922 	default:
1923 		ipha = (ipha_t *)&icmph[1];
1924 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1925 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1926 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1927 				freemsg(first_mp);
1928 				return;
1929 			}
1930 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1931 			ipha = (ipha_t *)&icmph[1];
1932 		}
1933 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1934 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1935 			freemsg(first_mp);
1936 			return;
1937 		}
1938 		hdr_length = IPH_HDR_LENGTH(ipha);
1939 		if (hdr_length < sizeof (ipha_t)) {
1940 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1941 			freemsg(first_mp);
1942 			return;
1943 		}
1944 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1945 			if (!pullupmsg(mp,
1946 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1947 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1948 				freemsg(first_mp);
1949 				return;
1950 			}
1951 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1952 			ipha = (ipha_t *)&icmph[1];
1953 		}
1954 		switch (icmph->icmph_type) {
1955 		case ICMP_REDIRECT:
1956 			/*
1957 			 * As there is no upper client to deliver, we don't
1958 			 * need the first_mp any more.
1959 			 */
1960 			if (mctl_present) {
1961 				freeb(first_mp);
1962 			}
1963 			icmp_redirect(ill, mp);
1964 			return;
1965 		case ICMP_DEST_UNREACHABLE:
1966 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1967 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1968 				    zoneid, mp, iph_hdr_length, ipst)) {
1969 					freemsg(first_mp);
1970 					return;
1971 				}
1972 				/*
1973 				 * icmp_inbound_too_big() may alter mp.
1974 				 * Resynch ipha and icmph accordingly.
1975 				 */
1976 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1977 				ipha = (ipha_t *)&icmph[1];
1978 			}
1979 			/* FALLTHRU */
1980 		default :
1981 			/*
1982 			 * IPQoS notes: Since we have already done IPQoS
1983 			 * processing we don't want to do it again in
1984 			 * the fanout routines called by
1985 			 * icmp_inbound_error_fanout, hence the last
1986 			 * argument, ip_policy, is B_FALSE.
1987 			 */
1988 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1989 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1990 			    B_FALSE, recv_ill, zoneid);
1991 		}
1992 		return;
1993 	}
1994 	/* Send out an ICMP packet */
1995 	icmph->icmph_checksum = 0;
1996 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1997 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1998 		ipif_t	*ipif_chosen;
1999 		/*
2000 		 * Make it look like it was directed to us, so we don't look
2001 		 * like a fool with a broadcast or multicast source address.
2002 		 */
2003 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2004 		/*
2005 		 * Make sure that we haven't grabbed an interface that's DOWN.
2006 		 */
2007 		if (ipif != NULL) {
2008 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2009 			    ipha->ipha_src, zoneid);
2010 			if (ipif_chosen != NULL) {
2011 				ipif_refrele(ipif);
2012 				ipif = ipif_chosen;
2013 			}
2014 		}
2015 		if (ipif == NULL) {
2016 			ip0dbg(("icmp_inbound: "
2017 			    "No source for broadcast/multicast:\n"
2018 			    "\tsrc 0x%x dst 0x%x ill %p "
2019 			    "ipif_lcl_addr 0x%x\n",
2020 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2021 			    (void *)ill,
2022 			    ill->ill_ipif->ipif_lcl_addr));
2023 			freemsg(first_mp);
2024 			return;
2025 		}
2026 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2027 		ipha->ipha_dst = ipif->ipif_src_addr;
2028 		ipif_refrele(ipif);
2029 	}
2030 	/* Reset time to live. */
2031 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2032 	{
2033 		/* Swap source and destination addresses */
2034 		ipaddr_t tmp;
2035 
2036 		tmp = ipha->ipha_src;
2037 		ipha->ipha_src = ipha->ipha_dst;
2038 		ipha->ipha_dst = tmp;
2039 	}
2040 	ipha->ipha_ident = 0;
2041 	if (!IS_SIMPLE_IPH(ipha))
2042 		icmp_options_update(ipha);
2043 
2044 	if (!mctl_present) {
2045 		/*
2046 		 * This packet should go out the same way as it
2047 		 * came in i.e in clear. To make sure that global
2048 		 * policy will not be applied to this in ip_wput_ire,
2049 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2050 		 */
2051 		ASSERT(first_mp == mp);
2052 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2053 		if (first_mp == NULL) {
2054 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2055 			freemsg(mp);
2056 			return;
2057 		}
2058 		ii = (ipsec_in_t *)first_mp->b_rptr;
2059 
2060 		/* This is not a secure packet */
2061 		ii->ipsec_in_secure = B_FALSE;
2062 		first_mp->b_cont = mp;
2063 	} else {
2064 		ii = (ipsec_in_t *)first_mp->b_rptr;
2065 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2066 	}
2067 	ii->ipsec_in_zoneid = zoneid;
2068 	ASSERT(zoneid != ALL_ZONES);
2069 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2070 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2071 		return;
2072 	}
2073 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2074 	put(WR(q), first_mp);
2075 }
2076 
2077 static ipaddr_t
2078 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2079 {
2080 	conn_t *connp;
2081 	connf_t *connfp;
2082 	ipaddr_t nexthop_addr = INADDR_ANY;
2083 	int hdr_length = IPH_HDR_LENGTH(ipha);
2084 	uint16_t *up;
2085 	uint32_t ports;
2086 	ip_stack_t *ipst = ill->ill_ipst;
2087 
2088 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2089 	switch (ipha->ipha_protocol) {
2090 		case IPPROTO_TCP:
2091 		{
2092 			tcph_t *tcph;
2093 
2094 			/* do a reverse lookup */
2095 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2096 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2097 			    TCPS_LISTEN, ipst);
2098 			break;
2099 		}
2100 		case IPPROTO_UDP:
2101 		{
2102 			uint32_t dstport, srcport;
2103 
2104 			((uint16_t *)&ports)[0] = up[1];
2105 			((uint16_t *)&ports)[1] = up[0];
2106 
2107 			/* Extract ports in net byte order */
2108 			dstport = htons(ntohl(ports) & 0xFFFF);
2109 			srcport = htons(ntohl(ports) >> 16);
2110 
2111 			connfp = &ipst->ips_ipcl_udp_fanout[
2112 			    IPCL_UDP_HASH(dstport, ipst)];
2113 			mutex_enter(&connfp->connf_lock);
2114 			connp = connfp->connf_head;
2115 
2116 			/* do a reverse lookup */
2117 			while ((connp != NULL) &&
2118 			    (!IPCL_UDP_MATCH(connp, dstport,
2119 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2120 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2121 				connp = connp->conn_next;
2122 			}
2123 			if (connp != NULL)
2124 				CONN_INC_REF(connp);
2125 			mutex_exit(&connfp->connf_lock);
2126 			break;
2127 		}
2128 		case IPPROTO_SCTP:
2129 		{
2130 			in6_addr_t map_src, map_dst;
2131 
2132 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2133 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2134 			((uint16_t *)&ports)[0] = up[1];
2135 			((uint16_t *)&ports)[1] = up[0];
2136 
2137 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2138 			    zoneid, ipst->ips_netstack->netstack_sctp);
2139 			if (connp == NULL) {
2140 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2141 				    zoneid, ports, ipha, ipst);
2142 			} else {
2143 				CONN_INC_REF(connp);
2144 				SCTP_REFRELE(CONN2SCTP(connp));
2145 			}
2146 			break;
2147 		}
2148 		default:
2149 		{
2150 			ipha_t ripha;
2151 
2152 			ripha.ipha_src = ipha->ipha_dst;
2153 			ripha.ipha_dst = ipha->ipha_src;
2154 			ripha.ipha_protocol = ipha->ipha_protocol;
2155 
2156 			connfp = &ipst->ips_ipcl_proto_fanout[
2157 			    ipha->ipha_protocol];
2158 			mutex_enter(&connfp->connf_lock);
2159 			connp = connfp->connf_head;
2160 			for (connp = connfp->connf_head; connp != NULL;
2161 			    connp = connp->conn_next) {
2162 				if (IPCL_PROTO_MATCH(connp,
2163 				    ipha->ipha_protocol, &ripha, ill,
2164 				    0, zoneid)) {
2165 					CONN_INC_REF(connp);
2166 					break;
2167 				}
2168 			}
2169 			mutex_exit(&connfp->connf_lock);
2170 		}
2171 	}
2172 	if (connp != NULL) {
2173 		if (connp->conn_nexthop_set)
2174 			nexthop_addr = connp->conn_nexthop_v4;
2175 		CONN_DEC_REF(connp);
2176 	}
2177 	return (nexthop_addr);
2178 }
2179 
2180 /* Table from RFC 1191 */
2181 static int icmp_frag_size_table[] =
2182 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2183 
2184 /*
2185  * Process received ICMP Packet too big.
2186  * After updating any IRE it does the fanout to any matching transport streams.
2187  * Assumes the message has been pulled up till the IP header that caused
2188  * the error.
2189  *
2190  * Returns B_FALSE on failure and B_TRUE on success.
2191  */
2192 static boolean_t
2193 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2194     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2195     ip_stack_t *ipst)
2196 {
2197 	ire_t	*ire, *first_ire;
2198 	int	mtu, orig_mtu;
2199 	int	hdr_length;
2200 	ipaddr_t nexthop_addr;
2201 	boolean_t disable_pmtud;
2202 
2203 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2204 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2205 	ASSERT(ill != NULL);
2206 
2207 	hdr_length = IPH_HDR_LENGTH(ipha);
2208 
2209 	/* Drop if the original packet contained a source route */
2210 	if (ip_source_route_included(ipha)) {
2211 		return (B_FALSE);
2212 	}
2213 	/*
2214 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2215 	 * header.
2216 	 */
2217 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2218 	    mp->b_wptr) {
2219 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2220 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2221 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2222 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2223 			return (B_FALSE);
2224 		}
2225 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2226 		ipha = (ipha_t *)&icmph[1];
2227 	}
2228 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2229 	if (nexthop_addr != INADDR_ANY) {
2230 		/* nexthop set */
2231 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2232 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2233 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2234 	} else {
2235 		/* nexthop not set */
2236 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2237 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2238 	}
2239 
2240 	if (!first_ire) {
2241 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2242 		    ntohl(ipha->ipha_dst)));
2243 		return (B_FALSE);
2244 	}
2245 
2246 	/* Check for MTU discovery advice as described in RFC 1191 */
2247 	mtu = ntohs(icmph->icmph_du_mtu);
2248 	orig_mtu = mtu;
2249 	disable_pmtud = B_FALSE;
2250 
2251 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2252 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2253 	    ire = ire->ire_next) {
2254 		/*
2255 		 * Look for the connection to which this ICMP message is
2256 		 * directed. If it has the IP_NEXTHOP option set, then the
2257 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2258 		 * option. Else the search is limited to regular IREs.
2259 		 */
2260 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2261 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2262 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2263 		    (nexthop_addr != INADDR_ANY)))
2264 			continue;
2265 
2266 		mutex_enter(&ire->ire_lock);
2267 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2268 			uint32_t length;
2269 			int	i;
2270 
2271 			/*
2272 			 * Use the table from RFC 1191 to figure out
2273 			 * the next "plateau" based on the length in
2274 			 * the original IP packet.
2275 			 */
2276 			length = ntohs(ipha->ipha_length);
2277 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2278 			    uint32_t, length);
2279 			if (ire->ire_max_frag <= length &&
2280 			    ire->ire_max_frag >= length - hdr_length) {
2281 				/*
2282 				 * Handle broken BSD 4.2 systems that
2283 				 * return the wrong iph_length in ICMP
2284 				 * errors.
2285 				 */
2286 				length -= hdr_length;
2287 			}
2288 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2289 				if (length > icmp_frag_size_table[i])
2290 					break;
2291 			}
2292 			if (i == A_CNT(icmp_frag_size_table)) {
2293 				/* Smaller than 68! */
2294 				disable_pmtud = B_TRUE;
2295 				mtu = ipst->ips_ip_pmtu_min;
2296 			} else {
2297 				mtu = icmp_frag_size_table[i];
2298 				if (mtu < ipst->ips_ip_pmtu_min) {
2299 					mtu = ipst->ips_ip_pmtu_min;
2300 					disable_pmtud = B_TRUE;
2301 				}
2302 			}
2303 			/* Fool the ULP into believing our guessed PMTU. */
2304 			icmph->icmph_du_zero = 0;
2305 			icmph->icmph_du_mtu = htons(mtu);
2306 		}
2307 		if (disable_pmtud)
2308 			ire->ire_frag_flag = 0;
2309 		/* Reduce the IRE max frag value as advised. */
2310 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2311 		mutex_exit(&ire->ire_lock);
2312 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2313 		    ire, int, orig_mtu, int, mtu);
2314 	}
2315 	rw_exit(&first_ire->ire_bucket->irb_lock);
2316 	ire_refrele(first_ire);
2317 	return (B_TRUE);
2318 }
2319 
2320 /*
2321  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2322  * calls this function.
2323  */
2324 static mblk_t *
2325 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2326 {
2327 	ipha_t *ipha;
2328 	icmph_t *icmph;
2329 	ipha_t *in_ipha;
2330 	int length;
2331 
2332 	ASSERT(mp->b_datap->db_type == M_DATA);
2333 
2334 	/*
2335 	 * For Self-encapsulated packets, we added an extra IP header
2336 	 * without the options. Inner IP header is the one from which
2337 	 * the outer IP header was formed. Thus, we need to remove the
2338 	 * outer IP header. To do this, we pullup the whole message
2339 	 * and overlay whatever follows the outer IP header over the
2340 	 * outer IP header.
2341 	 */
2342 
2343 	if (!pullupmsg(mp, -1))
2344 		return (NULL);
2345 
2346 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2347 	ipha = (ipha_t *)&icmph[1];
2348 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2349 
2350 	/*
2351 	 * The length that we want to overlay is following the inner
2352 	 * IP header. Subtracting the IP header + icmp header + outer
2353 	 * IP header's length should give us the length that we want to
2354 	 * overlay.
2355 	 */
2356 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2357 	    hdr_length;
2358 	/*
2359 	 * Overlay whatever follows the inner header over the
2360 	 * outer header.
2361 	 */
2362 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2363 
2364 	/* Set the wptr to account for the outer header */
2365 	mp->b_wptr -= hdr_length;
2366 	return (mp);
2367 }
2368 
2369 /*
2370  * Try to pass the ICMP message upstream in case the ULP cares.
2371  *
2372  * If the packet that caused the ICMP error is secure, we send
2373  * it to AH/ESP to make sure that the attached packet has a
2374  * valid association. ipha in the code below points to the
2375  * IP header of the packet that caused the error.
2376  *
2377  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2378  * in the context of IPsec. Normally we tell the upper layer
2379  * whenever we send the ire (including ip_bind), the IPsec header
2380  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2381  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2382  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2383  * same thing. As TCP has the IPsec options size that needs to be
2384  * adjusted, we just pass the MTU unchanged.
2385  *
2386  * IFN could have been generated locally or by some router.
2387  *
2388  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2389  *	    This happens because IP adjusted its value of MTU on an
2390  *	    earlier IFN message and could not tell the upper layer,
2391  *	    the new adjusted value of MTU e.g. Packet was encrypted
2392  *	    or there was not enough information to fanout to upper
2393  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2394  *	    generates the IFN, where IPsec processing has *not* been
2395  *	    done.
2396  *
2397  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2398  *	    could have generated this. This happens because ire_max_frag
2399  *	    value in IP was set to a new value, while the IPsec processing
2400  *	    was being done and after we made the fragmentation check in
2401  *	    ip_wput_ire. Thus on return from IPsec processing,
2402  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2403  *	    and generates the IFN. As IPsec processing is over, we fanout
2404  *	    to AH/ESP to remove the header.
2405  *
2406  *	    In both these cases, ipsec_in_loopback will be set indicating
2407  *	    that IFN was generated locally.
2408  *
2409  * ROUTER : IFN could be secure or non-secure.
2410  *
2411  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2412  *	      packet in error has AH/ESP headers to validate the AH/ESP
2413  *	      headers. AH/ESP will verify whether there is a valid SA or
2414  *	      not and send it back. We will fanout again if we have more
2415  *	      data in the packet.
2416  *
2417  *	      If the packet in error does not have AH/ESP, we handle it
2418  *	      like any other case.
2419  *
2420  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2421  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2422  *	      for validation. AH/ESP will verify whether there is a
2423  *	      valid SA or not and send it back. We will fanout again if
2424  *	      we have more data in the packet.
2425  *
2426  *	      If the packet in error does not have AH/ESP, we handle it
2427  *	      like any other case.
2428  */
2429 static void
2430 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2431     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2432     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2433     zoneid_t zoneid)
2434 {
2435 	uint16_t *up;	/* Pointer to ports in ULP header */
2436 	uint32_t ports;	/* reversed ports for fanout */
2437 	ipha_t ripha;	/* With reversed addresses */
2438 	mblk_t *first_mp;
2439 	ipsec_in_t *ii;
2440 	tcph_t	*tcph;
2441 	conn_t	*connp;
2442 	ip_stack_t *ipst;
2443 
2444 	ASSERT(ill != NULL);
2445 
2446 	ASSERT(recv_ill != NULL);
2447 	ipst = recv_ill->ill_ipst;
2448 
2449 	first_mp = mp;
2450 	if (mctl_present) {
2451 		mp = first_mp->b_cont;
2452 		ASSERT(mp != NULL);
2453 
2454 		ii = (ipsec_in_t *)first_mp->b_rptr;
2455 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2456 	} else {
2457 		ii = NULL;
2458 	}
2459 
2460 	switch (ipha->ipha_protocol) {
2461 	case IPPROTO_UDP:
2462 		/*
2463 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2464 		 * transport header.
2465 		 */
2466 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2467 		    mp->b_wptr) {
2468 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2469 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2470 				goto discard_pkt;
2471 			}
2472 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2473 			ipha = (ipha_t *)&icmph[1];
2474 		}
2475 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2476 
2477 		/*
2478 		 * Attempt to find a client stream based on port.
2479 		 * Note that we do a reverse lookup since the header is
2480 		 * in the form we sent it out.
2481 		 * The ripha header is only used for the IP_UDP_MATCH and we
2482 		 * only set the src and dst addresses and protocol.
2483 		 */
2484 		ripha.ipha_src = ipha->ipha_dst;
2485 		ripha.ipha_dst = ipha->ipha_src;
2486 		ripha.ipha_protocol = ipha->ipha_protocol;
2487 		((uint16_t *)&ports)[0] = up[1];
2488 		((uint16_t *)&ports)[1] = up[0];
2489 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2490 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2491 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2492 		    icmph->icmph_type, icmph->icmph_code));
2493 
2494 		/* Have to change db_type after any pullupmsg */
2495 		DB_TYPE(mp) = M_CTL;
2496 
2497 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2498 		    mctl_present, ip_policy, recv_ill, zoneid);
2499 		return;
2500 
2501 	case IPPROTO_TCP:
2502 		/*
2503 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2504 		 * transport header.
2505 		 */
2506 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2507 		    mp->b_wptr) {
2508 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2509 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2510 				goto discard_pkt;
2511 			}
2512 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2513 			ipha = (ipha_t *)&icmph[1];
2514 		}
2515 		/*
2516 		 * Find a TCP client stream for this packet.
2517 		 * Note that we do a reverse lookup since the header is
2518 		 * in the form we sent it out.
2519 		 */
2520 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2521 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2522 		    ipst);
2523 		if (connp == NULL)
2524 			goto discard_pkt;
2525 
2526 		/* Have to change db_type after any pullupmsg */
2527 		DB_TYPE(mp) = M_CTL;
2528 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2529 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2530 		return;
2531 
2532 	case IPPROTO_SCTP:
2533 		/*
2534 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2535 		 * transport header.
2536 		 */
2537 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2538 		    mp->b_wptr) {
2539 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2540 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2541 				goto discard_pkt;
2542 			}
2543 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2544 			ipha = (ipha_t *)&icmph[1];
2545 		}
2546 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2547 		/*
2548 		 * Find a SCTP client stream for this packet.
2549 		 * Note that we do a reverse lookup since the header is
2550 		 * in the form we sent it out.
2551 		 * The ripha header is only used for the matching and we
2552 		 * only set the src and dst addresses, protocol, and version.
2553 		 */
2554 		ripha.ipha_src = ipha->ipha_dst;
2555 		ripha.ipha_dst = ipha->ipha_src;
2556 		ripha.ipha_protocol = ipha->ipha_protocol;
2557 		ripha.ipha_version_and_hdr_length =
2558 		    ipha->ipha_version_and_hdr_length;
2559 		((uint16_t *)&ports)[0] = up[1];
2560 		((uint16_t *)&ports)[1] = up[0];
2561 
2562 		/* Have to change db_type after any pullupmsg */
2563 		DB_TYPE(mp) = M_CTL;
2564 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2565 		    mctl_present, ip_policy, zoneid);
2566 		return;
2567 
2568 	case IPPROTO_ESP:
2569 	case IPPROTO_AH: {
2570 		int ipsec_rc;
2571 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2572 
2573 		/*
2574 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2575 		 * We will re-use the IPSEC_IN if it is already present as
2576 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2577 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2578 		 * one and attach it in the front.
2579 		 */
2580 		if (ii != NULL) {
2581 			/*
2582 			 * ip_fanout_proto_again converts the ICMP errors
2583 			 * that come back from AH/ESP to M_DATA so that
2584 			 * if it is non-AH/ESP and we do a pullupmsg in
2585 			 * this function, it would work. Convert it back
2586 			 * to M_CTL before we send up as this is a ICMP
2587 			 * error. This could have been generated locally or
2588 			 * by some router. Validate the inner IPsec
2589 			 * headers.
2590 			 *
2591 			 * NOTE : ill_index is used by ip_fanout_proto_again
2592 			 * to locate the ill.
2593 			 */
2594 			ASSERT(ill != NULL);
2595 			ii->ipsec_in_ill_index =
2596 			    ill->ill_phyint->phyint_ifindex;
2597 			ii->ipsec_in_rill_index =
2598 			    recv_ill->ill_phyint->phyint_ifindex;
2599 			DB_TYPE(first_mp->b_cont) = M_CTL;
2600 		} else {
2601 			/*
2602 			 * IPSEC_IN is not present. We attach a ipsec_in
2603 			 * message and send up to IPsec for validating
2604 			 * and removing the IPsec headers. Clear
2605 			 * ipsec_in_secure so that when we return
2606 			 * from IPsec, we don't mistakenly think that this
2607 			 * is a secure packet came from the network.
2608 			 *
2609 			 * NOTE : ill_index is used by ip_fanout_proto_again
2610 			 * to locate the ill.
2611 			 */
2612 			ASSERT(first_mp == mp);
2613 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2614 			if (first_mp == NULL) {
2615 				freemsg(mp);
2616 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2617 				return;
2618 			}
2619 			ii = (ipsec_in_t *)first_mp->b_rptr;
2620 
2621 			/* This is not a secure packet */
2622 			ii->ipsec_in_secure = B_FALSE;
2623 			first_mp->b_cont = mp;
2624 			DB_TYPE(mp) = M_CTL;
2625 			ASSERT(ill != NULL);
2626 			ii->ipsec_in_ill_index =
2627 			    ill->ill_phyint->phyint_ifindex;
2628 			ii->ipsec_in_rill_index =
2629 			    recv_ill->ill_phyint->phyint_ifindex;
2630 		}
2631 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2632 
2633 		if (!ipsec_loaded(ipss)) {
2634 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2635 			return;
2636 		}
2637 
2638 		if (ipha->ipha_protocol == IPPROTO_ESP)
2639 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2640 		else
2641 			ipsec_rc = ipsecah_icmp_error(first_mp);
2642 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2643 			return;
2644 
2645 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2646 		return;
2647 	}
2648 	default:
2649 		/*
2650 		 * The ripha header is only used for the lookup and we
2651 		 * only set the src and dst addresses and protocol.
2652 		 */
2653 		ripha.ipha_src = ipha->ipha_dst;
2654 		ripha.ipha_dst = ipha->ipha_src;
2655 		ripha.ipha_protocol = ipha->ipha_protocol;
2656 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2657 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2658 		    ntohl(ipha->ipha_dst),
2659 		    icmph->icmph_type, icmph->icmph_code));
2660 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2661 			ipha_t *in_ipha;
2662 
2663 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2664 			    mp->b_wptr) {
2665 				if (!pullupmsg(mp, (uchar_t *)ipha +
2666 				    hdr_length + sizeof (ipha_t) -
2667 				    mp->b_rptr)) {
2668 					goto discard_pkt;
2669 				}
2670 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2671 				ipha = (ipha_t *)&icmph[1];
2672 			}
2673 			/*
2674 			 * Caller has verified that length has to be
2675 			 * at least the size of IP header.
2676 			 */
2677 			ASSERT(hdr_length >= sizeof (ipha_t));
2678 			/*
2679 			 * Check the sanity of the inner IP header like
2680 			 * we did for the outer header.
2681 			 */
2682 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2683 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2684 				goto discard_pkt;
2685 			}
2686 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2687 				goto discard_pkt;
2688 			}
2689 			/* Check for Self-encapsulated tunnels */
2690 			if (in_ipha->ipha_src == ipha->ipha_src &&
2691 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2692 
2693 				mp = icmp_inbound_self_encap_error(mp,
2694 				    iph_hdr_length, hdr_length);
2695 				if (mp == NULL)
2696 					goto discard_pkt;
2697 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2698 				ipha = (ipha_t *)&icmph[1];
2699 				hdr_length = IPH_HDR_LENGTH(ipha);
2700 				/*
2701 				 * The packet in error is self-encapsualted.
2702 				 * And we are finding it further encapsulated
2703 				 * which we could not have possibly generated.
2704 				 */
2705 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2706 					goto discard_pkt;
2707 				}
2708 				icmp_inbound_error_fanout(q, ill, first_mp,
2709 				    icmph, ipha, iph_hdr_length, hdr_length,
2710 				    mctl_present, ip_policy, recv_ill, zoneid);
2711 				return;
2712 			}
2713 		}
2714 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2715 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2716 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2717 		    ii != NULL &&
2718 		    ii->ipsec_in_loopback &&
2719 		    ii->ipsec_in_secure) {
2720 			/*
2721 			 * For IP tunnels that get a looped-back
2722 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2723 			 * reported new MTU to take into account the IPsec
2724 			 * headers protecting this configured tunnel.
2725 			 *
2726 			 * This allows the tunnel module (tun.c) to blindly
2727 			 * accept the MTU reported in an ICMP "too big"
2728 			 * message.
2729 			 *
2730 			 * Non-looped back ICMP messages will just be
2731 			 * handled by the security protocols (if needed),
2732 			 * and the first subsequent packet will hit this
2733 			 * path.
2734 			 */
2735 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2736 			    ipsec_in_extra_length(first_mp));
2737 		}
2738 		/* Have to change db_type after any pullupmsg */
2739 		DB_TYPE(mp) = M_CTL;
2740 
2741 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2742 		    ip_policy, recv_ill, zoneid);
2743 		return;
2744 	}
2745 	/* NOTREACHED */
2746 discard_pkt:
2747 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2748 drop_pkt:;
2749 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2750 	freemsg(first_mp);
2751 }
2752 
2753 /*
2754  * Common IP options parser.
2755  *
2756  * Setup routine: fill in *optp with options-parsing state, then
2757  * tail-call ipoptp_next to return the first option.
2758  */
2759 uint8_t
2760 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2761 {
2762 	uint32_t totallen; /* total length of all options */
2763 
2764 	totallen = ipha->ipha_version_and_hdr_length -
2765 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2766 	totallen <<= 2;
2767 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2768 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2769 	optp->ipoptp_flags = 0;
2770 	return (ipoptp_next(optp));
2771 }
2772 
2773 /*
2774  * Common IP options parser: extract next option.
2775  */
2776 uint8_t
2777 ipoptp_next(ipoptp_t *optp)
2778 {
2779 	uint8_t *end = optp->ipoptp_end;
2780 	uint8_t *cur = optp->ipoptp_next;
2781 	uint8_t opt, len, pointer;
2782 
2783 	/*
2784 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2785 	 * has been corrupted.
2786 	 */
2787 	ASSERT(cur <= end);
2788 
2789 	if (cur == end)
2790 		return (IPOPT_EOL);
2791 
2792 	opt = cur[IPOPT_OPTVAL];
2793 
2794 	/*
2795 	 * Skip any NOP options.
2796 	 */
2797 	while (opt == IPOPT_NOP) {
2798 		cur++;
2799 		if (cur == end)
2800 			return (IPOPT_EOL);
2801 		opt = cur[IPOPT_OPTVAL];
2802 	}
2803 
2804 	if (opt == IPOPT_EOL)
2805 		return (IPOPT_EOL);
2806 
2807 	/*
2808 	 * Option requiring a length.
2809 	 */
2810 	if ((cur + 1) >= end) {
2811 		optp->ipoptp_flags |= IPOPTP_ERROR;
2812 		return (IPOPT_EOL);
2813 	}
2814 	len = cur[IPOPT_OLEN];
2815 	if (len < 2) {
2816 		optp->ipoptp_flags |= IPOPTP_ERROR;
2817 		return (IPOPT_EOL);
2818 	}
2819 	optp->ipoptp_cur = cur;
2820 	optp->ipoptp_len = len;
2821 	optp->ipoptp_next = cur + len;
2822 	if (cur + len > end) {
2823 		optp->ipoptp_flags |= IPOPTP_ERROR;
2824 		return (IPOPT_EOL);
2825 	}
2826 
2827 	/*
2828 	 * For the options which require a pointer field, make sure
2829 	 * its there, and make sure it points to either something
2830 	 * inside this option, or the end of the option.
2831 	 */
2832 	switch (opt) {
2833 	case IPOPT_RR:
2834 	case IPOPT_TS:
2835 	case IPOPT_LSRR:
2836 	case IPOPT_SSRR:
2837 		if (len <= IPOPT_OFFSET) {
2838 			optp->ipoptp_flags |= IPOPTP_ERROR;
2839 			return (opt);
2840 		}
2841 		pointer = cur[IPOPT_OFFSET];
2842 		if (pointer - 1 > len) {
2843 			optp->ipoptp_flags |= IPOPTP_ERROR;
2844 			return (opt);
2845 		}
2846 		break;
2847 	}
2848 
2849 	/*
2850 	 * Sanity check the pointer field based on the type of the
2851 	 * option.
2852 	 */
2853 	switch (opt) {
2854 	case IPOPT_RR:
2855 	case IPOPT_SSRR:
2856 	case IPOPT_LSRR:
2857 		if (pointer < IPOPT_MINOFF_SR)
2858 			optp->ipoptp_flags |= IPOPTP_ERROR;
2859 		break;
2860 	case IPOPT_TS:
2861 		if (pointer < IPOPT_MINOFF_IT)
2862 			optp->ipoptp_flags |= IPOPTP_ERROR;
2863 		/*
2864 		 * Note that the Internet Timestamp option also
2865 		 * contains two four bit fields (the Overflow field,
2866 		 * and the Flag field), which follow the pointer
2867 		 * field.  We don't need to check that these fields
2868 		 * fall within the length of the option because this
2869 		 * was implicitely done above.  We've checked that the
2870 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2871 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2872 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2873 		 */
2874 		ASSERT(len > IPOPT_POS_OV_FLG);
2875 		break;
2876 	}
2877 
2878 	return (opt);
2879 }
2880 
2881 /*
2882  * Use the outgoing IP header to create an IP_OPTIONS option the way
2883  * it was passed down from the application.
2884  */
2885 int
2886 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2887 {
2888 	ipoptp_t	opts;
2889 	const uchar_t	*opt;
2890 	uint8_t		optval;
2891 	uint8_t		optlen;
2892 	uint32_t	len = 0;
2893 	uchar_t	*buf1 = buf;
2894 
2895 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2896 	len += IP_ADDR_LEN;
2897 	bzero(buf1, IP_ADDR_LEN);
2898 
2899 	/*
2900 	 * OK to cast away const here, as we don't store through the returned
2901 	 * opts.ipoptp_cur pointer.
2902 	 */
2903 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2904 	    optval != IPOPT_EOL;
2905 	    optval = ipoptp_next(&opts)) {
2906 		int	off;
2907 
2908 		opt = opts.ipoptp_cur;
2909 		optlen = opts.ipoptp_len;
2910 		switch (optval) {
2911 		case IPOPT_SSRR:
2912 		case IPOPT_LSRR:
2913 
2914 			/*
2915 			 * Insert ipha_dst as the first entry in the source
2916 			 * route and move down the entries on step.
2917 			 * The last entry gets placed at buf1.
2918 			 */
2919 			buf[IPOPT_OPTVAL] = optval;
2920 			buf[IPOPT_OLEN] = optlen;
2921 			buf[IPOPT_OFFSET] = optlen;
2922 
2923 			off = optlen - IP_ADDR_LEN;
2924 			if (off < 0) {
2925 				/* No entries in source route */
2926 				break;
2927 			}
2928 			/* Last entry in source route */
2929 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2930 			off -= IP_ADDR_LEN;
2931 
2932 			while (off > 0) {
2933 				bcopy(opt + off,
2934 				    buf + off + IP_ADDR_LEN,
2935 				    IP_ADDR_LEN);
2936 				off -= IP_ADDR_LEN;
2937 			}
2938 			/* ipha_dst into first slot */
2939 			bcopy(&ipha->ipha_dst,
2940 			    buf + off + IP_ADDR_LEN,
2941 			    IP_ADDR_LEN);
2942 			buf += optlen;
2943 			len += optlen;
2944 			break;
2945 
2946 		case IPOPT_COMSEC:
2947 		case IPOPT_SECURITY:
2948 			/* if passing up a label is not ok, then remove */
2949 			if (is_system_labeled())
2950 				break;
2951 			/* FALLTHROUGH */
2952 		default:
2953 			bcopy(opt, buf, optlen);
2954 			buf += optlen;
2955 			len += optlen;
2956 			break;
2957 		}
2958 	}
2959 done:
2960 	/* Pad the resulting options */
2961 	while (len & 0x3) {
2962 		*buf++ = IPOPT_EOL;
2963 		len++;
2964 	}
2965 	return (len);
2966 }
2967 
2968 /*
2969  * Update any record route or timestamp options to include this host.
2970  * Reverse any source route option.
2971  * This routine assumes that the options are well formed i.e. that they
2972  * have already been checked.
2973  */
2974 static void
2975 icmp_options_update(ipha_t *ipha)
2976 {
2977 	ipoptp_t	opts;
2978 	uchar_t		*opt;
2979 	uint8_t		optval;
2980 	ipaddr_t	src;		/* Our local address */
2981 	ipaddr_t	dst;
2982 
2983 	ip2dbg(("icmp_options_update\n"));
2984 	src = ipha->ipha_src;
2985 	dst = ipha->ipha_dst;
2986 
2987 	for (optval = ipoptp_first(&opts, ipha);
2988 	    optval != IPOPT_EOL;
2989 	    optval = ipoptp_next(&opts)) {
2990 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2991 		opt = opts.ipoptp_cur;
2992 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2993 		    optval, opts.ipoptp_len));
2994 		switch (optval) {
2995 			int off1, off2;
2996 		case IPOPT_SSRR:
2997 		case IPOPT_LSRR:
2998 			/*
2999 			 * Reverse the source route.  The first entry
3000 			 * should be the next to last one in the current
3001 			 * source route (the last entry is our address).
3002 			 * The last entry should be the final destination.
3003 			 */
3004 			off1 = IPOPT_MINOFF_SR - 1;
3005 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3006 			if (off2 < 0) {
3007 				/* No entries in source route */
3008 				ip1dbg((
3009 				    "icmp_options_update: bad src route\n"));
3010 				break;
3011 			}
3012 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3013 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3014 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3015 			off2 -= IP_ADDR_LEN;
3016 
3017 			while (off1 < off2) {
3018 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3019 				bcopy((char *)opt + off2, (char *)opt + off1,
3020 				    IP_ADDR_LEN);
3021 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3022 				off1 += IP_ADDR_LEN;
3023 				off2 -= IP_ADDR_LEN;
3024 			}
3025 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3026 			break;
3027 		}
3028 	}
3029 }
3030 
3031 /*
3032  * Process received ICMP Redirect messages.
3033  */
3034 static void
3035 icmp_redirect(ill_t *ill, mblk_t *mp)
3036 {
3037 	ipha_t	*ipha;
3038 	int	iph_hdr_length;
3039 	icmph_t	*icmph;
3040 	ipha_t	*ipha_err;
3041 	ire_t	*ire;
3042 	ire_t	*prev_ire;
3043 	ire_t	*save_ire;
3044 	ipaddr_t  src, dst, gateway;
3045 	iulp_t	ulp_info = { 0 };
3046 	int	error;
3047 	ip_stack_t *ipst;
3048 
3049 	ASSERT(ill != NULL);
3050 	ipst = ill->ill_ipst;
3051 
3052 	ipha = (ipha_t *)mp->b_rptr;
3053 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3054 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3055 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3056 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3057 		freemsg(mp);
3058 		return;
3059 	}
3060 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3061 	ipha_err = (ipha_t *)&icmph[1];
3062 	src = ipha->ipha_src;
3063 	dst = ipha_err->ipha_dst;
3064 	gateway = icmph->icmph_rd_gateway;
3065 	/* Make sure the new gateway is reachable somehow. */
3066 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3067 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3068 	/*
3069 	 * Make sure we had a route for the dest in question and that
3070 	 * that route was pointing to the old gateway (the source of the
3071 	 * redirect packet.)
3072 	 */
3073 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3074 	    NULL, MATCH_IRE_GW, ipst);
3075 	/*
3076 	 * Check that
3077 	 *	the redirect was not from ourselves
3078 	 *	the new gateway and the old gateway are directly reachable
3079 	 */
3080 	if (!prev_ire ||
3081 	    !ire ||
3082 	    ire->ire_type == IRE_LOCAL) {
3083 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3084 		freemsg(mp);
3085 		if (ire != NULL)
3086 			ire_refrele(ire);
3087 		if (prev_ire != NULL)
3088 			ire_refrele(prev_ire);
3089 		return;
3090 	}
3091 
3092 	/*
3093 	 * Should we use the old ULP info to create the new gateway?  From
3094 	 * a user's perspective, we should inherit the info so that it
3095 	 * is a "smooth" transition.  If we do not do that, then new
3096 	 * connections going thru the new gateway will have no route metrics,
3097 	 * which is counter-intuitive to user.  From a network point of
3098 	 * view, this may or may not make sense even though the new gateway
3099 	 * is still directly connected to us so the route metrics should not
3100 	 * change much.
3101 	 *
3102 	 * But if the old ire_uinfo is not initialized, we do another
3103 	 * recursive lookup on the dest using the new gateway.  There may
3104 	 * be a route to that.  If so, use it to initialize the redirect
3105 	 * route.
3106 	 */
3107 	if (prev_ire->ire_uinfo.iulp_set) {
3108 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3109 	} else {
3110 		ire_t *tmp_ire;
3111 		ire_t *sire;
3112 
3113 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3114 		    ALL_ZONES, 0, NULL,
3115 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3116 		    ipst);
3117 		if (sire != NULL) {
3118 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3119 			/*
3120 			 * If sire != NULL, ire_ftable_lookup() should not
3121 			 * return a NULL value.
3122 			 */
3123 			ASSERT(tmp_ire != NULL);
3124 			ire_refrele(tmp_ire);
3125 			ire_refrele(sire);
3126 		} else if (tmp_ire != NULL) {
3127 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3128 			    sizeof (iulp_t));
3129 			ire_refrele(tmp_ire);
3130 		}
3131 	}
3132 	if (prev_ire->ire_type == IRE_CACHE)
3133 		ire_delete(prev_ire);
3134 	ire_refrele(prev_ire);
3135 	/*
3136 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3137 	 * require TOS routing
3138 	 */
3139 	switch (icmph->icmph_code) {
3140 	case 0:
3141 	case 1:
3142 		/* TODO: TOS specificity for cases 2 and 3 */
3143 	case 2:
3144 	case 3:
3145 		break;
3146 	default:
3147 		freemsg(mp);
3148 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3149 		ire_refrele(ire);
3150 		return;
3151 	}
3152 	/*
3153 	 * Create a Route Association.  This will allow us to remember that
3154 	 * someone we believe told us to use the particular gateway.
3155 	 */
3156 	save_ire = ire;
3157 	ire = ire_create(
3158 	    (uchar_t *)&dst,			/* dest addr */
3159 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3160 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3161 	    (uchar_t *)&gateway,		/* gateway addr */
3162 	    &save_ire->ire_max_frag,		/* max frag */
3163 	    NULL,				/* no src nce */
3164 	    NULL,				/* no rfq */
3165 	    NULL,				/* no stq */
3166 	    IRE_HOST,
3167 	    NULL,				/* ipif */
3168 	    0,					/* cmask */
3169 	    0,					/* phandle */
3170 	    0,					/* ihandle */
3171 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3172 	    &ulp_info,
3173 	    NULL,				/* tsol_gc_t */
3174 	    NULL,				/* gcgrp */
3175 	    ipst);
3176 
3177 	if (ire == NULL) {
3178 		freemsg(mp);
3179 		ire_refrele(save_ire);
3180 		return;
3181 	}
3182 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3183 	ire_refrele(save_ire);
3184 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3185 
3186 	if (error == 0) {
3187 		ire_refrele(ire);		/* Held in ire_add_v4 */
3188 		/* tell routing sockets that we received a redirect */
3189 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3190 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3191 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3192 	}
3193 
3194 	/*
3195 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3196 	 * This together with the added IRE has the effect of
3197 	 * modifying an existing redirect.
3198 	 */
3199 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3200 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3201 	if (prev_ire != NULL) {
3202 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3203 			ire_delete(prev_ire);
3204 		ire_refrele(prev_ire);
3205 	}
3206 
3207 	freemsg(mp);
3208 }
3209 
3210 /*
3211  * Generate an ICMP parameter problem message.
3212  */
3213 static void
3214 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3215 	ip_stack_t *ipst)
3216 {
3217 	icmph_t	icmph;
3218 	boolean_t mctl_present;
3219 	mblk_t *first_mp;
3220 
3221 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3222 
3223 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3224 		if (mctl_present)
3225 			freeb(first_mp);
3226 		return;
3227 	}
3228 
3229 	bzero(&icmph, sizeof (icmph_t));
3230 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3231 	icmph.icmph_pp_ptr = ptr;
3232 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3233 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3234 	    ipst);
3235 }
3236 
3237 /*
3238  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3239  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3240  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3241  * an icmp error packet can be sent.
3242  * Assigns an appropriate source address to the packet. If ipha_dst is
3243  * one of our addresses use it for source. Otherwise pick a source based
3244  * on a route lookup back to ipha_src.
3245  * Note that ipha_src must be set here since the
3246  * packet is likely to arrive on an ill queue in ip_wput() which will
3247  * not set a source address.
3248  */
3249 static void
3250 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3251     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3252 {
3253 	ipaddr_t dst;
3254 	icmph_t	*icmph;
3255 	ipha_t	*ipha;
3256 	uint_t	len_needed;
3257 	size_t	msg_len;
3258 	mblk_t	*mp1;
3259 	ipaddr_t src;
3260 	ire_t	*ire;
3261 	mblk_t *ipsec_mp;
3262 	ipsec_out_t	*io = NULL;
3263 
3264 	if (mctl_present) {
3265 		/*
3266 		 * If it is :
3267 		 *
3268 		 * 1) a IPSEC_OUT, then this is caused by outbound
3269 		 *    datagram originating on this host. IPsec processing
3270 		 *    may or may not have been done. Refer to comments above
3271 		 *    icmp_inbound_error_fanout for details.
3272 		 *
3273 		 * 2) a IPSEC_IN if we are generating a icmp_message
3274 		 *    for an incoming datagram destined for us i.e called
3275 		 *    from ip_fanout_send_icmp.
3276 		 */
3277 		ipsec_info_t *in;
3278 		ipsec_mp = mp;
3279 		mp = ipsec_mp->b_cont;
3280 
3281 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3282 		ipha = (ipha_t *)mp->b_rptr;
3283 
3284 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3285 		    in->ipsec_info_type == IPSEC_IN);
3286 
3287 		if (in->ipsec_info_type == IPSEC_IN) {
3288 			/*
3289 			 * Convert the IPSEC_IN to IPSEC_OUT.
3290 			 */
3291 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3292 				BUMP_MIB(&ipst->ips_ip_mib,
3293 				    ipIfStatsOutDiscards);
3294 				return;
3295 			}
3296 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3297 		} else {
3298 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3299 			io = (ipsec_out_t *)in;
3300 			/*
3301 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3302 			 * ire lookup.
3303 			 */
3304 			io->ipsec_out_proc_begin = B_FALSE;
3305 		}
3306 		ASSERT(zoneid == io->ipsec_out_zoneid);
3307 		ASSERT(zoneid != ALL_ZONES);
3308 	} else {
3309 		/*
3310 		 * This is in clear. The icmp message we are building
3311 		 * here should go out in clear.
3312 		 *
3313 		 * Pardon the convolution of it all, but it's easier to
3314 		 * allocate a "use cleartext" IPSEC_IN message and convert
3315 		 * it than it is to allocate a new one.
3316 		 */
3317 		ipsec_in_t *ii;
3318 		ASSERT(DB_TYPE(mp) == M_DATA);
3319 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3320 		if (ipsec_mp == NULL) {
3321 			freemsg(mp);
3322 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3323 			return;
3324 		}
3325 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3326 
3327 		/* This is not a secure packet */
3328 		ii->ipsec_in_secure = B_FALSE;
3329 		/*
3330 		 * For trusted extensions using a shared IP address we can
3331 		 * send using any zoneid.
3332 		 */
3333 		if (zoneid == ALL_ZONES)
3334 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3335 		else
3336 			ii->ipsec_in_zoneid = zoneid;
3337 		ipsec_mp->b_cont = mp;
3338 		ipha = (ipha_t *)mp->b_rptr;
3339 		/*
3340 		 * Convert the IPSEC_IN to IPSEC_OUT.
3341 		 */
3342 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3343 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3344 			return;
3345 		}
3346 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3347 	}
3348 
3349 	/* Remember our eventual destination */
3350 	dst = ipha->ipha_src;
3351 
3352 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3353 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3354 	if (ire != NULL &&
3355 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3356 		src = ipha->ipha_dst;
3357 	} else {
3358 		if (ire != NULL)
3359 			ire_refrele(ire);
3360 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3361 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3362 		    ipst);
3363 		if (ire == NULL) {
3364 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3365 			freemsg(ipsec_mp);
3366 			return;
3367 		}
3368 		src = ire->ire_src_addr;
3369 	}
3370 
3371 	if (ire != NULL)
3372 		ire_refrele(ire);
3373 
3374 	/*
3375 	 * Check if we can send back more then 8 bytes in addition to
3376 	 * the IP header.  We try to send 64 bytes of data and the internal
3377 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3378 	 */
3379 	len_needed = IPH_HDR_LENGTH(ipha);
3380 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3381 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3382 
3383 		if (!pullupmsg(mp, -1)) {
3384 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3385 			freemsg(ipsec_mp);
3386 			return;
3387 		}
3388 		ipha = (ipha_t *)mp->b_rptr;
3389 
3390 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3391 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3392 			    len_needed));
3393 		} else {
3394 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3395 
3396 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3397 			len_needed += ip_hdr_length_v6(mp, ip6h);
3398 		}
3399 	}
3400 	len_needed += ipst->ips_ip_icmp_return;
3401 	msg_len = msgdsize(mp);
3402 	if (msg_len > len_needed) {
3403 		(void) adjmsg(mp, len_needed - msg_len);
3404 		msg_len = len_needed;
3405 	}
3406 	/* Make sure we propagate the cred/label for TX */
3407 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3408 	if (mp1 == NULL) {
3409 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3410 		freemsg(ipsec_mp);
3411 		return;
3412 	}
3413 	mp1->b_cont = mp;
3414 	mp = mp1;
3415 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3416 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3417 	    io->ipsec_out_type == IPSEC_OUT);
3418 	ipsec_mp->b_cont = mp;
3419 
3420 	/*
3421 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3422 	 * node generates be accepted in peace by all on-host destinations.
3423 	 * If we do NOT assume that all on-host destinations trust
3424 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3425 	 * (Look for ipsec_out_icmp_loopback).
3426 	 */
3427 	io->ipsec_out_icmp_loopback = B_TRUE;
3428 
3429 	ipha = (ipha_t *)mp->b_rptr;
3430 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3431 	*ipha = icmp_ipha;
3432 	ipha->ipha_src = src;
3433 	ipha->ipha_dst = dst;
3434 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3435 	msg_len += sizeof (icmp_ipha) + len;
3436 	if (msg_len > IP_MAXPACKET) {
3437 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3438 		msg_len = IP_MAXPACKET;
3439 	}
3440 	ipha->ipha_length = htons((uint16_t)msg_len);
3441 	icmph = (icmph_t *)&ipha[1];
3442 	bcopy(stuff, icmph, len);
3443 	icmph->icmph_checksum = 0;
3444 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3445 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3446 	put(q, ipsec_mp);
3447 }
3448 
3449 /*
3450  * Determine if an ICMP error packet can be sent given the rate limit.
3451  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3452  * in milliseconds) and a burst size. Burst size number of packets can
3453  * be sent arbitrarely closely spaced.
3454  * The state is tracked using two variables to implement an approximate
3455  * token bucket filter:
3456  *	icmp_pkt_err_last - lbolt value when the last burst started
3457  *	icmp_pkt_err_sent - number of packets sent in current burst
3458  */
3459 boolean_t
3460 icmp_err_rate_limit(ip_stack_t *ipst)
3461 {
3462 	clock_t now = TICK_TO_MSEC(lbolt);
3463 	uint_t refilled; /* Number of packets refilled in tbf since last */
3464 	/* Guard against changes by loading into local variable */
3465 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3466 
3467 	if (err_interval == 0)
3468 		return (B_FALSE);
3469 
3470 	if (ipst->ips_icmp_pkt_err_last > now) {
3471 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3472 		ipst->ips_icmp_pkt_err_last = 0;
3473 		ipst->ips_icmp_pkt_err_sent = 0;
3474 	}
3475 	/*
3476 	 * If we are in a burst update the token bucket filter.
3477 	 * Update the "last" time to be close to "now" but make sure
3478 	 * we don't loose precision.
3479 	 */
3480 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3481 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3482 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3483 			ipst->ips_icmp_pkt_err_sent = 0;
3484 		} else {
3485 			ipst->ips_icmp_pkt_err_sent -= refilled;
3486 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3487 		}
3488 	}
3489 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3490 		/* Start of new burst */
3491 		ipst->ips_icmp_pkt_err_last = now;
3492 	}
3493 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3494 		ipst->ips_icmp_pkt_err_sent++;
3495 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3496 		    ipst->ips_icmp_pkt_err_sent));
3497 		return (B_FALSE);
3498 	}
3499 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3500 	return (B_TRUE);
3501 }
3502 
3503 /*
3504  * Check if it is ok to send an IPv4 ICMP error packet in
3505  * response to the IPv4 packet in mp.
3506  * Free the message and return null if no
3507  * ICMP error packet should be sent.
3508  */
3509 static mblk_t *
3510 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3511 {
3512 	icmph_t	*icmph;
3513 	ipha_t	*ipha;
3514 	uint_t	len_needed;
3515 	ire_t	*src_ire;
3516 	ire_t	*dst_ire;
3517 
3518 	if (!mp)
3519 		return (NULL);
3520 	ipha = (ipha_t *)mp->b_rptr;
3521 	if (ip_csum_hdr(ipha)) {
3522 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3523 		freemsg(mp);
3524 		return (NULL);
3525 	}
3526 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3527 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3528 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3529 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3530 	if (src_ire != NULL || dst_ire != NULL ||
3531 	    CLASSD(ipha->ipha_dst) ||
3532 	    CLASSD(ipha->ipha_src) ||
3533 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3534 		/* Note: only errors to the fragment with offset 0 */
3535 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3536 		freemsg(mp);
3537 		if (src_ire != NULL)
3538 			ire_refrele(src_ire);
3539 		if (dst_ire != NULL)
3540 			ire_refrele(dst_ire);
3541 		return (NULL);
3542 	}
3543 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3544 		/*
3545 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3546 		 * errors in response to any ICMP errors.
3547 		 */
3548 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3549 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3550 			if (!pullupmsg(mp, len_needed)) {
3551 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3552 				freemsg(mp);
3553 				return (NULL);
3554 			}
3555 			ipha = (ipha_t *)mp->b_rptr;
3556 		}
3557 		icmph = (icmph_t *)
3558 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3559 		switch (icmph->icmph_type) {
3560 		case ICMP_DEST_UNREACHABLE:
3561 		case ICMP_SOURCE_QUENCH:
3562 		case ICMP_TIME_EXCEEDED:
3563 		case ICMP_PARAM_PROBLEM:
3564 		case ICMP_REDIRECT:
3565 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3566 			freemsg(mp);
3567 			return (NULL);
3568 		default:
3569 			break;
3570 		}
3571 	}
3572 	/*
3573 	 * If this is a labeled system, then check to see if we're allowed to
3574 	 * send a response to this particular sender.  If not, then just drop.
3575 	 */
3576 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3577 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3578 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3579 		freemsg(mp);
3580 		return (NULL);
3581 	}
3582 	if (icmp_err_rate_limit(ipst)) {
3583 		/*
3584 		 * Only send ICMP error packets every so often.
3585 		 * This should be done on a per port/source basis,
3586 		 * but for now this will suffice.
3587 		 */
3588 		freemsg(mp);
3589 		return (NULL);
3590 	}
3591 	return (mp);
3592 }
3593 
3594 /*
3595  * Generate an ICMP redirect message.
3596  */
3597 static void
3598 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3599 {
3600 	icmph_t	icmph;
3601 
3602 	/*
3603 	 * We are called from ip_rput where we could
3604 	 * not have attached an IPSEC_IN.
3605 	 */
3606 	ASSERT(mp->b_datap->db_type == M_DATA);
3607 
3608 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3609 		return;
3610 	}
3611 
3612 	bzero(&icmph, sizeof (icmph_t));
3613 	icmph.icmph_type = ICMP_REDIRECT;
3614 	icmph.icmph_code = 1;
3615 	icmph.icmph_rd_gateway = gateway;
3616 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3617 	/* Redirects sent by router, and router is global zone */
3618 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3619 }
3620 
3621 /*
3622  * Generate an ICMP time exceeded message.
3623  */
3624 void
3625 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3626     ip_stack_t *ipst)
3627 {
3628 	icmph_t	icmph;
3629 	boolean_t mctl_present;
3630 	mblk_t *first_mp;
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_TIME_EXCEEDED;
3642 	icmph.icmph_code = code;
3643 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3644 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3645 	    ipst);
3646 }
3647 
3648 /*
3649  * Generate an ICMP unreachable message.
3650  */
3651 void
3652 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3653     ip_stack_t *ipst)
3654 {
3655 	icmph_t	icmph;
3656 	mblk_t *first_mp;
3657 	boolean_t mctl_present;
3658 
3659 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3660 
3661 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3662 		if (mctl_present)
3663 			freeb(first_mp);
3664 		return;
3665 	}
3666 
3667 	bzero(&icmph, sizeof (icmph_t));
3668 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3669 	icmph.icmph_code = code;
3670 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3671 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3672 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3673 	    zoneid, ipst);
3674 }
3675 
3676 /*
3677  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3678  * duplicate.  As long as someone else holds the address, the interface will
3679  * stay down.  When that conflict goes away, the interface is brought back up.
3680  * This is done so that accidental shutdowns of addresses aren't made
3681  * permanent.  Your server will recover from a failure.
3682  *
3683  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3684  * user space process (dhcpagent).
3685  *
3686  * Recovery completes if ARP reports that the address is now ours (via
3687  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3688  *
3689  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3690  */
3691 static void
3692 ipif_dup_recovery(void *arg)
3693 {
3694 	ipif_t *ipif = arg;
3695 	ill_t *ill = ipif->ipif_ill;
3696 	mblk_t *arp_add_mp;
3697 	mblk_t *arp_del_mp;
3698 	ip_stack_t *ipst = ill->ill_ipst;
3699 
3700 	ipif->ipif_recovery_id = 0;
3701 
3702 	/*
3703 	 * No lock needed for moving or condemned check, as this is just an
3704 	 * optimization.
3705 	 */
3706 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3707 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3708 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3709 		/* No reason to try to bring this address back. */
3710 		return;
3711 	}
3712 
3713 	/* ACE_F_UNVERIFIED restarts DAD */
3714 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3715 		goto alloc_fail;
3716 
3717 	if (ipif->ipif_arp_del_mp == NULL) {
3718 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3719 			goto alloc_fail;
3720 		ipif->ipif_arp_del_mp = arp_del_mp;
3721 	}
3722 
3723 	putnext(ill->ill_rq, arp_add_mp);
3724 	return;
3725 
3726 alloc_fail:
3727 	/*
3728 	 * On allocation failure, just restart the timer.  Note that the ipif
3729 	 * is down here, so no other thread could be trying to start a recovery
3730 	 * timer.  The ill_lock protects the condemned flag and the recovery
3731 	 * timer ID.
3732 	 */
3733 	freemsg(arp_add_mp);
3734 	mutex_enter(&ill->ill_lock);
3735 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3736 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3737 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3738 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3739 	}
3740 	mutex_exit(&ill->ill_lock);
3741 }
3742 
3743 /*
3744  * This is for exclusive changes due to ARP.  Either tear down an interface due
3745  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3746  */
3747 /* ARGSUSED */
3748 static void
3749 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3750 {
3751 	ill_t	*ill = rq->q_ptr;
3752 	arh_t *arh;
3753 	ipaddr_t src;
3754 	ipif_t	*ipif;
3755 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3756 	char hbuf[MAC_STR_LEN];
3757 	char sbuf[INET_ADDRSTRLEN];
3758 	const char *failtype;
3759 	boolean_t bring_up;
3760 	ip_stack_t *ipst = ill->ill_ipst;
3761 
3762 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3763 	case AR_CN_READY:
3764 		failtype = NULL;
3765 		bring_up = B_TRUE;
3766 		break;
3767 	case AR_CN_FAILED:
3768 		failtype = "in use";
3769 		bring_up = B_FALSE;
3770 		break;
3771 	default:
3772 		failtype = "claimed";
3773 		bring_up = B_FALSE;
3774 		break;
3775 	}
3776 
3777 	arh = (arh_t *)mp->b_cont->b_rptr;
3778 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3779 
3780 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3781 	    sizeof (hbuf));
3782 	(void) ip_dot_addr(src, sbuf);
3783 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3784 
3785 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3786 		    ipif->ipif_lcl_addr != src) {
3787 			continue;
3788 		}
3789 
3790 		/*
3791 		 * If we failed on a recovery probe, then restart the timer to
3792 		 * try again later.
3793 		 */
3794 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3795 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3796 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3797 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3798 		    ipst->ips_ip_dup_recovery > 0 &&
3799 		    ipif->ipif_recovery_id == 0) {
3800 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3801 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3802 			continue;
3803 		}
3804 
3805 		/*
3806 		 * If what we're trying to do has already been done, then do
3807 		 * nothing.
3808 		 */
3809 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3810 			continue;
3811 
3812 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3813 
3814 		if (failtype == NULL) {
3815 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3816 			    ibuf);
3817 		} else {
3818 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3819 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3820 		}
3821 
3822 		if (bring_up) {
3823 			ASSERT(ill->ill_dl_up);
3824 			/*
3825 			 * Free up the ARP delete message so we can allocate
3826 			 * a fresh one through the normal path.
3827 			 */
3828 			freemsg(ipif->ipif_arp_del_mp);
3829 			ipif->ipif_arp_del_mp = NULL;
3830 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3831 			    EINPROGRESS) {
3832 				ipif->ipif_addr_ready = 1;
3833 				(void) ipif_up_done(ipif);
3834 				ASSERT(ill->ill_move_ipif == NULL);
3835 			}
3836 			continue;
3837 		}
3838 
3839 		mutex_enter(&ill->ill_lock);
3840 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3841 		ipif->ipif_flags |= IPIF_DUPLICATE;
3842 		ill->ill_ipif_dup_count++;
3843 		mutex_exit(&ill->ill_lock);
3844 		/*
3845 		 * Already exclusive on the ill; no need to handle deferred
3846 		 * processing here.
3847 		 */
3848 		(void) ipif_down(ipif, NULL, NULL);
3849 		ipif_down_tail(ipif);
3850 		mutex_enter(&ill->ill_lock);
3851 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3852 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3853 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3854 		    ipst->ips_ip_dup_recovery > 0) {
3855 			ASSERT(ipif->ipif_recovery_id == 0);
3856 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3857 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3858 		}
3859 		mutex_exit(&ill->ill_lock);
3860 	}
3861 	freemsg(mp);
3862 }
3863 
3864 /* ARGSUSED */
3865 static void
3866 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3867 {
3868 	ill_t	*ill = rq->q_ptr;
3869 	arh_t *arh;
3870 	ipaddr_t src;
3871 	ipif_t	*ipif;
3872 
3873 	arh = (arh_t *)mp->b_cont->b_rptr;
3874 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3875 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3876 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3877 			(void) ipif_resolver_up(ipif, Res_act_defend);
3878 	}
3879 	freemsg(mp);
3880 }
3881 
3882 /*
3883  * News from ARP.  ARP sends notification of interesting events down
3884  * to its clients using M_CTL messages with the interesting ARP packet
3885  * attached via b_cont.
3886  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3887  * queue as opposed to ARP sending the message to all the clients, i.e. all
3888  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3889  * table if a cache IRE is found to delete all the entries for the address in
3890  * the packet.
3891  */
3892 static void
3893 ip_arp_news(queue_t *q, mblk_t *mp)
3894 {
3895 	arcn_t		*arcn;
3896 	arh_t		*arh;
3897 	ire_t		*ire = NULL;
3898 	char		hbuf[MAC_STR_LEN];
3899 	char		sbuf[INET_ADDRSTRLEN];
3900 	ipaddr_t	src;
3901 	in6_addr_t	v6src;
3902 	boolean_t	isv6 = B_FALSE;
3903 	ipif_t		*ipif;
3904 	ill_t		*ill;
3905 	ip_stack_t	*ipst;
3906 
3907 	if (CONN_Q(q)) {
3908 		conn_t *connp = Q_TO_CONN(q);
3909 
3910 		ipst = connp->conn_netstack->netstack_ip;
3911 	} else {
3912 		ill_t *ill = (ill_t *)q->q_ptr;
3913 
3914 		ipst = ill->ill_ipst;
3915 	}
3916 
3917 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3918 		if (q->q_next) {
3919 			putnext(q, mp);
3920 		} else
3921 			freemsg(mp);
3922 		return;
3923 	}
3924 	arh = (arh_t *)mp->b_cont->b_rptr;
3925 	/* Is it one we are interested in? */
3926 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3927 		isv6 = B_TRUE;
3928 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3929 		    IPV6_ADDR_LEN);
3930 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3931 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3932 		    IP_ADDR_LEN);
3933 	} else {
3934 		freemsg(mp);
3935 		return;
3936 	}
3937 
3938 	ill = q->q_ptr;
3939 
3940 	arcn = (arcn_t *)mp->b_rptr;
3941 	switch (arcn->arcn_code) {
3942 	case AR_CN_BOGON:
3943 		/*
3944 		 * Someone is sending ARP packets with a source protocol
3945 		 * address that we have published and for which we believe our
3946 		 * entry is authoritative and (when ill_arp_extend is set)
3947 		 * verified to be unique on the network.
3948 		 *
3949 		 * The ARP module internally handles the cases where the sender
3950 		 * is just probing (for DAD) and where the hardware address of
3951 		 * a non-authoritative entry has changed.  Thus, these are the
3952 		 * real conflicts, and we have to do resolution.
3953 		 *
3954 		 * We back away quickly from the address if it's from DHCP or
3955 		 * otherwise temporary and hasn't been used recently (or at
3956 		 * all).  We'd like to include "deprecated" addresses here as
3957 		 * well (as there's no real reason to defend something we're
3958 		 * discarding), but IPMP "reuses" this flag to mean something
3959 		 * other than the standard meaning.
3960 		 *
3961 		 * If the ARP module above is not extended (meaning that it
3962 		 * doesn't know how to defend the address), then we just log
3963 		 * the problem as we always did and continue on.  It's not
3964 		 * right, but there's little else we can do, and those old ATM
3965 		 * users are going away anyway.
3966 		 */
3967 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3968 		    hbuf, sizeof (hbuf));
3969 		(void) ip_dot_addr(src, sbuf);
3970 		if (isv6) {
3971 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3972 			    ipst);
3973 		} else {
3974 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3975 		}
3976 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3977 			uint32_t now;
3978 			uint32_t maxage;
3979 			clock_t lused;
3980 			uint_t maxdefense;
3981 			uint_t defs;
3982 
3983 			/*
3984 			 * First, figure out if this address hasn't been used
3985 			 * in a while.  If it hasn't, then it's a better
3986 			 * candidate for abandoning.
3987 			 */
3988 			ipif = ire->ire_ipif;
3989 			ASSERT(ipif != NULL);
3990 			now = gethrestime_sec();
3991 			maxage = now - ire->ire_create_time;
3992 			if (maxage > ipst->ips_ip_max_temp_idle)
3993 				maxage = ipst->ips_ip_max_temp_idle;
3994 			lused = drv_hztousec(ddi_get_lbolt() -
3995 			    ire->ire_last_used_time) / MICROSEC + 1;
3996 			if (lused >= maxage && (ipif->ipif_flags &
3997 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3998 				maxdefense = ipst->ips_ip_max_temp_defend;
3999 			else
4000 				maxdefense = ipst->ips_ip_max_defend;
4001 
4002 			/*
4003 			 * Now figure out how many times we've defended
4004 			 * ourselves.  Ignore defenses that happened long in
4005 			 * the past.
4006 			 */
4007 			mutex_enter(&ire->ire_lock);
4008 			if ((defs = ire->ire_defense_count) > 0 &&
4009 			    now - ire->ire_defense_time >
4010 			    ipst->ips_ip_defend_interval) {
4011 				ire->ire_defense_count = defs = 0;
4012 			}
4013 			ire->ire_defense_count++;
4014 			ire->ire_defense_time = now;
4015 			mutex_exit(&ire->ire_lock);
4016 			ill_refhold(ill);
4017 			ire_refrele(ire);
4018 
4019 			/*
4020 			 * If we've defended ourselves too many times already,
4021 			 * then give up and tear down the interface(s) using
4022 			 * this address.  Otherwise, defend by sending out a
4023 			 * gratuitous ARP.
4024 			 */
4025 			if (defs >= maxdefense && ill->ill_arp_extend) {
4026 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4027 				    B_FALSE);
4028 			} else {
4029 				cmn_err(CE_WARN,
4030 				    "node %s is using our IP address %s on %s",
4031 				    hbuf, sbuf, ill->ill_name);
4032 				/*
4033 				 * If this is an old (ATM) ARP module, then
4034 				 * don't try to defend the address.  Remain
4035 				 * compatible with the old behavior.  Defend
4036 				 * only with new ARP.
4037 				 */
4038 				if (ill->ill_arp_extend) {
4039 					qwriter_ip(ill, q, mp, ip_arp_defend,
4040 					    NEW_OP, B_FALSE);
4041 				} else {
4042 					ill_refrele(ill);
4043 				}
4044 			}
4045 			return;
4046 		}
4047 		cmn_err(CE_WARN,
4048 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4049 		    hbuf, sbuf, ill->ill_name);
4050 		if (ire != NULL)
4051 			ire_refrele(ire);
4052 		break;
4053 	case AR_CN_ANNOUNCE:
4054 		if (isv6) {
4055 			/*
4056 			 * For XRESOLV interfaces.
4057 			 * Delete the IRE cache entry and NCE for this
4058 			 * v6 address
4059 			 */
4060 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4061 			/*
4062 			 * If v6src is a non-zero, it's a router address
4063 			 * as below. Do the same sort of thing to clean
4064 			 * out off-net IRE_CACHE entries that go through
4065 			 * the router.
4066 			 */
4067 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4068 				ire_walk_v6(ire_delete_cache_gw_v6,
4069 				    (char *)&v6src, ALL_ZONES, ipst);
4070 			}
4071 		} else {
4072 			nce_hw_map_t hwm;
4073 
4074 			/*
4075 			 * ARP gives us a copy of any packet where it thinks
4076 			 * the address has changed, so that we can update our
4077 			 * caches.  We're responsible for caching known answers
4078 			 * in the current design.  We check whether the
4079 			 * hardware address really has changed in all of our
4080 			 * entries that have cached this mapping, and if so, we
4081 			 * blow them away.  This way we will immediately pick
4082 			 * up the rare case of a host changing hardware
4083 			 * address.
4084 			 */
4085 			if (src == 0)
4086 				break;
4087 			hwm.hwm_addr = src;
4088 			hwm.hwm_hwlen = arh->arh_hlen;
4089 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4090 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4091 			ndp_walk_common(ipst->ips_ndp4, NULL,
4092 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4093 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4094 		}
4095 		break;
4096 	case AR_CN_READY:
4097 		/* No external v6 resolver has a contract to use this */
4098 		if (isv6)
4099 			break;
4100 		/* If the link is down, we'll retry this later */
4101 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4102 			break;
4103 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4104 		    NULL, NULL, ipst);
4105 		if (ipif != NULL) {
4106 			/*
4107 			 * If this is a duplicate recovery, then we now need to
4108 			 * go exclusive to bring this thing back up.
4109 			 */
4110 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4111 			    IPIF_DUPLICATE) {
4112 				ipif_refrele(ipif);
4113 				ill_refhold(ill);
4114 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4115 				    B_FALSE);
4116 				return;
4117 			}
4118 			/*
4119 			 * If this is the first notice that this address is
4120 			 * ready, then let the user know now.
4121 			 */
4122 			if ((ipif->ipif_flags & IPIF_UP) &&
4123 			    !ipif->ipif_addr_ready) {
4124 				ipif_mask_reply(ipif);
4125 				ipif_up_notify(ipif);
4126 			}
4127 			ipif->ipif_addr_ready = 1;
4128 			ipif_refrele(ipif);
4129 		}
4130 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4131 		if (ire != NULL) {
4132 			ire->ire_defense_count = 0;
4133 			ire_refrele(ire);
4134 		}
4135 		break;
4136 	case AR_CN_FAILED:
4137 		/* No external v6 resolver has a contract to use this */
4138 		if (isv6)
4139 			break;
4140 		if (!ill->ill_arp_extend) {
4141 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4142 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4143 			(void) ip_dot_addr(src, sbuf);
4144 
4145 			cmn_err(CE_WARN,
4146 			    "node %s is using our IP address %s on %s",
4147 			    hbuf, sbuf, ill->ill_name);
4148 			break;
4149 		}
4150 		ill_refhold(ill);
4151 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4152 		return;
4153 	}
4154 	freemsg(mp);
4155 }
4156 
4157 /*
4158  * Create a mblk suitable for carrying the interface index and/or source link
4159  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4160  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4161  * application.
4162  */
4163 mblk_t *
4164 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4165     ip_stack_t *ipst)
4166 {
4167 	mblk_t		*mp;
4168 	ip_pktinfo_t	*pinfo;
4169 	ipha_t 		*ipha;
4170 	struct ether_header *pether;
4171 	boolean_t	ipmp_ill_held = B_FALSE;
4172 
4173 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4174 	if (mp == NULL) {
4175 		ip1dbg(("ip_add_info: allocation failure.\n"));
4176 		return (data_mp);
4177 	}
4178 
4179 	ipha = (ipha_t *)data_mp->b_rptr;
4180 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4181 	bzero(pinfo, sizeof (ip_pktinfo_t));
4182 	pinfo->ip_pkt_flags = (uchar_t)flags;
4183 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4184 
4185 	pether = (struct ether_header *)((char *)ipha
4186 	    - sizeof (struct ether_header));
4187 
4188 	/*
4189 	 * Make sure the interface is an ethernet type, since this option
4190 	 * is currently supported only on this type of interface. Also make
4191 	 * sure we are pointing correctly above db_base.
4192 	 */
4193 	if ((flags & IPF_RECVSLLA) &&
4194 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4195 	    (ill->ill_type == IFT_ETHER) &&
4196 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4197 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4198 		bcopy(pether->ether_shost.ether_addr_octet,
4199 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4200 	} else {
4201 		/*
4202 		 * Clear the bit. Indicate to upper layer that IP is not
4203 		 * sending this ancillary info.
4204 		 */
4205 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4206 	}
4207 
4208 	/*
4209 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4210 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4211 	 * IPF_RECVADDR support on test addresses is not needed.)
4212 	 *
4213 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4214 	 * processing a packet looped back to an IPMP data address
4215 	 * (since those IRE_LOCALs are tied to IPMP ills).
4216 	 */
4217 	if (IS_UNDER_IPMP(ill)) {
4218 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4219 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4220 			freemsg(mp);
4221 			return (data_mp);
4222 		}
4223 		ipmp_ill_held = B_TRUE;
4224 	}
4225 
4226 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4227 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4228 	if (flags & IPF_RECVADDR) {
4229 		ipif_t	*ipif;
4230 		ire_t	*ire;
4231 
4232 		/*
4233 		 * Only valid for V4
4234 		 */
4235 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4236 		    (IPV4_VERSION << 4));
4237 
4238 		ipif = ipif_get_next_ipif(NULL, ill);
4239 		if (ipif != NULL) {
4240 			/*
4241 			 * Since a decision has already been made to deliver the
4242 			 * packet, there is no need to test for SECATTR and
4243 			 * ZONEONLY.
4244 			 * When a multicast packet is transmitted
4245 			 * a cache entry is created for the multicast address.
4246 			 * When delivering a copy of the packet or when new
4247 			 * packets are received we do not want to match on the
4248 			 * cached entry so explicitly match on
4249 			 * IRE_LOCAL and IRE_LOOPBACK
4250 			 */
4251 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4252 			    IRE_LOCAL | IRE_LOOPBACK,
4253 			    ipif, zoneid, NULL,
4254 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4255 			if (ire == NULL) {
4256 				/*
4257 				 * packet must have come on a different
4258 				 * interface.
4259 				 * Since a decision has already been made to
4260 				 * deliver the packet, there is no need to test
4261 				 * for SECATTR and ZONEONLY.
4262 				 * Only match on local and broadcast ire's.
4263 				 * See detailed comment above.
4264 				 */
4265 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4266 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4267 				    NULL, MATCH_IRE_TYPE, ipst);
4268 			}
4269 
4270 			if (ire == NULL) {
4271 				/*
4272 				 * This is either a multicast packet or
4273 				 * the address has been removed since
4274 				 * the packet was received.
4275 				 * Return INADDR_ANY so that normal source
4276 				 * selection occurs for the response.
4277 				 */
4278 
4279 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4280 			} else {
4281 				pinfo->ip_pkt_match_addr.s_addr =
4282 				    ire->ire_src_addr;
4283 				ire_refrele(ire);
4284 			}
4285 			ipif_refrele(ipif);
4286 		} else {
4287 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4288 		}
4289 	}
4290 
4291 	if (ipmp_ill_held)
4292 		ill_refrele(ill);
4293 
4294 	mp->b_datap->db_type = M_CTL;
4295 	mp->b_wptr += sizeof (ip_pktinfo_t);
4296 	mp->b_cont = data_mp;
4297 
4298 	return (mp);
4299 }
4300 
4301 /*
4302  * Used to determine the most accurate cred_t to use for TX.
4303  * First priority is SCM_UCRED having set the label in the message,
4304  * which is used for MLP on UDP. Second priority is the peers label (aka
4305  * conn_peercred), which is needed for MLP on TCP/SCTP. Last priority is the
4306  * open credentials.
4307  */
4308 cred_t *
4309 ip_best_cred(mblk_t *mp, conn_t *connp)
4310 {
4311 	cred_t *cr;
4312 
4313 	cr = msg_getcred(mp, NULL);
4314 	if (cr != NULL && crgetlabel(cr) != NULL)
4315 		return (cr);
4316 	return (CONN_CRED(connp));
4317 }
4318 
4319 /*
4320  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4321  * part of the bind request.
4322  */
4323 
4324 boolean_t
4325 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4326 {
4327 	ipsec_in_t *ii;
4328 
4329 	ASSERT(policy_mp != NULL);
4330 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4331 
4332 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4333 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4334 
4335 	connp->conn_policy = ii->ipsec_in_policy;
4336 	ii->ipsec_in_policy = NULL;
4337 
4338 	if (ii->ipsec_in_action != NULL) {
4339 		if (connp->conn_latch == NULL) {
4340 			connp->conn_latch = iplatch_create();
4341 			if (connp->conn_latch == NULL)
4342 				return (B_FALSE);
4343 		}
4344 		ipsec_latch_inbound(connp->conn_latch, ii);
4345 	}
4346 	return (B_TRUE);
4347 }
4348 
4349 static void
4350 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4351 {
4352 	/*
4353 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4354 	 * We can't do this in ip_bind_get_ire because the policy
4355 	 * may not have been inherited at that point in time and hence
4356 	 * conn_out_enforce_policy may not be set.
4357 	 */
4358 	if (ire_requested && connp->conn_out_enforce_policy &&
4359 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4360 		ire_t *ire = (ire_t *)mp->b_rptr;
4361 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4362 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4363 	}
4364 }
4365 
4366 /*
4367  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4368  * and to arrange for power-fanout assist.  The ULP is identified by
4369  * adding a single byte at the end of the original bind message.
4370  * A ULP other than UDP or TCP that wishes to be recognized passes
4371  * down a bind with a zero length address.
4372  *
4373  * The binding works as follows:
4374  * - A zero byte address means just bind to the protocol.
4375  * - A four byte address is treated as a request to validate
4376  *   that the address is a valid local address, appropriate for
4377  *   an application to bind to. This does not affect any fanout
4378  *   information in IP.
4379  * - A sizeof sin_t byte address is used to bind to only the local address
4380  *   and port.
4381  * - A sizeof ipa_conn_t byte address contains complete fanout information
4382  *   consisting of local and remote addresses and ports.  In
4383  *   this case, the addresses are both validated as appropriate
4384  *   for this operation, and, if so, the information is retained
4385  *   for use in the inbound fanout.
4386  *
4387  * The ULP (except in the zero-length bind) can append an
4388  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4389  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4390  * a copy of the source or destination IRE (source for local bind;
4391  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4392  * policy information contained should be copied on to the conn.
4393  *
4394  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4395  */
4396 mblk_t *
4397 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4398 {
4399 	ssize_t		len;
4400 	struct T_bind_req	*tbr;
4401 	sin_t		*sin;
4402 	ipa_conn_t	*ac;
4403 	uchar_t		*ucp;
4404 	mblk_t		*mp1;
4405 	boolean_t	ire_requested;
4406 	int		error = 0;
4407 	int		protocol;
4408 	ipa_conn_x_t	*acx;
4409 	cred_t		*cr;
4410 
4411 	/*
4412 	 * All Solaris components should pass a db_credp
4413 	 * for this TPI message, hence we ASSERT.
4414 	 * But in case there is some other M_PROTO that looks
4415 	 * like a TPI message sent by some other kernel
4416 	 * component, we check and return an error.
4417 	 */
4418 	cr = msg_getcred(mp, NULL);
4419 	ASSERT(cr != NULL);
4420 	if (cr == NULL) {
4421 		error = EINVAL;
4422 		goto bad_addr;
4423 	}
4424 
4425 	ASSERT(!connp->conn_af_isv6);
4426 	connp->conn_pkt_isv6 = B_FALSE;
4427 
4428 	len = MBLKL(mp);
4429 	if (len < (sizeof (*tbr) + 1)) {
4430 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4431 		    "ip_bind: bogus msg, len %ld", len);
4432 		/* XXX: Need to return something better */
4433 		goto bad_addr;
4434 	}
4435 	/* Back up and extract the protocol identifier. */
4436 	mp->b_wptr--;
4437 	protocol = *mp->b_wptr & 0xFF;
4438 	tbr = (struct T_bind_req *)mp->b_rptr;
4439 	/* Reset the message type in preparation for shipping it back. */
4440 	DB_TYPE(mp) = M_PCPROTO;
4441 
4442 	connp->conn_ulp = (uint8_t)protocol;
4443 
4444 	/*
4445 	 * Check for a zero length address.  This is from a protocol that
4446 	 * wants to register to receive all packets of its type.
4447 	 */
4448 	if (tbr->ADDR_length == 0) {
4449 		/*
4450 		 * These protocols are now intercepted in ip_bind_v6().
4451 		 * Reject protocol-level binds here for now.
4452 		 *
4453 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4454 		 * so that the protocol type cannot be SCTP.
4455 		 */
4456 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4457 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4458 			goto bad_addr;
4459 		}
4460 
4461 		/*
4462 		 *
4463 		 * The udp module never sends down a zero-length address,
4464 		 * and allowing this on a labeled system will break MLP
4465 		 * functionality.
4466 		 */
4467 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4468 			goto bad_addr;
4469 
4470 		if (connp->conn_mac_exempt)
4471 			goto bad_addr;
4472 
4473 		/* No hash here really.  The table is big enough. */
4474 		connp->conn_srcv6 = ipv6_all_zeros;
4475 
4476 		ipcl_proto_insert(connp, protocol);
4477 
4478 		tbr->PRIM_type = T_BIND_ACK;
4479 		return (mp);
4480 	}
4481 
4482 	/* Extract the address pointer from the message. */
4483 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4484 	    tbr->ADDR_length);
4485 	if (ucp == NULL) {
4486 		ip1dbg(("ip_bind: no address\n"));
4487 		goto bad_addr;
4488 	}
4489 	if (!OK_32PTR(ucp)) {
4490 		ip1dbg(("ip_bind: unaligned address\n"));
4491 		goto bad_addr;
4492 	}
4493 	/*
4494 	 * Check for trailing mps.
4495 	 */
4496 
4497 	mp1 = mp->b_cont;
4498 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4499 
4500 	switch (tbr->ADDR_length) {
4501 	default:
4502 		ip1dbg(("ip_bind: bad address length %d\n",
4503 		    (int)tbr->ADDR_length));
4504 		goto bad_addr;
4505 
4506 	case IP_ADDR_LEN:
4507 		/* Verification of local address only */
4508 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4509 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4510 		break;
4511 
4512 	case sizeof (sin_t):
4513 		sin = (sin_t *)ucp;
4514 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4515 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4516 		break;
4517 
4518 	case sizeof (ipa_conn_t):
4519 		ac = (ipa_conn_t *)ucp;
4520 		/* For raw socket, the local port is not set. */
4521 		if (ac->ac_lport == 0)
4522 			ac->ac_lport = connp->conn_lport;
4523 		/* Always verify destination reachability. */
4524 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4525 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4526 		    B_TRUE, B_TRUE, cr);
4527 		break;
4528 
4529 	case sizeof (ipa_conn_x_t):
4530 		acx = (ipa_conn_x_t *)ucp;
4531 		/*
4532 		 * Whether or not to verify destination reachability depends
4533 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4534 		 */
4535 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4536 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4537 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4538 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4539 		break;
4540 	}
4541 	ASSERT(error != EINPROGRESS);
4542 	if (error != 0)
4543 		goto bad_addr;
4544 
4545 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4546 
4547 	/* Send it home. */
4548 	mp->b_datap->db_type = M_PCPROTO;
4549 	tbr->PRIM_type = T_BIND_ACK;
4550 	return (mp);
4551 
4552 bad_addr:
4553 	/*
4554 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4555 	 * a unix errno.
4556 	 */
4557 	if (error > 0)
4558 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4559 	else
4560 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4561 	return (mp);
4562 }
4563 
4564 /*
4565  * Here address is verified to be a valid local address.
4566  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4567  * address is also considered a valid local address.
4568  * In the case of a broadcast/multicast address, however, the
4569  * upper protocol is expected to reset the src address
4570  * to 0 if it sees a IRE_BROADCAST type returned so that
4571  * no packets are emitted with broadcast/multicast address as
4572  * source address (that violates hosts requirements RFC 1122)
4573  * The addresses valid for bind are:
4574  *	(1) - INADDR_ANY (0)
4575  *	(2) - IP address of an UP interface
4576  *	(3) - IP address of a DOWN interface
4577  *	(4) - valid local IP broadcast addresses. In this case
4578  *	the conn will only receive packets destined to
4579  *	the specified broadcast address.
4580  *	(5) - a multicast address. In this case
4581  *	the conn will only receive packets destined to
4582  *	the specified multicast address. Note: the
4583  *	application still has to issue an
4584  *	IP_ADD_MEMBERSHIP socket option.
4585  *
4586  * On error, return -1 for TBADADDR otherwise pass the
4587  * errno with TSYSERR reply.
4588  *
4589  * In all the above cases, the bound address must be valid in the current zone.
4590  * When the address is loopback, multicast or broadcast, there might be many
4591  * matching IREs so bind has to look up based on the zone.
4592  *
4593  * Note: lport is in network byte order.
4594  *
4595  */
4596 int
4597 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4598     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4599 {
4600 	int		error = 0;
4601 	ire_t		*src_ire;
4602 	zoneid_t	zoneid;
4603 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4604 	mblk_t		*mp = NULL;
4605 	boolean_t	ire_requested = B_FALSE;
4606 	boolean_t	ipsec_policy_set = B_FALSE;
4607 
4608 	if (mpp)
4609 		mp = *mpp;
4610 
4611 	if (mp != NULL) {
4612 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4613 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4614 	}
4615 
4616 	/*
4617 	 * If it was previously connected, conn_fully_bound would have
4618 	 * been set.
4619 	 */
4620 	connp->conn_fully_bound = B_FALSE;
4621 
4622 	src_ire = NULL;
4623 
4624 	zoneid = IPCL_ZONEID(connp);
4625 
4626 	if (src_addr) {
4627 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4628 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4629 		/*
4630 		 * If an address other than 0.0.0.0 is requested,
4631 		 * we verify that it is a valid address for bind
4632 		 * Note: Following code is in if-else-if form for
4633 		 * readability compared to a condition check.
4634 		 */
4635 		/* LINTED - statement has no consequence */
4636 		if (IRE_IS_LOCAL(src_ire)) {
4637 			/*
4638 			 * (2) Bind to address of local UP interface
4639 			 */
4640 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4641 			/*
4642 			 * (4) Bind to broadcast address
4643 			 * Note: permitted only from transports that
4644 			 * request IRE
4645 			 */
4646 			if (!ire_requested)
4647 				error = EADDRNOTAVAIL;
4648 		} else {
4649 			/*
4650 			 * (3) Bind to address of local DOWN interface
4651 			 * (ipif_lookup_addr() looks up all interfaces
4652 			 * but we do not get here for UP interfaces
4653 			 * - case (2) above)
4654 			 */
4655 			/* LINTED - statement has no consequent */
4656 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4657 				/* The address exists */
4658 			} else if (CLASSD(src_addr)) {
4659 				error = 0;
4660 				if (src_ire != NULL)
4661 					ire_refrele(src_ire);
4662 				/*
4663 				 * (5) bind to multicast address.
4664 				 * Fake out the IRE returned to upper
4665 				 * layer to be a broadcast IRE.
4666 				 */
4667 				src_ire = ire_ctable_lookup(
4668 				    INADDR_BROADCAST, INADDR_ANY,
4669 				    IRE_BROADCAST, NULL, zoneid, NULL,
4670 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4671 				    ipst);
4672 				if (src_ire == NULL || !ire_requested)
4673 					error = EADDRNOTAVAIL;
4674 			} else {
4675 				/*
4676 				 * Not a valid address for bind
4677 				 */
4678 				error = EADDRNOTAVAIL;
4679 			}
4680 		}
4681 		if (error) {
4682 			/* Red Alert!  Attempting to be a bogon! */
4683 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4684 			    ntohl(src_addr)));
4685 			goto bad_addr;
4686 		}
4687 	}
4688 
4689 	/*
4690 	 * Allow setting new policies. For example, disconnects come
4691 	 * down as ipa_t bind. As we would have set conn_policy_cached
4692 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4693 	 * can change after the disconnect.
4694 	 */
4695 	connp->conn_policy_cached = B_FALSE;
4696 
4697 	/*
4698 	 * If not fanout_insert this was just an address verification
4699 	 */
4700 	if (fanout_insert) {
4701 		/*
4702 		 * The addresses have been verified. Time to insert in
4703 		 * the correct fanout list.
4704 		 */
4705 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4706 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4707 		connp->conn_lport = lport;
4708 		connp->conn_fport = 0;
4709 		/*
4710 		 * Do we need to add a check to reject Multicast packets
4711 		 */
4712 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4713 	}
4714 
4715 	if (error == 0) {
4716 		if (ire_requested) {
4717 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4718 				error = -1;
4719 				/* Falls through to bad_addr */
4720 			}
4721 		} else if (ipsec_policy_set) {
4722 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4723 				error = -1;
4724 				/* Falls through to bad_addr */
4725 			}
4726 		}
4727 	}
4728 bad_addr:
4729 	if (error != 0) {
4730 		if (connp->conn_anon_port) {
4731 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4732 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4733 			    B_FALSE);
4734 		}
4735 		connp->conn_mlp_type = mlptSingle;
4736 	}
4737 	if (src_ire != NULL)
4738 		IRE_REFRELE(src_ire);
4739 	return (error);
4740 }
4741 
4742 int
4743 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4744     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4745 {
4746 	int error;
4747 	mblk_t	*mp = NULL;
4748 	boolean_t ire_requested;
4749 
4750 	if (ire_mpp)
4751 		mp = *ire_mpp;
4752 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4753 
4754 	ASSERT(!connp->conn_af_isv6);
4755 	connp->conn_pkt_isv6 = B_FALSE;
4756 	connp->conn_ulp = protocol;
4757 
4758 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4759 	    fanout_insert);
4760 	if (error == 0) {
4761 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4762 		    ire_requested);
4763 	} else if (error < 0) {
4764 		error = -TBADADDR;
4765 	}
4766 	return (error);
4767 }
4768 
4769 /*
4770  * Verify that both the source and destination addresses
4771  * are valid.  If verify_dst is false, then the destination address may be
4772  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4773  * destination reachability, while tunnels do not.
4774  * Note that we allow connect to broadcast and multicast
4775  * addresses when ire_requested is set. Thus the ULP
4776  * has to check for IRE_BROADCAST and multicast.
4777  *
4778  * Returns zero if ok.
4779  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4780  * (for use with TSYSERR reply).
4781  *
4782  * Note: lport and fport are in network byte order.
4783  */
4784 int
4785 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4786     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4787     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4788 {
4789 
4790 	ire_t		*src_ire;
4791 	ire_t		*dst_ire;
4792 	int		error = 0;
4793 	ire_t		*sire = NULL;
4794 	ire_t		*md_dst_ire = NULL;
4795 	ire_t		*lso_dst_ire = NULL;
4796 	ill_t		*ill = NULL;
4797 	zoneid_t	zoneid;
4798 	ipaddr_t	src_addr = *src_addrp;
4799 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4800 	mblk_t		*mp = NULL;
4801 	boolean_t	ire_requested = B_FALSE;
4802 	boolean_t	ipsec_policy_set = B_FALSE;
4803 	ts_label_t	*tsl = NULL;
4804 
4805 	if (mpp)
4806 		mp = *mpp;
4807 
4808 	if (mp != NULL) {
4809 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4810 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4811 	}
4812 	if (cr != NULL)
4813 		tsl = crgetlabel(cr);
4814 
4815 	src_ire = dst_ire = NULL;
4816 
4817 	/*
4818 	 * If we never got a disconnect before, clear it now.
4819 	 */
4820 	connp->conn_fully_bound = B_FALSE;
4821 
4822 	zoneid = IPCL_ZONEID(connp);
4823 
4824 	if (CLASSD(dst_addr)) {
4825 		/* Pick up an IRE_BROADCAST */
4826 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4827 		    NULL, zoneid, tsl,
4828 		    (MATCH_IRE_RECURSIVE |
4829 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4830 		    MATCH_IRE_SECATTR), ipst);
4831 	} else {
4832 		/*
4833 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4834 		 * and onlink ipif is not found set ENETUNREACH error.
4835 		 */
4836 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4837 			ipif_t *ipif;
4838 
4839 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4840 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4841 			if (ipif == NULL) {
4842 				error = ENETUNREACH;
4843 				goto bad_addr;
4844 			}
4845 			ipif_refrele(ipif);
4846 		}
4847 
4848 		if (connp->conn_nexthop_set) {
4849 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4850 			    0, 0, NULL, NULL, zoneid, tsl,
4851 			    MATCH_IRE_SECATTR, ipst);
4852 		} else {
4853 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4854 			    &sire, zoneid, tsl,
4855 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4856 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4857 			    MATCH_IRE_SECATTR), ipst);
4858 		}
4859 	}
4860 	/*
4861 	 * dst_ire can't be a broadcast when not ire_requested.
4862 	 * We also prevent ire's with src address INADDR_ANY to
4863 	 * be used, which are created temporarily for
4864 	 * sending out packets from endpoints that have
4865 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4866 	 * reachable.  If verify_dst is false, the destination needn't be
4867 	 * reachable.
4868 	 *
4869 	 * If we match on a reject or black hole, then we've got a
4870 	 * local failure.  May as well fail out the connect() attempt,
4871 	 * since it's never going to succeed.
4872 	 */
4873 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4874 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4875 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4876 		/*
4877 		 * If we're verifying destination reachability, we always want
4878 		 * to complain here.
4879 		 *
4880 		 * If we're not verifying destination reachability but the
4881 		 * destination has a route, we still want to fail on the
4882 		 * temporary address and broadcast address tests.
4883 		 */
4884 		if (verify_dst || (dst_ire != NULL)) {
4885 			if (ip_debug > 2) {
4886 				pr_addr_dbg("ip_bind_connected_v4:"
4887 				    "bad connected dst %s\n",
4888 				    AF_INET, &dst_addr);
4889 			}
4890 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4891 				error = ENETUNREACH;
4892 			else
4893 				error = EHOSTUNREACH;
4894 			goto bad_addr;
4895 		}
4896 	}
4897 
4898 	/*
4899 	 * We now know that routing will allow us to reach the destination.
4900 	 * Check whether Trusted Solaris policy allows communication with this
4901 	 * host, and pretend that the destination is unreachable if not.
4902 	 *
4903 	 * This is never a problem for TCP, since that transport is known to
4904 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4905 	 * handling.  If the remote is unreachable, it will be detected at that
4906 	 * point, so there's no reason to check it here.
4907 	 *
4908 	 * Note that for sendto (and other datagram-oriented friends), this
4909 	 * check is done as part of the data path label computation instead.
4910 	 * The check here is just to make non-TCP connect() report the right
4911 	 * error.
4912 	 */
4913 	if (dst_ire != NULL && is_system_labeled() &&
4914 	    !IPCL_IS_TCP(connp) &&
4915 	    tsol_compute_label(cr, dst_addr, NULL,
4916 	    connp->conn_mac_exempt, ipst) != 0) {
4917 		error = EHOSTUNREACH;
4918 		if (ip_debug > 2) {
4919 			pr_addr_dbg("ip_bind_connected_v4:"
4920 			    " no label for dst %s\n",
4921 			    AF_INET, &dst_addr);
4922 		}
4923 		goto bad_addr;
4924 	}
4925 
4926 	/*
4927 	 * If the app does a connect(), it means that it will most likely
4928 	 * send more than 1 packet to the destination.  It makes sense
4929 	 * to clear the temporary flag.
4930 	 */
4931 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4932 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4933 		irb_t *irb = dst_ire->ire_bucket;
4934 
4935 		rw_enter(&irb->irb_lock, RW_WRITER);
4936 		/*
4937 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4938 		 * the lock to guarantee irb_tmp_ire_cnt.
4939 		 */
4940 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4941 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4942 			irb->irb_tmp_ire_cnt--;
4943 		}
4944 		rw_exit(&irb->irb_lock);
4945 	}
4946 
4947 	/*
4948 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4949 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4950 	 * eligibility tests for passive connects are handled separately
4951 	 * through tcp_adapt_ire().  We do this before the source address
4952 	 * selection, because dst_ire may change after a call to
4953 	 * ipif_select_source().  This is a best-effort check, as the
4954 	 * packet for this connection may not actually go through
4955 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4956 	 * calling ip_newroute().  This is why we further check on the
4957 	 * IRE during LSO/Multidata packet transmission in
4958 	 * tcp_lsosend()/tcp_multisend().
4959 	 */
4960 	if (!ipsec_policy_set && dst_ire != NULL &&
4961 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4962 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4963 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4964 			lso_dst_ire = dst_ire;
4965 			IRE_REFHOLD(lso_dst_ire);
4966 		} else if (ipst->ips_ip_multidata_outbound &&
4967 		    ILL_MDT_CAPABLE(ill)) {
4968 			md_dst_ire = dst_ire;
4969 			IRE_REFHOLD(md_dst_ire);
4970 		}
4971 	}
4972 
4973 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4974 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4975 		/*
4976 		 * If the IRE belongs to a different zone, look for a matching
4977 		 * route in the forwarding table and use the source address from
4978 		 * that route.
4979 		 */
4980 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4981 		    zoneid, 0, NULL,
4982 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4983 		    MATCH_IRE_RJ_BHOLE, ipst);
4984 		if (src_ire == NULL) {
4985 			error = EHOSTUNREACH;
4986 			goto bad_addr;
4987 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4988 			if (!(src_ire->ire_type & IRE_HOST))
4989 				error = ENETUNREACH;
4990 			else
4991 				error = EHOSTUNREACH;
4992 			goto bad_addr;
4993 		}
4994 		if (src_addr == INADDR_ANY)
4995 			src_addr = src_ire->ire_src_addr;
4996 		ire_refrele(src_ire);
4997 		src_ire = NULL;
4998 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4999 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
5000 			src_addr = sire->ire_src_addr;
5001 			ire_refrele(dst_ire);
5002 			dst_ire = sire;
5003 			sire = NULL;
5004 		} else {
5005 			/*
5006 			 * Pick a source address so that a proper inbound
5007 			 * load spreading would happen.
5008 			 */
5009 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
5010 			ipif_t *src_ipif = NULL;
5011 			ire_t *ipif_ire;
5012 
5013 			/*
5014 			 * Supply a local source address such that inbound
5015 			 * load spreading happens.
5016 			 *
5017 			 * Determine the best source address on this ill for
5018 			 * the destination.
5019 			 *
5020 			 * 1) For broadcast, we should return a broadcast ire
5021 			 *    found above so that upper layers know that the
5022 			 *    destination address is a broadcast address.
5023 			 *
5024 			 * 2) If the ipif is DEPRECATED, select a better
5025 			 *    source address.  Similarly, if the ipif is on
5026 			 *    the IPMP meta-interface, pick a source address
5027 			 *    at random to improve inbound load spreading.
5028 			 *
5029 			 * 3) If the outgoing interface is part of a usesrc
5030 			 *    group, then try selecting a source address from
5031 			 *    the usesrc ILL.
5032 			 */
5033 			if ((dst_ire->ire_zoneid != zoneid &&
5034 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5035 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5036 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5037 			    (IS_IPMP(ire_ill) ||
5038 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5039 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
5040 				/*
5041 				 * If the destination is reachable via a
5042 				 * given gateway, the selected source address
5043 				 * should be in the same subnet as the gateway.
5044 				 * Otherwise, the destination is not reachable.
5045 				 *
5046 				 * If there are no interfaces on the same subnet
5047 				 * as the destination, ipif_select_source gives
5048 				 * first non-deprecated interface which might be
5049 				 * on a different subnet than the gateway.
5050 				 * This is not desirable. Hence pass the dst_ire
5051 				 * source address to ipif_select_source.
5052 				 * It is sure that the destination is reachable
5053 				 * with the dst_ire source address subnet.
5054 				 * So passing dst_ire source address to
5055 				 * ipif_select_source will make sure that the
5056 				 * selected source will be on the same subnet
5057 				 * as dst_ire source address.
5058 				 */
5059 				ipaddr_t saddr =
5060 				    dst_ire->ire_ipif->ipif_src_addr;
5061 				src_ipif = ipif_select_source(ire_ill,
5062 				    saddr, zoneid);
5063 				if (src_ipif != NULL) {
5064 					if (IS_VNI(src_ipif->ipif_ill)) {
5065 						/*
5066 						 * For VNI there is no
5067 						 * interface route
5068 						 */
5069 						src_addr =
5070 						    src_ipif->ipif_src_addr;
5071 					} else {
5072 						ipif_ire =
5073 						    ipif_to_ire(src_ipif);
5074 						if (ipif_ire != NULL) {
5075 							IRE_REFRELE(dst_ire);
5076 							dst_ire = ipif_ire;
5077 						}
5078 						src_addr =
5079 						    dst_ire->ire_src_addr;
5080 					}
5081 					ipif_refrele(src_ipif);
5082 				} else {
5083 					src_addr = dst_ire->ire_src_addr;
5084 				}
5085 			} else {
5086 				src_addr = dst_ire->ire_src_addr;
5087 			}
5088 		}
5089 	}
5090 
5091 	/*
5092 	 * We do ire_route_lookup() here (and not
5093 	 * interface lookup as we assert that
5094 	 * src_addr should only come from an
5095 	 * UP interface for hard binding.
5096 	 */
5097 	ASSERT(src_ire == NULL);
5098 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5099 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5100 	/* src_ire must be a local|loopback */
5101 	if (!IRE_IS_LOCAL(src_ire)) {
5102 		if (ip_debug > 2) {
5103 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5104 			    "src %s\n", AF_INET, &src_addr);
5105 		}
5106 		error = EADDRNOTAVAIL;
5107 		goto bad_addr;
5108 	}
5109 
5110 	/*
5111 	 * If the source address is a loopback address, the
5112 	 * destination had best be local or multicast.
5113 	 * The transports that can't handle multicast will reject
5114 	 * those addresses.
5115 	 */
5116 	if (src_ire->ire_type == IRE_LOOPBACK &&
5117 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5118 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5119 		error = -1;
5120 		goto bad_addr;
5121 	}
5122 
5123 	/*
5124 	 * Allow setting new policies. For example, disconnects come
5125 	 * down as ipa_t bind. As we would have set conn_policy_cached
5126 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5127 	 * can change after the disconnect.
5128 	 */
5129 	connp->conn_policy_cached = B_FALSE;
5130 
5131 	/*
5132 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5133 	 * can handle their passed-in conn's.
5134 	 */
5135 
5136 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5137 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5138 	connp->conn_lport = lport;
5139 	connp->conn_fport = fport;
5140 	*src_addrp = src_addr;
5141 
5142 	ASSERT(!(ipsec_policy_set && ire_requested));
5143 	if (ire_requested) {
5144 		iulp_t *ulp_info = NULL;
5145 
5146 		/*
5147 		 * Note that sire will not be NULL if this is an off-link
5148 		 * connection and there is not cache for that dest yet.
5149 		 *
5150 		 * XXX Because of an existing bug, if there are multiple
5151 		 * default routes, the IRE returned now may not be the actual
5152 		 * default route used (default routes are chosen in a
5153 		 * round robin fashion).  So if the metrics for different
5154 		 * default routes are different, we may return the wrong
5155 		 * metrics.  This will not be a problem if the existing
5156 		 * bug is fixed.
5157 		 */
5158 		if (sire != NULL) {
5159 			ulp_info = &(sire->ire_uinfo);
5160 		}
5161 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5162 			error = -1;
5163 			goto bad_addr;
5164 		}
5165 		mp = *mpp;
5166 	} else if (ipsec_policy_set) {
5167 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5168 			error = -1;
5169 			goto bad_addr;
5170 		}
5171 	}
5172 
5173 	/*
5174 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5175 	 * we'll cache that.  If we don't, we'll inherit global policy.
5176 	 *
5177 	 * We can't insert until the conn reflects the policy. Note that
5178 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5179 	 * connections where we don't have a policy. This is to prevent
5180 	 * global policy lookups in the inbound path.
5181 	 *
5182 	 * If we insert before we set conn_policy_cached,
5183 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5184 	 * because global policy cound be non-empty. We normally call
5185 	 * ipsec_check_policy() for conn_policy_cached connections only if
5186 	 * ipc_in_enforce_policy is set. But in this case,
5187 	 * conn_policy_cached can get set anytime since we made the
5188 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5189 	 * called, which will make the above assumption false.  Thus, we
5190 	 * need to insert after we set conn_policy_cached.
5191 	 */
5192 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5193 		goto bad_addr;
5194 
5195 	if (fanout_insert) {
5196 		/*
5197 		 * The addresses have been verified. Time to insert in
5198 		 * the correct fanout list.
5199 		 */
5200 		error = ipcl_conn_insert(connp, protocol, src_addr,
5201 		    dst_addr, connp->conn_ports);
5202 	}
5203 
5204 	if (error == 0) {
5205 		connp->conn_fully_bound = B_TRUE;
5206 		/*
5207 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5208 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5209 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5210 		 * ip_xxinfo_return(), which performs further checks
5211 		 * against them and upon success, returns the LSO/MDT info
5212 		 * mblk which we will attach to the bind acknowledgment.
5213 		 */
5214 		if (lso_dst_ire != NULL) {
5215 			mblk_t *lsoinfo_mp;
5216 
5217 			ASSERT(ill->ill_lso_capab != NULL);
5218 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5219 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5220 				if (mp == NULL) {
5221 					*mpp = lsoinfo_mp;
5222 				} else {
5223 					linkb(mp, lsoinfo_mp);
5224 				}
5225 			}
5226 		} else if (md_dst_ire != NULL) {
5227 			mblk_t *mdinfo_mp;
5228 
5229 			ASSERT(ill->ill_mdt_capab != NULL);
5230 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5231 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5232 				if (mp == NULL) {
5233 					*mpp = mdinfo_mp;
5234 				} else {
5235 					linkb(mp, mdinfo_mp);
5236 				}
5237 			}
5238 		}
5239 	}
5240 bad_addr:
5241 	if (ipsec_policy_set) {
5242 		ASSERT(mp != NULL);
5243 		freeb(mp);
5244 		/*
5245 		 * As of now assume that nothing else accompanies
5246 		 * IPSEC_POLICY_SET.
5247 		 */
5248 		*mpp = NULL;
5249 	}
5250 	if (src_ire != NULL)
5251 		IRE_REFRELE(src_ire);
5252 	if (dst_ire != NULL)
5253 		IRE_REFRELE(dst_ire);
5254 	if (sire != NULL)
5255 		IRE_REFRELE(sire);
5256 	if (md_dst_ire != NULL)
5257 		IRE_REFRELE(md_dst_ire);
5258 	if (lso_dst_ire != NULL)
5259 		IRE_REFRELE(lso_dst_ire);
5260 	return (error);
5261 }
5262 
5263 int
5264 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5265     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5266     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5267 {
5268 	int error;
5269 	mblk_t	*mp = NULL;
5270 	boolean_t ire_requested;
5271 
5272 	if (ire_mpp)
5273 		mp = *ire_mpp;
5274 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5275 
5276 	ASSERT(!connp->conn_af_isv6);
5277 	connp->conn_pkt_isv6 = B_FALSE;
5278 	connp->conn_ulp = protocol;
5279 
5280 	/* For raw socket, the local port is not set. */
5281 	if (lport == 0)
5282 		lport = connp->conn_lport;
5283 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5284 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5285 	if (error == 0) {
5286 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5287 		    ire_requested);
5288 	} else if (error < 0) {
5289 		error = -TBADADDR;
5290 	}
5291 	return (error);
5292 }
5293 
5294 /*
5295  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5296  * Prefers dst_ire over src_ire.
5297  */
5298 static boolean_t
5299 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5300 {
5301 	mblk_t	*mp = *mpp;
5302 	ire_t	*ret_ire;
5303 
5304 	ASSERT(mp != NULL);
5305 
5306 	if (ire != NULL) {
5307 		/*
5308 		 * mp initialized above to IRE_DB_REQ_TYPE
5309 		 * appended mblk. Its <upper protocol>'s
5310 		 * job to make sure there is room.
5311 		 */
5312 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5313 			return (B_FALSE);
5314 
5315 		mp->b_datap->db_type = IRE_DB_TYPE;
5316 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5317 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5318 		ret_ire = (ire_t *)mp->b_rptr;
5319 		/*
5320 		 * Pass the latest setting of the ip_path_mtu_discovery and
5321 		 * copy the ulp info if any.
5322 		 */
5323 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5324 		    IPH_DF : 0;
5325 		if (ulp_info != NULL) {
5326 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5327 			    sizeof (iulp_t));
5328 		}
5329 		ret_ire->ire_mp = mp;
5330 	} else {
5331 		/*
5332 		 * No IRE was found. Remove IRE mblk.
5333 		 */
5334 		*mpp = mp->b_cont;
5335 		freeb(mp);
5336 	}
5337 	return (B_TRUE);
5338 }
5339 
5340 /*
5341  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5342  * the final piece where we don't.  Return a pointer to the first mblk in the
5343  * result, and update the pointer to the next mblk to chew on.  If anything
5344  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5345  * NULL pointer.
5346  */
5347 mblk_t *
5348 ip_carve_mp(mblk_t **mpp, ssize_t len)
5349 {
5350 	mblk_t	*mp0;
5351 	mblk_t	*mp1;
5352 	mblk_t	*mp2;
5353 
5354 	if (!len || !mpp || !(mp0 = *mpp))
5355 		return (NULL);
5356 	/* If we aren't going to consume the first mblk, we need a dup. */
5357 	if (mp0->b_wptr - mp0->b_rptr > len) {
5358 		mp1 = dupb(mp0);
5359 		if (mp1) {
5360 			/* Partition the data between the two mblks. */
5361 			mp1->b_wptr = mp1->b_rptr + len;
5362 			mp0->b_rptr = mp1->b_wptr;
5363 			/*
5364 			 * after adjustments if mblk not consumed is now
5365 			 * unaligned, try to align it. If this fails free
5366 			 * all messages and let upper layer recover.
5367 			 */
5368 			if (!OK_32PTR(mp0->b_rptr)) {
5369 				if (!pullupmsg(mp0, -1)) {
5370 					freemsg(mp0);
5371 					freemsg(mp1);
5372 					*mpp = NULL;
5373 					return (NULL);
5374 				}
5375 			}
5376 		}
5377 		return (mp1);
5378 	}
5379 	/* Eat through as many mblks as we need to get len bytes. */
5380 	len -= mp0->b_wptr - mp0->b_rptr;
5381 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5382 		if (mp2->b_wptr - mp2->b_rptr > len) {
5383 			/*
5384 			 * We won't consume the entire last mblk.  Like
5385 			 * above, dup and partition it.
5386 			 */
5387 			mp1->b_cont = dupb(mp2);
5388 			mp1 = mp1->b_cont;
5389 			if (!mp1) {
5390 				/*
5391 				 * Trouble.  Rather than go to a lot of
5392 				 * trouble to clean up, we free the messages.
5393 				 * This won't be any worse than losing it on
5394 				 * the wire.
5395 				 */
5396 				freemsg(mp0);
5397 				freemsg(mp2);
5398 				*mpp = NULL;
5399 				return (NULL);
5400 			}
5401 			mp1->b_wptr = mp1->b_rptr + len;
5402 			mp2->b_rptr = mp1->b_wptr;
5403 			/*
5404 			 * after adjustments if mblk not consumed is now
5405 			 * unaligned, try to align it. If this fails free
5406 			 * all messages and let upper layer recover.
5407 			 */
5408 			if (!OK_32PTR(mp2->b_rptr)) {
5409 				if (!pullupmsg(mp2, -1)) {
5410 					freemsg(mp0);
5411 					freemsg(mp2);
5412 					*mpp = NULL;
5413 					return (NULL);
5414 				}
5415 			}
5416 			*mpp = mp2;
5417 			return (mp0);
5418 		}
5419 		/* Decrement len by the amount we just got. */
5420 		len -= mp2->b_wptr - mp2->b_rptr;
5421 	}
5422 	/*
5423 	 * len should be reduced to zero now.  If not our caller has
5424 	 * screwed up.
5425 	 */
5426 	if (len) {
5427 		/* Shouldn't happen! */
5428 		freemsg(mp0);
5429 		*mpp = NULL;
5430 		return (NULL);
5431 	}
5432 	/*
5433 	 * We consumed up to exactly the end of an mblk.  Detach the part
5434 	 * we are returning from the rest of the chain.
5435 	 */
5436 	mp1->b_cont = NULL;
5437 	*mpp = mp2;
5438 	return (mp0);
5439 }
5440 
5441 /* The ill stream is being unplumbed. Called from ip_close */
5442 int
5443 ip_modclose(ill_t *ill)
5444 {
5445 	boolean_t success;
5446 	ipsq_t	*ipsq;
5447 	ipif_t	*ipif;
5448 	queue_t	*q = ill->ill_rq;
5449 	ip_stack_t	*ipst = ill->ill_ipst;
5450 	int	i;
5451 
5452 	/*
5453 	 * The punlink prior to this may have initiated a capability
5454 	 * negotiation. But ipsq_enter will block until that finishes or
5455 	 * times out.
5456 	 */
5457 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5458 
5459 	/*
5460 	 * Open/close/push/pop is guaranteed to be single threaded
5461 	 * per stream by STREAMS. FS guarantees that all references
5462 	 * from top are gone before close is called. So there can't
5463 	 * be another close thread that has set CONDEMNED on this ill.
5464 	 * and cause ipsq_enter to return failure.
5465 	 */
5466 	ASSERT(success);
5467 	ipsq = ill->ill_phyint->phyint_ipsq;
5468 
5469 	/*
5470 	 * Mark it condemned. No new reference will be made to this ill.
5471 	 * Lookup functions will return an error. Threads that try to
5472 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5473 	 * that the refcnt will drop down to zero.
5474 	 */
5475 	mutex_enter(&ill->ill_lock);
5476 	ill->ill_state_flags |= ILL_CONDEMNED;
5477 	for (ipif = ill->ill_ipif; ipif != NULL;
5478 	    ipif = ipif->ipif_next) {
5479 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5480 	}
5481 	/*
5482 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5483 	 * returns  error if ILL_CONDEMNED is set
5484 	 */
5485 	cv_broadcast(&ill->ill_cv);
5486 	mutex_exit(&ill->ill_lock);
5487 
5488 	/*
5489 	 * Send all the deferred DLPI messages downstream which came in
5490 	 * during the small window right before ipsq_enter(). We do this
5491 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5492 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5493 	 */
5494 	ill_dlpi_send_deferred(ill);
5495 
5496 	/*
5497 	 * Shut down fragmentation reassembly.
5498 	 * ill_frag_timer won't start a timer again.
5499 	 * Now cancel any existing timer
5500 	 */
5501 	(void) untimeout(ill->ill_frag_timer_id);
5502 	(void) ill_frag_timeout(ill, 0);
5503 
5504 	/*
5505 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5506 	 * this ill. Then wait for the refcnts to drop to zero.
5507 	 * ill_is_freeable checks whether the ill is really quiescent.
5508 	 * Then make sure that threads that are waiting to enter the
5509 	 * ipsq have seen the error returned by ipsq_enter and have
5510 	 * gone away. Then we call ill_delete_tail which does the
5511 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5512 	 */
5513 	ill_delete(ill);
5514 	mutex_enter(&ill->ill_lock);
5515 	while (!ill_is_freeable(ill))
5516 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5517 	while (ill->ill_waiters)
5518 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5519 
5520 	mutex_exit(&ill->ill_lock);
5521 
5522 	/*
5523 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5524 	 * it held until the end of the function since the cleanup
5525 	 * below needs to be able to use the ip_stack_t.
5526 	 */
5527 	netstack_hold(ipst->ips_netstack);
5528 
5529 	/* qprocsoff is done via ill_delete_tail */
5530 	ill_delete_tail(ill);
5531 	ASSERT(ill->ill_ipst == NULL);
5532 
5533 	/*
5534 	 * Walk through all upper (conn) streams and qenable
5535 	 * those that have queued data.
5536 	 * close synchronization needs this to
5537 	 * be done to ensure that all upper layers blocked
5538 	 * due to flow control to the closing device
5539 	 * get unblocked.
5540 	 */
5541 	ip1dbg(("ip_wsrv: walking\n"));
5542 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5543 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5544 	}
5545 
5546 	mutex_enter(&ipst->ips_ip_mi_lock);
5547 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5548 	mutex_exit(&ipst->ips_ip_mi_lock);
5549 
5550 	/*
5551 	 * credp could be null if the open didn't succeed and ip_modopen
5552 	 * itself calls ip_close.
5553 	 */
5554 	if (ill->ill_credp != NULL)
5555 		crfree(ill->ill_credp);
5556 
5557 	/*
5558 	 * Now we are done with the module close pieces that
5559 	 * need the netstack_t.
5560 	 */
5561 	netstack_rele(ipst->ips_netstack);
5562 
5563 	mi_close_free((IDP)ill);
5564 	q->q_ptr = WR(q)->q_ptr = NULL;
5565 
5566 	ipsq_exit(ipsq);
5567 
5568 	return (0);
5569 }
5570 
5571 /*
5572  * This is called as part of close() for IP, UDP, ICMP, and RTS
5573  * in order to quiesce the conn.
5574  */
5575 void
5576 ip_quiesce_conn(conn_t *connp)
5577 {
5578 	boolean_t	drain_cleanup_reqd = B_FALSE;
5579 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5580 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5581 	ip_stack_t	*ipst;
5582 
5583 	ASSERT(!IPCL_IS_TCP(connp));
5584 	ipst = connp->conn_netstack->netstack_ip;
5585 
5586 	/*
5587 	 * Mark the conn as closing, and this conn must not be
5588 	 * inserted in future into any list. Eg. conn_drain_insert(),
5589 	 * won't insert this conn into the conn_drain_list.
5590 	 * Similarly ill_pending_mp_add() will not add any mp to
5591 	 * the pending mp list, after this conn has started closing.
5592 	 *
5593 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5594 	 * cannot get set henceforth.
5595 	 */
5596 	mutex_enter(&connp->conn_lock);
5597 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5598 	connp->conn_state_flags |= CONN_CLOSING;
5599 	if (connp->conn_idl != NULL)
5600 		drain_cleanup_reqd = B_TRUE;
5601 	if (connp->conn_oper_pending_ill != NULL)
5602 		conn_ioctl_cleanup_reqd = B_TRUE;
5603 	if (connp->conn_dhcpinit_ill != NULL) {
5604 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5605 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5606 		connp->conn_dhcpinit_ill = NULL;
5607 	}
5608 	if (connp->conn_ilg_inuse != 0)
5609 		ilg_cleanup_reqd = B_TRUE;
5610 	mutex_exit(&connp->conn_lock);
5611 
5612 	if (conn_ioctl_cleanup_reqd)
5613 		conn_ioctl_cleanup(connp);
5614 
5615 	if (is_system_labeled() && connp->conn_anon_port) {
5616 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5617 		    connp->conn_mlp_type, connp->conn_ulp,
5618 		    ntohs(connp->conn_lport), B_FALSE);
5619 		connp->conn_anon_port = 0;
5620 	}
5621 	connp->conn_mlp_type = mlptSingle;
5622 
5623 	/*
5624 	 * Remove this conn from any fanout list it is on.
5625 	 * and then wait for any threads currently operating
5626 	 * on this endpoint to finish
5627 	 */
5628 	ipcl_hash_remove(connp);
5629 
5630 	/*
5631 	 * Remove this conn from the drain list, and do
5632 	 * any other cleanup that may be required.
5633 	 * (Only non-tcp streams may have a non-null conn_idl.
5634 	 * TCP streams are never flow controlled, and
5635 	 * conn_idl will be null)
5636 	 */
5637 	if (drain_cleanup_reqd)
5638 		conn_drain_tail(connp, B_TRUE);
5639 
5640 	if (connp == ipst->ips_ip_g_mrouter)
5641 		(void) ip_mrouter_done(NULL, ipst);
5642 
5643 	if (ilg_cleanup_reqd)
5644 		ilg_delete_all(connp);
5645 
5646 	conn_delete_ire(connp, NULL);
5647 
5648 	/*
5649 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5650 	 * callers from write side can't be there now because close
5651 	 * is in progress. The only other caller is ipcl_walk
5652 	 * which checks for the condemned flag.
5653 	 */
5654 	mutex_enter(&connp->conn_lock);
5655 	connp->conn_state_flags |= CONN_CONDEMNED;
5656 	while (connp->conn_ref != 1)
5657 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5658 	connp->conn_state_flags |= CONN_QUIESCED;
5659 	mutex_exit(&connp->conn_lock);
5660 }
5661 
5662 /* ARGSUSED */
5663 int
5664 ip_close(queue_t *q, int flags)
5665 {
5666 	conn_t		*connp;
5667 
5668 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5669 
5670 	/*
5671 	 * Call the appropriate delete routine depending on whether this is
5672 	 * a module or device.
5673 	 */
5674 	if (WR(q)->q_next != NULL) {
5675 		/* This is a module close */
5676 		return (ip_modclose((ill_t *)q->q_ptr));
5677 	}
5678 
5679 	connp = q->q_ptr;
5680 	ip_quiesce_conn(connp);
5681 
5682 	qprocsoff(q);
5683 
5684 	/*
5685 	 * Now we are truly single threaded on this stream, and can
5686 	 * delete the things hanging off the connp, and finally the connp.
5687 	 * We removed this connp from the fanout list, it cannot be
5688 	 * accessed thru the fanouts, and we already waited for the
5689 	 * conn_ref to drop to 0. We are already in close, so
5690 	 * there cannot be any other thread from the top. qprocsoff
5691 	 * has completed, and service has completed or won't run in
5692 	 * future.
5693 	 */
5694 	ASSERT(connp->conn_ref == 1);
5695 
5696 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5697 
5698 	connp->conn_ref--;
5699 	ipcl_conn_destroy(connp);
5700 
5701 	q->q_ptr = WR(q)->q_ptr = NULL;
5702 	return (0);
5703 }
5704 
5705 /*
5706  * Wapper around putnext() so that ip_rts_request can merely use
5707  * conn_recv.
5708  */
5709 /*ARGSUSED2*/
5710 static void
5711 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5712 {
5713 	conn_t *connp = (conn_t *)arg1;
5714 
5715 	putnext(connp->conn_rq, mp);
5716 }
5717 
5718 /*
5719  * Called when the module is about to be unloaded
5720  */
5721 void
5722 ip_ddi_destroy(void)
5723 {
5724 	tnet_fini();
5725 
5726 	icmp_ddi_g_destroy();
5727 	rts_ddi_g_destroy();
5728 	udp_ddi_g_destroy();
5729 	sctp_ddi_g_destroy();
5730 	tcp_ddi_g_destroy();
5731 	ipsec_policy_g_destroy();
5732 	ipcl_g_destroy();
5733 	ip_net_g_destroy();
5734 	ip_ire_g_fini();
5735 	inet_minor_destroy(ip_minor_arena_sa);
5736 #if defined(_LP64)
5737 	inet_minor_destroy(ip_minor_arena_la);
5738 #endif
5739 
5740 #ifdef DEBUG
5741 	list_destroy(&ip_thread_list);
5742 	rw_destroy(&ip_thread_rwlock);
5743 	tsd_destroy(&ip_thread_data);
5744 #endif
5745 
5746 	netstack_unregister(NS_IP);
5747 }
5748 
5749 /*
5750  * First step in cleanup.
5751  */
5752 /* ARGSUSED */
5753 static void
5754 ip_stack_shutdown(netstackid_t stackid, void *arg)
5755 {
5756 	ip_stack_t *ipst = (ip_stack_t *)arg;
5757 
5758 #ifdef NS_DEBUG
5759 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5760 #endif
5761 
5762 	/* Get rid of loopback interfaces and their IREs */
5763 	ip_loopback_cleanup(ipst);
5764 
5765 	/*
5766 	 * The *_hook_shutdown()s start the process of notifying any
5767 	 * consumers that things are going away.... nothing is destroyed.
5768 	 */
5769 	ipv4_hook_shutdown(ipst);
5770 	ipv6_hook_shutdown(ipst);
5771 
5772 	mutex_enter(&ipst->ips_capab_taskq_lock);
5773 	ipst->ips_capab_taskq_quit = B_TRUE;
5774 	cv_signal(&ipst->ips_capab_taskq_cv);
5775 	mutex_exit(&ipst->ips_capab_taskq_lock);
5776 
5777 	mutex_enter(&ipst->ips_mrt_lock);
5778 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5779 	cv_signal(&ipst->ips_mrt_cv);
5780 	mutex_exit(&ipst->ips_mrt_lock);
5781 }
5782 
5783 /*
5784  * Free the IP stack instance.
5785  */
5786 static void
5787 ip_stack_fini(netstackid_t stackid, void *arg)
5788 {
5789 	ip_stack_t *ipst = (ip_stack_t *)arg;
5790 	int ret;
5791 
5792 #ifdef NS_DEBUG
5793 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5794 #endif
5795 	/*
5796 	 * At this point, all of the notifications that the events and
5797 	 * protocols are going away have been run, meaning that we can
5798 	 * now set about starting to clean things up.
5799 	 */
5800 	ipv4_hook_destroy(ipst);
5801 	ipv6_hook_destroy(ipst);
5802 	ip_net_destroy(ipst);
5803 
5804 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5805 	cv_destroy(&ipst->ips_capab_taskq_cv);
5806 	list_destroy(&ipst->ips_capab_taskq_list);
5807 
5808 	mutex_enter(&ipst->ips_mrt_lock);
5809 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5810 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5811 	mutex_destroy(&ipst->ips_mrt_lock);
5812 	cv_destroy(&ipst->ips_mrt_cv);
5813 	cv_destroy(&ipst->ips_mrt_done_cv);
5814 
5815 	ipmp_destroy(ipst);
5816 	rw_destroy(&ipst->ips_srcid_lock);
5817 
5818 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5819 	ipst->ips_ip_mibkp = NULL;
5820 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5821 	ipst->ips_icmp_mibkp = NULL;
5822 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5823 	ipst->ips_ip_kstat = NULL;
5824 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5825 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5826 	ipst->ips_ip6_kstat = NULL;
5827 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5828 
5829 	nd_free(&ipst->ips_ip_g_nd);
5830 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5831 	ipst->ips_param_arr = NULL;
5832 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5833 	ipst->ips_ndp_arr = NULL;
5834 
5835 	ip_mrouter_stack_destroy(ipst);
5836 
5837 	mutex_destroy(&ipst->ips_ip_mi_lock);
5838 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5839 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5840 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5841 
5842 	ret = untimeout(ipst->ips_igmp_timeout_id);
5843 	if (ret == -1) {
5844 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5845 	} else {
5846 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5847 		ipst->ips_igmp_timeout_id = 0;
5848 	}
5849 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5850 	if (ret == -1) {
5851 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5852 	} else {
5853 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5854 		ipst->ips_igmp_slowtimeout_id = 0;
5855 	}
5856 	ret = untimeout(ipst->ips_mld_timeout_id);
5857 	if (ret == -1) {
5858 		ASSERT(ipst->ips_mld_timeout_id == 0);
5859 	} else {
5860 		ASSERT(ipst->ips_mld_timeout_id != 0);
5861 		ipst->ips_mld_timeout_id = 0;
5862 	}
5863 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5864 	if (ret == -1) {
5865 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5866 	} else {
5867 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5868 		ipst->ips_mld_slowtimeout_id = 0;
5869 	}
5870 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5871 	if (ret == -1) {
5872 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5873 	} else {
5874 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5875 		ipst->ips_ip_ire_expire_id = 0;
5876 	}
5877 
5878 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5879 	mutex_destroy(&ipst->ips_mld_timer_lock);
5880 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5881 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5882 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5883 	rw_destroy(&ipst->ips_ill_g_lock);
5884 
5885 	ipobs_fini(ipst);
5886 	ip_ire_fini(ipst);
5887 	ip6_asp_free(ipst);
5888 	conn_drain_fini(ipst);
5889 	ipcl_destroy(ipst);
5890 
5891 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5892 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5893 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5894 	ipst->ips_ndp4 = NULL;
5895 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5896 	ipst->ips_ndp6 = NULL;
5897 
5898 	if (ipst->ips_loopback_ksp != NULL) {
5899 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5900 		ipst->ips_loopback_ksp = NULL;
5901 	}
5902 
5903 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5904 	ipst->ips_phyint_g_list = NULL;
5905 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5906 	ipst->ips_ill_g_heads = NULL;
5907 
5908 	ldi_ident_release(ipst->ips_ldi_ident);
5909 	kmem_free(ipst, sizeof (*ipst));
5910 }
5911 
5912 /*
5913  * This function is called from the TSD destructor, and is used to debug
5914  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5915  * details.
5916  */
5917 static void
5918 ip_thread_exit(void *phash)
5919 {
5920 	th_hash_t *thh = phash;
5921 
5922 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5923 	list_remove(&ip_thread_list, thh);
5924 	rw_exit(&ip_thread_rwlock);
5925 	mod_hash_destroy_hash(thh->thh_hash);
5926 	kmem_free(thh, sizeof (*thh));
5927 }
5928 
5929 /*
5930  * Called when the IP kernel module is loaded into the kernel
5931  */
5932 void
5933 ip_ddi_init(void)
5934 {
5935 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5936 
5937 	/*
5938 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5939 	 * initial devices: ip, ip6, tcp, tcp6.
5940 	 */
5941 	/*
5942 	 * If this is a 64-bit kernel, then create two separate arenas -
5943 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5944 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5945 	 */
5946 	ip_minor_arena_la = NULL;
5947 	ip_minor_arena_sa = NULL;
5948 #if defined(_LP64)
5949 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5950 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5951 		cmn_err(CE_PANIC,
5952 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5953 	}
5954 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5955 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5956 		cmn_err(CE_PANIC,
5957 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5958 	}
5959 #else
5960 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5961 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5962 		cmn_err(CE_PANIC,
5963 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5964 	}
5965 #endif
5966 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5967 
5968 	ipcl_g_init();
5969 	ip_ire_g_init();
5970 	ip_net_g_init();
5971 
5972 #ifdef DEBUG
5973 	tsd_create(&ip_thread_data, ip_thread_exit);
5974 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5975 	list_create(&ip_thread_list, sizeof (th_hash_t),
5976 	    offsetof(th_hash_t, thh_link));
5977 #endif
5978 
5979 	/*
5980 	 * We want to be informed each time a stack is created or
5981 	 * destroyed in the kernel, so we can maintain the
5982 	 * set of udp_stack_t's.
5983 	 */
5984 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5985 	    ip_stack_fini);
5986 
5987 	ipsec_policy_g_init();
5988 	tcp_ddi_g_init();
5989 	sctp_ddi_g_init();
5990 
5991 	tnet_init();
5992 
5993 	udp_ddi_g_init();
5994 	rts_ddi_g_init();
5995 	icmp_ddi_g_init();
5996 }
5997 
5998 /*
5999  * Initialize the IP stack instance.
6000  */
6001 static void *
6002 ip_stack_init(netstackid_t stackid, netstack_t *ns)
6003 {
6004 	ip_stack_t	*ipst;
6005 	ipparam_t	*pa;
6006 	ipndp_t		*na;
6007 	major_t		major;
6008 
6009 #ifdef NS_DEBUG
6010 	printf("ip_stack_init(stack %d)\n", stackid);
6011 #endif
6012 
6013 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6014 	ipst->ips_netstack = ns;
6015 
6016 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6017 	    KM_SLEEP);
6018 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6019 	    KM_SLEEP);
6020 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6021 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6022 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6023 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6024 
6025 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6026 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6027 	ipst->ips_igmp_deferred_next = INFINITY;
6028 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6029 	ipst->ips_mld_deferred_next = INFINITY;
6030 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6031 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6032 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6033 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6034 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6035 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6036 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6037 
6038 	ipcl_init(ipst);
6039 	ip_ire_init(ipst);
6040 	ip6_asp_init(ipst);
6041 	ipif_init(ipst);
6042 	conn_drain_init(ipst);
6043 	ip_mrouter_stack_init(ipst);
6044 
6045 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6046 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6047 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
6048 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
6049 
6050 	ipst->ips_ip_multirt_log_interval = 1000;
6051 
6052 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6053 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6054 	ipst->ips_ill_index = 1;
6055 
6056 	ipst->ips_saved_ip_g_forward = -1;
6057 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6058 
6059 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6060 	ipst->ips_param_arr = pa;
6061 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6062 
6063 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6064 	ipst->ips_ndp_arr = na;
6065 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6066 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6067 	    (caddr_t)&ipst->ips_ip_g_forward;
6068 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6069 	    (caddr_t)&ipst->ips_ipv6_forward;
6070 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6071 	    "ip_cgtp_filter") == 0);
6072 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6073 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6074 
6075 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6076 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6077 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6078 
6079 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6080 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6081 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6082 	ipst->ips_ip6_kstat =
6083 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6084 
6085 	ipst->ips_ip_src_id = 1;
6086 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6087 
6088 	ipobs_init(ipst);
6089 	ip_net_init(ipst, ns);
6090 	ipv4_hook_init(ipst);
6091 	ipv6_hook_init(ipst);
6092 	ipmp_init(ipst);
6093 
6094 	/*
6095 	 * Create the taskq dispatcher thread and initialize related stuff.
6096 	 */
6097 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6098 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6099 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6100 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6101 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6102 	    offsetof(mblk_t, b_next));
6103 
6104 	/*
6105 	 * Create the mcast_restart_timers_thread() worker thread.
6106 	 */
6107 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6108 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6109 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6110 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6111 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6112 
6113 	major = mod_name_to_major(INET_NAME);
6114 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6115 	return (ipst);
6116 }
6117 
6118 /*
6119  * Allocate and initialize a DLPI template of the specified length.  (May be
6120  * called as writer.)
6121  */
6122 mblk_t *
6123 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6124 {
6125 	mblk_t	*mp;
6126 
6127 	mp = allocb(len, BPRI_MED);
6128 	if (!mp)
6129 		return (NULL);
6130 
6131 	/*
6132 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6133 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6134 	 * that other DLPI are M_PROTO.
6135 	 */
6136 	if (prim == DL_INFO_REQ) {
6137 		mp->b_datap->db_type = M_PCPROTO;
6138 	} else {
6139 		mp->b_datap->db_type = M_PROTO;
6140 	}
6141 
6142 	mp->b_wptr = mp->b_rptr + len;
6143 	bzero(mp->b_rptr, len);
6144 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6145 	return (mp);
6146 }
6147 
6148 /*
6149  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6150  */
6151 mblk_t *
6152 ip_dlnotify_alloc(uint_t notification, uint_t data)
6153 {
6154 	dl_notify_ind_t	*notifyp;
6155 	mblk_t		*mp;
6156 
6157 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6158 		return (NULL);
6159 
6160 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6161 	notifyp->dl_notification = notification;
6162 	notifyp->dl_data = data;
6163 	return (mp);
6164 }
6165 
6166 /*
6167  * Debug formatting routine.  Returns a character string representation of the
6168  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6169  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6170  *
6171  * Once the ndd table-printing interfaces are removed, this can be changed to
6172  * standard dotted-decimal form.
6173  */
6174 char *
6175 ip_dot_addr(ipaddr_t addr, char *buf)
6176 {
6177 	uint8_t *ap = (uint8_t *)&addr;
6178 
6179 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6180 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6181 	return (buf);
6182 }
6183 
6184 /*
6185  * Write the given MAC address as a printable string in the usual colon-
6186  * separated format.
6187  */
6188 const char *
6189 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6190 {
6191 	char *bp;
6192 
6193 	if (alen == 0 || buflen < 4)
6194 		return ("?");
6195 	bp = buf;
6196 	for (;;) {
6197 		/*
6198 		 * If there are more MAC address bytes available, but we won't
6199 		 * have any room to print them, then add "..." to the string
6200 		 * instead.  See below for the 'magic number' explanation.
6201 		 */
6202 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6203 			(void) strcpy(bp, "...");
6204 			break;
6205 		}
6206 		(void) sprintf(bp, "%02x", *addr++);
6207 		bp += 2;
6208 		if (--alen == 0)
6209 			break;
6210 		*bp++ = ':';
6211 		buflen -= 3;
6212 		/*
6213 		 * At this point, based on the first 'if' statement above,
6214 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6215 		 * buflen >= 4.  The first case leaves room for the final "xx"
6216 		 * number and trailing NUL byte.  The second leaves room for at
6217 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6218 		 * that statement.
6219 		 */
6220 	}
6221 	return (buf);
6222 }
6223 
6224 /*
6225  * Send an ICMP error after patching up the packet appropriately.  Returns
6226  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6227  */
6228 static boolean_t
6229 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6230     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6231     zoneid_t zoneid, ip_stack_t *ipst)
6232 {
6233 	ipha_t *ipha;
6234 	mblk_t *first_mp;
6235 	boolean_t secure;
6236 	unsigned char db_type;
6237 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6238 
6239 	first_mp = mp;
6240 	if (mctl_present) {
6241 		mp = mp->b_cont;
6242 		secure = ipsec_in_is_secure(first_mp);
6243 		ASSERT(mp != NULL);
6244 	} else {
6245 		/*
6246 		 * If this is an ICMP error being reported - which goes
6247 		 * up as M_CTLs, we need to convert them to M_DATA till
6248 		 * we finish checking with global policy because
6249 		 * ipsec_check_global_policy() assumes M_DATA as clear
6250 		 * and M_CTL as secure.
6251 		 */
6252 		db_type = DB_TYPE(mp);
6253 		DB_TYPE(mp) = M_DATA;
6254 		secure = B_FALSE;
6255 	}
6256 	/*
6257 	 * We are generating an icmp error for some inbound packet.
6258 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6259 	 * Before we generate an error, check with global policy
6260 	 * to see whether this is allowed to enter the system. As
6261 	 * there is no "conn", we are checking with global policy.
6262 	 */
6263 	ipha = (ipha_t *)mp->b_rptr;
6264 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6265 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6266 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6267 		if (first_mp == NULL)
6268 			return (B_FALSE);
6269 	}
6270 
6271 	if (!mctl_present)
6272 		DB_TYPE(mp) = db_type;
6273 
6274 	if (flags & IP_FF_SEND_ICMP) {
6275 		if (flags & IP_FF_HDR_COMPLETE) {
6276 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6277 				freemsg(first_mp);
6278 				return (B_TRUE);
6279 			}
6280 		}
6281 		if (flags & IP_FF_CKSUM) {
6282 			/*
6283 			 * Have to correct checksum since
6284 			 * the packet might have been
6285 			 * fragmented and the reassembly code in ip_rput
6286 			 * does not restore the IP checksum.
6287 			 */
6288 			ipha->ipha_hdr_checksum = 0;
6289 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6290 		}
6291 		switch (icmp_type) {
6292 		case ICMP_DEST_UNREACHABLE:
6293 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6294 			    ipst);
6295 			break;
6296 		default:
6297 			freemsg(first_mp);
6298 			break;
6299 		}
6300 	} else {
6301 		freemsg(first_mp);
6302 		return (B_FALSE);
6303 	}
6304 
6305 	return (B_TRUE);
6306 }
6307 
6308 /*
6309  * Used to send an ICMP error message when a packet is received for
6310  * a protocol that is not supported. The mblk passed as argument
6311  * is consumed by this function.
6312  */
6313 void
6314 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6315     ip_stack_t *ipst)
6316 {
6317 	mblk_t *mp;
6318 	ipha_t *ipha;
6319 	ill_t *ill;
6320 	ipsec_in_t *ii;
6321 
6322 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6323 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6324 
6325 	mp = ipsec_mp->b_cont;
6326 	ipsec_mp->b_cont = NULL;
6327 	ipha = (ipha_t *)mp->b_rptr;
6328 	/* Get ill from index in ipsec_in_t. */
6329 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6330 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6331 	    ipst);
6332 	if (ill != NULL) {
6333 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6334 			if (ip_fanout_send_icmp(q, mp, flags,
6335 			    ICMP_DEST_UNREACHABLE,
6336 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6337 				BUMP_MIB(ill->ill_ip_mib,
6338 				    ipIfStatsInUnknownProtos);
6339 			}
6340 		} else {
6341 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6342 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6343 			    0, B_FALSE, zoneid, ipst)) {
6344 				BUMP_MIB(ill->ill_ip_mib,
6345 				    ipIfStatsInUnknownProtos);
6346 			}
6347 		}
6348 		ill_refrele(ill);
6349 	} else { /* re-link for the freemsg() below. */
6350 		ipsec_mp->b_cont = mp;
6351 	}
6352 
6353 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6354 	freemsg(ipsec_mp);
6355 }
6356 
6357 /*
6358  * See if the inbound datagram has had IPsec processing applied to it.
6359  */
6360 boolean_t
6361 ipsec_in_is_secure(mblk_t *ipsec_mp)
6362 {
6363 	ipsec_in_t *ii;
6364 
6365 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6366 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6367 
6368 	if (ii->ipsec_in_loopback) {
6369 		return (ii->ipsec_in_secure);
6370 	} else {
6371 		return (ii->ipsec_in_ah_sa != NULL ||
6372 		    ii->ipsec_in_esp_sa != NULL ||
6373 		    ii->ipsec_in_decaps);
6374 	}
6375 }
6376 
6377 /*
6378  * Handle protocols with which IP is less intimate.  There
6379  * can be more than one stream bound to a particular
6380  * protocol.  When this is the case, normally each one gets a copy
6381  * of any incoming packets.
6382  *
6383  * IPsec NOTE :
6384  *
6385  * Don't allow a secure packet going up a non-secure connection.
6386  * We don't allow this because
6387  *
6388  * 1) Reply might go out in clear which will be dropped at
6389  *    the sending side.
6390  * 2) If the reply goes out in clear it will give the
6391  *    adversary enough information for getting the key in
6392  *    most of the cases.
6393  *
6394  * Moreover getting a secure packet when we expect clear
6395  * implies that SA's were added without checking for
6396  * policy on both ends. This should not happen once ISAKMP
6397  * is used to negotiate SAs as SAs will be added only after
6398  * verifying the policy.
6399  *
6400  * NOTE : If the packet was tunneled and not multicast we only send
6401  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6402  * back to delivering packets to AF_INET6 raw sockets.
6403  *
6404  * IPQoS Notes:
6405  * Once we have determined the client, invoke IPPF processing.
6406  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6407  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6408  * ip_policy will be false.
6409  *
6410  * Zones notes:
6411  * Currently only applications in the global zone can create raw sockets for
6412  * protocols other than ICMP. So unlike the broadcast / multicast case of
6413  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6414  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6415  */
6416 static void
6417 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6418     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6419     zoneid_t zoneid)
6420 {
6421 	queue_t	*rq;
6422 	mblk_t	*mp1, *first_mp1;
6423 	uint_t	protocol = ipha->ipha_protocol;
6424 	ipaddr_t dst;
6425 	boolean_t one_only;
6426 	mblk_t *first_mp = mp;
6427 	boolean_t secure;
6428 	uint32_t ill_index;
6429 	conn_t	*connp, *first_connp, *next_connp;
6430 	connf_t	*connfp;
6431 	boolean_t shared_addr;
6432 	mib2_ipIfStatsEntry_t *mibptr;
6433 	ip_stack_t *ipst = recv_ill->ill_ipst;
6434 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6435 
6436 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6437 	if (mctl_present) {
6438 		mp = first_mp->b_cont;
6439 		secure = ipsec_in_is_secure(first_mp);
6440 		ASSERT(mp != NULL);
6441 	} else {
6442 		secure = B_FALSE;
6443 	}
6444 	dst = ipha->ipha_dst;
6445 	/*
6446 	 * If the packet was tunneled and not multicast we only send to it
6447 	 * the first match.
6448 	 */
6449 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6450 	    !CLASSD(dst));
6451 
6452 	shared_addr = (zoneid == ALL_ZONES);
6453 	if (shared_addr) {
6454 		/*
6455 		 * We don't allow multilevel ports for raw IP, so no need to
6456 		 * check for that here.
6457 		 */
6458 		zoneid = tsol_packet_to_zoneid(mp);
6459 	}
6460 
6461 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6462 	mutex_enter(&connfp->connf_lock);
6463 	connp = connfp->connf_head;
6464 	for (connp = connfp->connf_head; connp != NULL;
6465 	    connp = connp->conn_next) {
6466 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6467 		    zoneid) &&
6468 		    (!is_system_labeled() ||
6469 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6470 		    connp))) {
6471 			break;
6472 		}
6473 	}
6474 
6475 	if (connp == NULL) {
6476 		/*
6477 		 * No one bound to these addresses.  Is
6478 		 * there a client that wants all
6479 		 * unclaimed datagrams?
6480 		 */
6481 		mutex_exit(&connfp->connf_lock);
6482 		/*
6483 		 * Check for IPPROTO_ENCAP...
6484 		 */
6485 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6486 			/*
6487 			 * If an IPsec mblk is here on a multicast
6488 			 * tunnel (using ip_mroute stuff), check policy here,
6489 			 * THEN ship off to ip_mroute_decap().
6490 			 *
6491 			 * BTW,  If I match a configured IP-in-IP
6492 			 * tunnel, this path will not be reached, and
6493 			 * ip_mroute_decap will never be called.
6494 			 */
6495 			first_mp = ipsec_check_global_policy(first_mp, connp,
6496 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6497 			if (first_mp != NULL) {
6498 				if (mctl_present)
6499 					freeb(first_mp);
6500 				ip_mroute_decap(q, mp, ill);
6501 			} /* Else we already freed everything! */
6502 		} else {
6503 			/*
6504 			 * Otherwise send an ICMP protocol unreachable.
6505 			 */
6506 			if (ip_fanout_send_icmp(q, first_mp, flags,
6507 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6508 			    mctl_present, zoneid, ipst)) {
6509 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6510 			}
6511 		}
6512 		return;
6513 	}
6514 
6515 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6516 
6517 	CONN_INC_REF(connp);
6518 	first_connp = connp;
6519 
6520 	/*
6521 	 * Only send message to one tunnel driver by immediately
6522 	 * terminating the loop.
6523 	 */
6524 	connp = one_only ? NULL : connp->conn_next;
6525 
6526 	for (;;) {
6527 		while (connp != NULL) {
6528 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6529 			    flags, zoneid) &&
6530 			    (!is_system_labeled() ||
6531 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6532 			    shared_addr, connp)))
6533 				break;
6534 			connp = connp->conn_next;
6535 		}
6536 
6537 		/*
6538 		 * Copy the packet.
6539 		 */
6540 		if (connp == NULL ||
6541 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6542 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6543 			/*
6544 			 * No more interested clients or memory
6545 			 * allocation failed
6546 			 */
6547 			connp = first_connp;
6548 			break;
6549 		}
6550 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6551 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6552 		CONN_INC_REF(connp);
6553 		mutex_exit(&connfp->connf_lock);
6554 		rq = connp->conn_rq;
6555 
6556 		/*
6557 		 * Check flow control
6558 		 */
6559 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6560 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6561 			if (flags & IP_FF_RAWIP) {
6562 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6563 			} else {
6564 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6565 			}
6566 
6567 			freemsg(first_mp1);
6568 		} else {
6569 			/*
6570 			 * Don't enforce here if we're an actual tunnel -
6571 			 * let "tun" do it instead.
6572 			 */
6573 			if (!IPCL_IS_IPTUN(connp) &&
6574 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6575 			    secure)) {
6576 				first_mp1 = ipsec_check_inbound_policy
6577 				    (first_mp1, connp, ipha, NULL,
6578 				    mctl_present);
6579 			}
6580 			if (first_mp1 != NULL) {
6581 				int in_flags = 0;
6582 				/*
6583 				 * ip_fanout_proto also gets called from
6584 				 * icmp_inbound_error_fanout, in which case
6585 				 * the msg type is M_CTL.  Don't add info
6586 				 * in this case for the time being. In future
6587 				 * when there is a need for knowing the
6588 				 * inbound iface index for ICMP error msgs,
6589 				 * then this can be changed.
6590 				 */
6591 				if (connp->conn_recvif)
6592 					in_flags = IPF_RECVIF;
6593 				/*
6594 				 * The ULP may support IP_RECVPKTINFO for both
6595 				 * IP v4 and v6 so pass the appropriate argument
6596 				 * based on conn IP version.
6597 				 */
6598 				if (connp->conn_ip_recvpktinfo) {
6599 					if (connp->conn_af_isv6) {
6600 						/*
6601 						 * V6 only needs index
6602 						 */
6603 						in_flags |= IPF_RECVIF;
6604 					} else {
6605 						/*
6606 						 * V4 needs index +
6607 						 * matching address.
6608 						 */
6609 						in_flags |= IPF_RECVADDR;
6610 					}
6611 				}
6612 				if ((in_flags != 0) &&
6613 				    (mp->b_datap->db_type != M_CTL)) {
6614 					/*
6615 					 * the actual data will be
6616 					 * contained in b_cont upon
6617 					 * successful return of the
6618 					 * following call else
6619 					 * original mblk is returned
6620 					 */
6621 					ASSERT(recv_ill != NULL);
6622 					mp1 = ip_add_info(mp1, recv_ill,
6623 					    in_flags, IPCL_ZONEID(connp), ipst);
6624 				}
6625 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6626 				if (mctl_present)
6627 					freeb(first_mp1);
6628 				(connp->conn_recv)(connp, mp1, NULL);
6629 			}
6630 		}
6631 		mutex_enter(&connfp->connf_lock);
6632 		/* Follow the next pointer before releasing the conn. */
6633 		next_connp = connp->conn_next;
6634 		CONN_DEC_REF(connp);
6635 		connp = next_connp;
6636 	}
6637 
6638 	/* Last one.  Send it upstream. */
6639 	mutex_exit(&connfp->connf_lock);
6640 
6641 	/*
6642 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6643 	 * will be set to false.
6644 	 */
6645 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6646 		ill_index = ill->ill_phyint->phyint_ifindex;
6647 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6648 		if (mp == NULL) {
6649 			CONN_DEC_REF(connp);
6650 			if (mctl_present) {
6651 				freeb(first_mp);
6652 			}
6653 			return;
6654 		}
6655 	}
6656 
6657 	rq = connp->conn_rq;
6658 	/*
6659 	 * Check flow control
6660 	 */
6661 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6662 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6663 		if (flags & IP_FF_RAWIP) {
6664 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6665 		} else {
6666 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6667 		}
6668 
6669 		freemsg(first_mp);
6670 	} else {
6671 		if (IPCL_IS_IPTUN(connp)) {
6672 			/*
6673 			 * Tunneled packet.  We enforce policy in the tunnel
6674 			 * module itself.
6675 			 *
6676 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6677 			 * a policy check.
6678 			 * FIXME to use conn_recv for tun later.
6679 			 */
6680 			putnext(rq, first_mp);
6681 			CONN_DEC_REF(connp);
6682 			return;
6683 		}
6684 
6685 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6686 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6687 			    ipha, NULL, mctl_present);
6688 		}
6689 
6690 		if (first_mp != NULL) {
6691 			int in_flags = 0;
6692 
6693 			/*
6694 			 * ip_fanout_proto also gets called
6695 			 * from icmp_inbound_error_fanout, in
6696 			 * which case the msg type is M_CTL.
6697 			 * Don't add info in this case for time
6698 			 * being. In future when there is a
6699 			 * need for knowing the inbound iface
6700 			 * index for ICMP error msgs, then this
6701 			 * can be changed
6702 			 */
6703 			if (connp->conn_recvif)
6704 				in_flags = IPF_RECVIF;
6705 			if (connp->conn_ip_recvpktinfo) {
6706 				if (connp->conn_af_isv6) {
6707 					/*
6708 					 * V6 only needs index
6709 					 */
6710 					in_flags |= IPF_RECVIF;
6711 				} else {
6712 					/*
6713 					 * V4 needs index +
6714 					 * matching address.
6715 					 */
6716 					in_flags |= IPF_RECVADDR;
6717 				}
6718 			}
6719 			if ((in_flags != 0) &&
6720 			    (mp->b_datap->db_type != M_CTL)) {
6721 
6722 				/*
6723 				 * the actual data will be contained in
6724 				 * b_cont upon successful return
6725 				 * of the following call else original
6726 				 * mblk is returned
6727 				 */
6728 				ASSERT(recv_ill != NULL);
6729 				mp = ip_add_info(mp, recv_ill,
6730 				    in_flags, IPCL_ZONEID(connp), ipst);
6731 			}
6732 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6733 			(connp->conn_recv)(connp, mp, NULL);
6734 			if (mctl_present)
6735 				freeb(first_mp);
6736 		}
6737 	}
6738 	CONN_DEC_REF(connp);
6739 }
6740 
6741 /*
6742  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6743  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6744  * the correct squeue, in this case the same squeue as a valid listener with
6745  * no current connection state for the packet we are processing. The function
6746  * is called for synchronizing both IPv4 and IPv6.
6747  */
6748 void
6749 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6750     tcp_stack_t *tcps, conn_t *connp)
6751 {
6752 	mblk_t *rst_mp;
6753 	tcp_xmit_reset_event_t *eventp;
6754 
6755 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6756 
6757 	if (rst_mp == NULL) {
6758 		freemsg(mp);
6759 		return;
6760 	}
6761 
6762 	rst_mp->b_datap->db_type = M_PROTO;
6763 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6764 
6765 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6766 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6767 	eventp->tcp_xre_iphdrlen = hdrlen;
6768 	eventp->tcp_xre_zoneid = zoneid;
6769 	eventp->tcp_xre_tcps = tcps;
6770 
6771 	rst_mp->b_cont = mp;
6772 	mp = rst_mp;
6773 
6774 	/*
6775 	 * Increment the connref, this ref will be released by the squeue
6776 	 * framework.
6777 	 */
6778 	CONN_INC_REF(connp);
6779 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6780 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6781 }
6782 
6783 /*
6784  * Fanout for TCP packets
6785  * The caller puts <fport, lport> in the ports parameter.
6786  *
6787  * IPQoS Notes
6788  * Before sending it to the client, invoke IPPF processing.
6789  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6790  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6791  * ip_policy is false.
6792  */
6793 static void
6794 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6795     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6796 {
6797 	mblk_t  *first_mp;
6798 	boolean_t secure;
6799 	uint32_t ill_index;
6800 	int	ip_hdr_len;
6801 	tcph_t	*tcph;
6802 	boolean_t syn_present = B_FALSE;
6803 	conn_t	*connp;
6804 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6805 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6806 
6807 	ASSERT(recv_ill != NULL);
6808 
6809 	first_mp = mp;
6810 	if (mctl_present) {
6811 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6812 		mp = first_mp->b_cont;
6813 		secure = ipsec_in_is_secure(first_mp);
6814 		ASSERT(mp != NULL);
6815 	} else {
6816 		secure = B_FALSE;
6817 	}
6818 
6819 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6820 
6821 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6822 	    zoneid, ipst)) == NULL) {
6823 		/*
6824 		 * No connected connection or listener. Send a
6825 		 * TH_RST via tcp_xmit_listeners_reset.
6826 		 */
6827 
6828 		/* Initiate IPPf processing, if needed. */
6829 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6830 			uint32_t ill_index;
6831 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6832 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6833 			if (first_mp == NULL)
6834 				return;
6835 		}
6836 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6837 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6838 		    zoneid));
6839 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6840 		    ipst->ips_netstack->netstack_tcp, NULL);
6841 		return;
6842 	}
6843 
6844 	/*
6845 	 * Allocate the SYN for the TCP connection here itself
6846 	 */
6847 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6848 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6849 		if (IPCL_IS_TCP(connp)) {
6850 			squeue_t *sqp;
6851 
6852 			/*
6853 			 * For fused tcp loopback, assign the eager's
6854 			 * squeue to be that of the active connect's.
6855 			 * Note that we don't check for IP_FF_LOOPBACK
6856 			 * here since this routine gets called only
6857 			 * for loopback (unlike the IPv6 counterpart).
6858 			 */
6859 			ASSERT(Q_TO_CONN(q) != NULL);
6860 			if (do_tcp_fusion &&
6861 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6862 			    !secure &&
6863 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6864 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6865 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6866 				sqp = Q_TO_CONN(q)->conn_sqp;
6867 			} else {
6868 				sqp = IP_SQUEUE_GET(lbolt);
6869 			}
6870 
6871 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6872 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6873 			syn_present = B_TRUE;
6874 		}
6875 	}
6876 
6877 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6878 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6879 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6880 		if ((flags & TH_RST) || (flags & TH_URG)) {
6881 			CONN_DEC_REF(connp);
6882 			freemsg(first_mp);
6883 			return;
6884 		}
6885 		if (flags & TH_ACK) {
6886 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6887 			    ipst->ips_netstack->netstack_tcp, connp);
6888 			CONN_DEC_REF(connp);
6889 			return;
6890 		}
6891 
6892 		CONN_DEC_REF(connp);
6893 		freemsg(first_mp);
6894 		return;
6895 	}
6896 
6897 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6898 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6899 		    NULL, mctl_present);
6900 		if (first_mp == NULL) {
6901 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6902 			CONN_DEC_REF(connp);
6903 			return;
6904 		}
6905 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6906 			ASSERT(syn_present);
6907 			if (mctl_present) {
6908 				ASSERT(first_mp != mp);
6909 				first_mp->b_datap->db_struioflag |=
6910 				    STRUIO_POLICY;
6911 			} else {
6912 				ASSERT(first_mp == mp);
6913 				mp->b_datap->db_struioflag &=
6914 				    ~STRUIO_EAGER;
6915 				mp->b_datap->db_struioflag |=
6916 				    STRUIO_POLICY;
6917 			}
6918 		} else {
6919 			/*
6920 			 * Discard first_mp early since we're dealing with a
6921 			 * fully-connected conn_t and tcp doesn't do policy in
6922 			 * this case.
6923 			 */
6924 			if (mctl_present) {
6925 				freeb(first_mp);
6926 				mctl_present = B_FALSE;
6927 			}
6928 			first_mp = mp;
6929 		}
6930 	}
6931 
6932 	/*
6933 	 * Initiate policy processing here if needed. If we get here from
6934 	 * icmp_inbound_error_fanout, ip_policy is false.
6935 	 */
6936 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6937 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6938 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6939 		if (mp == NULL) {
6940 			CONN_DEC_REF(connp);
6941 			if (mctl_present)
6942 				freeb(first_mp);
6943 			return;
6944 		} else if (mctl_present) {
6945 			ASSERT(first_mp != mp);
6946 			first_mp->b_cont = mp;
6947 		} else {
6948 			first_mp = mp;
6949 		}
6950 	}
6951 
6952 	/* Handle socket options. */
6953 	if (!syn_present &&
6954 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6955 		/* Add header */
6956 		ASSERT(recv_ill != NULL);
6957 		/*
6958 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6959 		 * IPF_RECVIF.
6960 		 */
6961 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6962 		    ipst);
6963 		if (mp == NULL) {
6964 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6965 			CONN_DEC_REF(connp);
6966 			if (mctl_present)
6967 				freeb(first_mp);
6968 			return;
6969 		} else if (mctl_present) {
6970 			/*
6971 			 * ip_add_info might return a new mp.
6972 			 */
6973 			ASSERT(first_mp != mp);
6974 			first_mp->b_cont = mp;
6975 		} else {
6976 			first_mp = mp;
6977 		}
6978 	}
6979 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6980 	if (IPCL_IS_TCP(connp)) {
6981 		/* do not drain, certain use cases can blow the stack */
6982 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6983 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6984 	} else {
6985 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6986 		(connp->conn_recv)(connp, first_mp, NULL);
6987 		CONN_DEC_REF(connp);
6988 	}
6989 }
6990 
6991 /*
6992  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6993  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6994  * is not consumed.
6995  *
6996  * One of four things can happen, all of which affect the passed-in mblk:
6997  *
6998  * 1.) ICMP messages that go through here just get returned TRUE.
6999  *
7000  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
7001  *
7002  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
7003  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
7004  *
7005  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
7006  */
7007 static boolean_t
7008 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
7009     ipsec_stack_t *ipss)
7010 {
7011 	int shift, plen, iph_len;
7012 	ipha_t *ipha;
7013 	udpha_t *udpha;
7014 	uint32_t *spi;
7015 	uint32_t esp_ports;
7016 	uint8_t *orptr;
7017 	boolean_t free_ire;
7018 
7019 	if (DB_TYPE(mp) == M_CTL) {
7020 		/*
7021 		 * ICMP message with UDP inside.  Don't bother stripping, just
7022 		 * send it up.
7023 		 *
7024 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
7025 		 * to ignore errors set by ICMP anyway ('cause they might be
7026 		 * forged), but that's the app's decision, not ours.
7027 		 */
7028 
7029 		/* Bunch of reality checks for DEBUG kernels... */
7030 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
7031 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
7032 
7033 		return (B_TRUE);
7034 	}
7035 
7036 	ipha = (ipha_t *)mp->b_rptr;
7037 	iph_len = IPH_HDR_LENGTH(ipha);
7038 	plen = ntohs(ipha->ipha_length);
7039 
7040 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
7041 		/*
7042 		 * Most likely a keepalive for the benefit of an intervening
7043 		 * NAT.  These aren't for us, per se, so drop it.
7044 		 *
7045 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
7046 		 * byte packets (keepalives are 1-byte), but we'll drop them
7047 		 * also.
7048 		 */
7049 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7050 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7051 		return (B_FALSE);
7052 	}
7053 
7054 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7055 		/* might as well pull it all up - it might be ESP. */
7056 		if (!pullupmsg(mp, -1)) {
7057 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7058 			    DROPPER(ipss, ipds_esp_nomem),
7059 			    &ipss->ipsec_dropper);
7060 			return (B_FALSE);
7061 		}
7062 
7063 		ipha = (ipha_t *)mp->b_rptr;
7064 	}
7065 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7066 	if (*spi == 0) {
7067 		/* UDP packet - remove 0-spi. */
7068 		shift = sizeof (uint32_t);
7069 	} else {
7070 		/* ESP-in-UDP packet - reduce to ESP. */
7071 		ipha->ipha_protocol = IPPROTO_ESP;
7072 		shift = sizeof (udpha_t);
7073 	}
7074 
7075 	/* Fix IP header */
7076 	ipha->ipha_length = htons(plen - shift);
7077 	ipha->ipha_hdr_checksum = 0;
7078 
7079 	orptr = mp->b_rptr;
7080 	mp->b_rptr += shift;
7081 
7082 	udpha = (udpha_t *)(orptr + iph_len);
7083 	if (*spi == 0) {
7084 		ASSERT((uint8_t *)ipha == orptr);
7085 		udpha->uha_length = htons(plen - shift - iph_len);
7086 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7087 		esp_ports = 0;
7088 	} else {
7089 		esp_ports = *((uint32_t *)udpha);
7090 		ASSERT(esp_ports != 0);
7091 	}
7092 	ovbcopy(orptr, orptr + shift, iph_len);
7093 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7094 		ipha = (ipha_t *)(orptr + shift);
7095 
7096 		free_ire = (ire == NULL);
7097 		if (free_ire) {
7098 			/* Re-acquire ire. */
7099 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7100 			    ipss->ipsec_netstack->netstack_ip);
7101 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7102 				if (ire != NULL)
7103 					ire_refrele(ire);
7104 				/*
7105 				 * Do a regular freemsg(), as this is an IP
7106 				 * error (no local route) not an IPsec one.
7107 				 */
7108 				freemsg(mp);
7109 			}
7110 		}
7111 
7112 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7113 		if (free_ire)
7114 			ire_refrele(ire);
7115 	}
7116 
7117 	return (esp_ports == 0);
7118 }
7119 
7120 /*
7121  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7122  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7123  * Caller is responsible for dropping references to the conn, and freeing
7124  * first_mp.
7125  *
7126  * IPQoS Notes
7127  * Before sending it to the client, invoke IPPF processing. Policy processing
7128  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7129  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7130  * ip_wput_local, ip_policy is false.
7131  */
7132 static void
7133 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7134     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7135     boolean_t ip_policy)
7136 {
7137 	boolean_t	mctl_present = (first_mp != NULL);
7138 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7139 	uint32_t	ill_index;
7140 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7141 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7142 
7143 	ASSERT(ill != NULL);
7144 
7145 	if (mctl_present)
7146 		first_mp->b_cont = mp;
7147 	else
7148 		first_mp = mp;
7149 
7150 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7151 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7152 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7153 		freemsg(first_mp);
7154 		return;
7155 	}
7156 
7157 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7158 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7159 		    NULL, mctl_present);
7160 		/* Freed by ipsec_check_inbound_policy(). */
7161 		if (first_mp == NULL) {
7162 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7163 			return;
7164 		}
7165 	}
7166 	if (mctl_present)
7167 		freeb(first_mp);
7168 
7169 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7170 	if (connp->conn_udp->udp_nat_t_endpoint) {
7171 		if (mctl_present) {
7172 			/* mctl_present *shouldn't* happen. */
7173 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7174 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7175 			    &ipss->ipsec_dropper);
7176 			return;
7177 		}
7178 
7179 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7180 			return;
7181 	}
7182 
7183 	/* Handle options. */
7184 	if (connp->conn_recvif)
7185 		in_flags = IPF_RECVIF;
7186 	/*
7187 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7188 	 * passed to ip_add_info is based on IP version of connp.
7189 	 */
7190 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7191 		if (connp->conn_af_isv6) {
7192 			/*
7193 			 * V6 only needs index
7194 			 */
7195 			in_flags |= IPF_RECVIF;
7196 		} else {
7197 			/*
7198 			 * V4 needs index + matching address.
7199 			 */
7200 			in_flags |= IPF_RECVADDR;
7201 		}
7202 	}
7203 
7204 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7205 		in_flags |= IPF_RECVSLLA;
7206 
7207 	/*
7208 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7209 	 * freed if the packet is dropped. The caller will do so.
7210 	 */
7211 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7212 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7213 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7214 		if (mp == NULL) {
7215 			return;
7216 		}
7217 	}
7218 	if ((in_flags != 0) &&
7219 	    (mp->b_datap->db_type != M_CTL)) {
7220 		/*
7221 		 * The actual data will be contained in b_cont
7222 		 * upon successful return of the following call
7223 		 * else original mblk is returned
7224 		 */
7225 		ASSERT(recv_ill != NULL);
7226 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7227 		    ipst);
7228 	}
7229 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7230 	/* Send it upstream */
7231 	(connp->conn_recv)(connp, mp, NULL);
7232 }
7233 
7234 /*
7235  * Fanout for UDP packets.
7236  * The caller puts <fport, lport> in the ports parameter.
7237  *
7238  * If SO_REUSEADDR is set all multicast and broadcast packets
7239  * will be delivered to all streams bound to the same port.
7240  *
7241  * Zones notes:
7242  * Multicast and broadcast packets will be distributed to streams in all zones.
7243  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7244  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7245  * packets. To maintain this behavior with multiple zones, the conns are grouped
7246  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7247  * each zone. If unset, all the following conns in the same zone are skipped.
7248  */
7249 static void
7250 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7251     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7252     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7253 {
7254 	uint32_t	dstport, srcport;
7255 	ipaddr_t	dst;
7256 	mblk_t		*first_mp;
7257 	boolean_t	secure;
7258 	in6_addr_t	v6src;
7259 	conn_t		*connp;
7260 	connf_t		*connfp;
7261 	conn_t		*first_connp;
7262 	conn_t		*next_connp;
7263 	mblk_t		*mp1, *first_mp1;
7264 	ipaddr_t	src;
7265 	zoneid_t	last_zoneid;
7266 	boolean_t	reuseaddr;
7267 	boolean_t	shared_addr;
7268 	boolean_t	unlabeled;
7269 	ip_stack_t	*ipst;
7270 
7271 	ASSERT(recv_ill != NULL);
7272 	ipst = recv_ill->ill_ipst;
7273 
7274 	first_mp = mp;
7275 	if (mctl_present) {
7276 		mp = first_mp->b_cont;
7277 		first_mp->b_cont = NULL;
7278 		secure = ipsec_in_is_secure(first_mp);
7279 		ASSERT(mp != NULL);
7280 	} else {
7281 		first_mp = NULL;
7282 		secure = B_FALSE;
7283 	}
7284 
7285 	/* Extract ports in net byte order */
7286 	dstport = htons(ntohl(ports) & 0xFFFF);
7287 	srcport = htons(ntohl(ports) >> 16);
7288 	dst = ipha->ipha_dst;
7289 	src = ipha->ipha_src;
7290 
7291 	unlabeled = B_FALSE;
7292 	if (is_system_labeled())
7293 		/* Cred cannot be null on IPv4 */
7294 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7295 		    TSLF_UNLABELED) != 0;
7296 	shared_addr = (zoneid == ALL_ZONES);
7297 	if (shared_addr) {
7298 		/*
7299 		 * No need to handle exclusive-stack zones since ALL_ZONES
7300 		 * only applies to the shared stack.
7301 		 */
7302 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7303 		/*
7304 		 * If no shared MLP is found, tsol_mlp_findzone returns
7305 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7306 		 * search for the zone based on the packet label.
7307 		 *
7308 		 * If there is such a zone, we prefer to find a
7309 		 * connection in it.  Otherwise, we look for a
7310 		 * MAC-exempt connection in any zone whose label
7311 		 * dominates the default label on the packet.
7312 		 */
7313 		if (zoneid == ALL_ZONES)
7314 			zoneid = tsol_packet_to_zoneid(mp);
7315 		else
7316 			unlabeled = B_FALSE;
7317 	}
7318 
7319 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7320 	mutex_enter(&connfp->connf_lock);
7321 	connp = connfp->connf_head;
7322 	if (!broadcast && !CLASSD(dst)) {
7323 		/*
7324 		 * Not broadcast or multicast. Send to the one (first)
7325 		 * client we find. No need to check conn_wantpacket()
7326 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7327 		 * IPv4 unicast packets.
7328 		 */
7329 		while ((connp != NULL) &&
7330 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7331 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7332 		    !(unlabeled && connp->conn_mac_exempt)))) {
7333 			/*
7334 			 * We keep searching since the conn did not match,
7335 			 * or its zone did not match and it is not either
7336 			 * an allzones conn or a mac exempt conn (if the
7337 			 * sender is unlabeled.)
7338 			 */
7339 			connp = connp->conn_next;
7340 		}
7341 
7342 		if (connp == NULL ||
7343 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7344 			goto notfound;
7345 
7346 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7347 
7348 		if (is_system_labeled() &&
7349 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7350 		    connp))
7351 			goto notfound;
7352 
7353 		CONN_INC_REF(connp);
7354 		mutex_exit(&connfp->connf_lock);
7355 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7356 		    flags, recv_ill, ip_policy);
7357 		IP_STAT(ipst, ip_udp_fannorm);
7358 		CONN_DEC_REF(connp);
7359 		return;
7360 	}
7361 
7362 	/*
7363 	 * Broadcast and multicast case
7364 	 *
7365 	 * Need to check conn_wantpacket().
7366 	 * If SO_REUSEADDR has been set on the first we send the
7367 	 * packet to all clients that have joined the group and
7368 	 * match the port.
7369 	 */
7370 
7371 	while (connp != NULL) {
7372 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7373 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7374 		    (!is_system_labeled() ||
7375 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7376 		    connp)))
7377 			break;
7378 		connp = connp->conn_next;
7379 	}
7380 
7381 	if (connp == NULL ||
7382 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7383 		goto notfound;
7384 
7385 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7386 
7387 	first_connp = connp;
7388 	/*
7389 	 * When SO_REUSEADDR is not set, send the packet only to the first
7390 	 * matching connection in its zone by keeping track of the zoneid.
7391 	 */
7392 	reuseaddr = first_connp->conn_reuseaddr;
7393 	last_zoneid = first_connp->conn_zoneid;
7394 
7395 	CONN_INC_REF(connp);
7396 	connp = connp->conn_next;
7397 	for (;;) {
7398 		while (connp != NULL) {
7399 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7400 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7401 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7402 			    (!is_system_labeled() ||
7403 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7404 			    shared_addr, connp)))
7405 				break;
7406 			connp = connp->conn_next;
7407 		}
7408 		/*
7409 		 * Just copy the data part alone. The mctl part is
7410 		 * needed just for verifying policy and it is never
7411 		 * sent up.
7412 		 */
7413 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7414 		    ((mp1 = copymsg(mp)) == NULL))) {
7415 			/*
7416 			 * No more interested clients or memory
7417 			 * allocation failed
7418 			 */
7419 			connp = first_connp;
7420 			break;
7421 		}
7422 		if (connp->conn_zoneid != last_zoneid) {
7423 			/*
7424 			 * Update the zoneid so that the packet isn't sent to
7425 			 * any more conns in the same zone unless SO_REUSEADDR
7426 			 * is set.
7427 			 */
7428 			reuseaddr = connp->conn_reuseaddr;
7429 			last_zoneid = connp->conn_zoneid;
7430 		}
7431 		if (first_mp != NULL) {
7432 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7433 			    ipsec_info_type == IPSEC_IN);
7434 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7435 			    ipst->ips_netstack);
7436 			if (first_mp1 == NULL) {
7437 				freemsg(mp1);
7438 				connp = first_connp;
7439 				break;
7440 			}
7441 		} else {
7442 			first_mp1 = NULL;
7443 		}
7444 		CONN_INC_REF(connp);
7445 		mutex_exit(&connfp->connf_lock);
7446 		/*
7447 		 * IPQoS notes: We don't send the packet for policy
7448 		 * processing here, will do it for the last one (below).
7449 		 * i.e. we do it per-packet now, but if we do policy
7450 		 * processing per-conn, then we would need to do it
7451 		 * here too.
7452 		 */
7453 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7454 		    ipha, flags, recv_ill, B_FALSE);
7455 		mutex_enter(&connfp->connf_lock);
7456 		/* Follow the next pointer before releasing the conn. */
7457 		next_connp = connp->conn_next;
7458 		IP_STAT(ipst, ip_udp_fanmb);
7459 		CONN_DEC_REF(connp);
7460 		connp = next_connp;
7461 	}
7462 
7463 	/* Last one.  Send it upstream. */
7464 	mutex_exit(&connfp->connf_lock);
7465 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7466 	    recv_ill, ip_policy);
7467 	IP_STAT(ipst, ip_udp_fanmb);
7468 	CONN_DEC_REF(connp);
7469 	return;
7470 
7471 notfound:
7472 
7473 	mutex_exit(&connfp->connf_lock);
7474 	IP_STAT(ipst, ip_udp_fanothers);
7475 	/*
7476 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7477 	 * have already been matched above, since they live in the IPv4
7478 	 * fanout tables. This implies we only need to
7479 	 * check for IPv6 in6addr_any endpoints here.
7480 	 * Thus we compare using ipv6_all_zeros instead of the destination
7481 	 * address, except for the multicast group membership lookup which
7482 	 * uses the IPv4 destination.
7483 	 */
7484 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7485 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7486 	mutex_enter(&connfp->connf_lock);
7487 	connp = connfp->connf_head;
7488 	if (!broadcast && !CLASSD(dst)) {
7489 		while (connp != NULL) {
7490 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7491 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7492 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7493 			    !connp->conn_ipv6_v6only)
7494 				break;
7495 			connp = connp->conn_next;
7496 		}
7497 
7498 		if (connp != NULL && is_system_labeled() &&
7499 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7500 		    connp))
7501 			connp = NULL;
7502 
7503 		if (connp == NULL ||
7504 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7505 			/*
7506 			 * No one bound to this port.  Is
7507 			 * there a client that wants all
7508 			 * unclaimed datagrams?
7509 			 */
7510 			mutex_exit(&connfp->connf_lock);
7511 
7512 			if (mctl_present)
7513 				first_mp->b_cont = mp;
7514 			else
7515 				first_mp = mp;
7516 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7517 			    connf_head != NULL) {
7518 				ip_fanout_proto(q, first_mp, ill, ipha,
7519 				    flags | IP_FF_RAWIP, mctl_present,
7520 				    ip_policy, recv_ill, zoneid);
7521 			} else {
7522 				if (ip_fanout_send_icmp(q, first_mp, flags,
7523 				    ICMP_DEST_UNREACHABLE,
7524 				    ICMP_PORT_UNREACHABLE,
7525 				    mctl_present, zoneid, ipst)) {
7526 					BUMP_MIB(ill->ill_ip_mib,
7527 					    udpIfStatsNoPorts);
7528 				}
7529 			}
7530 			return;
7531 		}
7532 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7533 
7534 		CONN_INC_REF(connp);
7535 		mutex_exit(&connfp->connf_lock);
7536 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7537 		    flags, recv_ill, ip_policy);
7538 		CONN_DEC_REF(connp);
7539 		return;
7540 	}
7541 	/*
7542 	 * IPv4 multicast packet being delivered to an AF_INET6
7543 	 * in6addr_any endpoint.
7544 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7545 	 * and not conn_wantpacket_v6() since any multicast membership is
7546 	 * for an IPv4-mapped multicast address.
7547 	 * The packet is sent to all clients in all zones that have joined the
7548 	 * group and match the port.
7549 	 */
7550 	while (connp != NULL) {
7551 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7552 		    srcport, v6src) &&
7553 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7554 		    (!is_system_labeled() ||
7555 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7556 		    connp)))
7557 			break;
7558 		connp = connp->conn_next;
7559 	}
7560 
7561 	if (connp == NULL ||
7562 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7563 		/*
7564 		 * No one bound to this port.  Is
7565 		 * there a client that wants all
7566 		 * unclaimed datagrams?
7567 		 */
7568 		mutex_exit(&connfp->connf_lock);
7569 
7570 		if (mctl_present)
7571 			first_mp->b_cont = mp;
7572 		else
7573 			first_mp = mp;
7574 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7575 		    NULL) {
7576 			ip_fanout_proto(q, first_mp, ill, ipha,
7577 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7578 			    recv_ill, zoneid);
7579 		} else {
7580 			/*
7581 			 * We used to attempt to send an icmp error here, but
7582 			 * since this is known to be a multicast packet
7583 			 * and we don't send icmp errors in response to
7584 			 * multicast, just drop the packet and give up sooner.
7585 			 */
7586 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7587 			freemsg(first_mp);
7588 		}
7589 		return;
7590 	}
7591 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7592 
7593 	first_connp = connp;
7594 
7595 	CONN_INC_REF(connp);
7596 	connp = connp->conn_next;
7597 	for (;;) {
7598 		while (connp != NULL) {
7599 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7600 			    ipv6_all_zeros, srcport, v6src) &&
7601 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7602 			    (!is_system_labeled() ||
7603 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7604 			    shared_addr, connp)))
7605 				break;
7606 			connp = connp->conn_next;
7607 		}
7608 		/*
7609 		 * Just copy the data part alone. The mctl part is
7610 		 * needed just for verifying policy and it is never
7611 		 * sent up.
7612 		 */
7613 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7614 		    ((mp1 = copymsg(mp)) == NULL))) {
7615 			/*
7616 			 * No more intested clients or memory
7617 			 * allocation failed
7618 			 */
7619 			connp = first_connp;
7620 			break;
7621 		}
7622 		if (first_mp != NULL) {
7623 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7624 			    ipsec_info_type == IPSEC_IN);
7625 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7626 			    ipst->ips_netstack);
7627 			if (first_mp1 == NULL) {
7628 				freemsg(mp1);
7629 				connp = first_connp;
7630 				break;
7631 			}
7632 		} else {
7633 			first_mp1 = NULL;
7634 		}
7635 		CONN_INC_REF(connp);
7636 		mutex_exit(&connfp->connf_lock);
7637 		/*
7638 		 * IPQoS notes: We don't send the packet for policy
7639 		 * processing here, will do it for the last one (below).
7640 		 * i.e. we do it per-packet now, but if we do policy
7641 		 * processing per-conn, then we would need to do it
7642 		 * here too.
7643 		 */
7644 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7645 		    ipha, flags, recv_ill, B_FALSE);
7646 		mutex_enter(&connfp->connf_lock);
7647 		/* Follow the next pointer before releasing the conn. */
7648 		next_connp = connp->conn_next;
7649 		CONN_DEC_REF(connp);
7650 		connp = next_connp;
7651 	}
7652 
7653 	/* Last one.  Send it upstream. */
7654 	mutex_exit(&connfp->connf_lock);
7655 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7656 	    recv_ill, ip_policy);
7657 	CONN_DEC_REF(connp);
7658 }
7659 
7660 /*
7661  * Complete the ip_wput header so that it
7662  * is possible to generate ICMP
7663  * errors.
7664  */
7665 int
7666 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7667 {
7668 	ire_t *ire;
7669 
7670 	if (ipha->ipha_src == INADDR_ANY) {
7671 		ire = ire_lookup_local(zoneid, ipst);
7672 		if (ire == NULL) {
7673 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7674 			return (1);
7675 		}
7676 		ipha->ipha_src = ire->ire_addr;
7677 		ire_refrele(ire);
7678 	}
7679 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7680 	ipha->ipha_hdr_checksum = 0;
7681 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7682 	return (0);
7683 }
7684 
7685 /*
7686  * Nobody should be sending
7687  * packets up this stream
7688  */
7689 static void
7690 ip_lrput(queue_t *q, mblk_t *mp)
7691 {
7692 	mblk_t *mp1;
7693 
7694 	switch (mp->b_datap->db_type) {
7695 	case M_FLUSH:
7696 		/* Turn around */
7697 		if (*mp->b_rptr & FLUSHW) {
7698 			*mp->b_rptr &= ~FLUSHR;
7699 			qreply(q, mp);
7700 			return;
7701 		}
7702 		break;
7703 	}
7704 	/* Could receive messages that passed through ar_rput */
7705 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7706 		mp1->b_prev = mp1->b_next = NULL;
7707 	freemsg(mp);
7708 }
7709 
7710 /* Nobody should be sending packets down this stream */
7711 /* ARGSUSED */
7712 void
7713 ip_lwput(queue_t *q, mblk_t *mp)
7714 {
7715 	freemsg(mp);
7716 }
7717 
7718 /*
7719  * Move the first hop in any source route to ipha_dst and remove that part of
7720  * the source route.  Called by other protocols.  Errors in option formatting
7721  * are ignored - will be handled by ip_wput_options Return the final
7722  * destination (either ipha_dst or the last entry in a source route.)
7723  */
7724 ipaddr_t
7725 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7726 {
7727 	ipoptp_t	opts;
7728 	uchar_t		*opt;
7729 	uint8_t		optval;
7730 	uint8_t		optlen;
7731 	ipaddr_t	dst;
7732 	int		i;
7733 	ire_t		*ire;
7734 	ip_stack_t	*ipst = ns->netstack_ip;
7735 
7736 	ip2dbg(("ip_massage_options\n"));
7737 	dst = ipha->ipha_dst;
7738 	for (optval = ipoptp_first(&opts, ipha);
7739 	    optval != IPOPT_EOL;
7740 	    optval = ipoptp_next(&opts)) {
7741 		opt = opts.ipoptp_cur;
7742 		switch (optval) {
7743 			uint8_t off;
7744 		case IPOPT_SSRR:
7745 		case IPOPT_LSRR:
7746 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7747 				ip1dbg(("ip_massage_options: bad src route\n"));
7748 				break;
7749 			}
7750 			optlen = opts.ipoptp_len;
7751 			off = opt[IPOPT_OFFSET];
7752 			off--;
7753 		redo_srr:
7754 			if (optlen < IP_ADDR_LEN ||
7755 			    off > optlen - IP_ADDR_LEN) {
7756 				/* End of source route */
7757 				ip1dbg(("ip_massage_options: end of SR\n"));
7758 				break;
7759 			}
7760 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7761 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7762 			    ntohl(dst)));
7763 			/*
7764 			 * Check if our address is present more than
7765 			 * once as consecutive hops in source route.
7766 			 * XXX verify per-interface ip_forwarding
7767 			 * for source route?
7768 			 */
7769 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7770 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7771 			if (ire != NULL) {
7772 				ire_refrele(ire);
7773 				off += IP_ADDR_LEN;
7774 				goto redo_srr;
7775 			}
7776 			if (dst == htonl(INADDR_LOOPBACK)) {
7777 				ip1dbg(("ip_massage_options: loopback addr in "
7778 				    "source route!\n"));
7779 				break;
7780 			}
7781 			/*
7782 			 * Update ipha_dst to be the first hop and remove the
7783 			 * first hop from the source route (by overwriting
7784 			 * part of the option with NOP options).
7785 			 */
7786 			ipha->ipha_dst = dst;
7787 			/* Put the last entry in dst */
7788 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7789 			    3;
7790 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7791 
7792 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7793 			    ntohl(dst)));
7794 			/* Move down and overwrite */
7795 			opt[IP_ADDR_LEN] = opt[0];
7796 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7797 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7798 			for (i = 0; i < IP_ADDR_LEN; i++)
7799 				opt[i] = IPOPT_NOP;
7800 			break;
7801 		}
7802 	}
7803 	return (dst);
7804 }
7805 
7806 /*
7807  * Return the network mask
7808  * associated with the specified address.
7809  */
7810 ipaddr_t
7811 ip_net_mask(ipaddr_t addr)
7812 {
7813 	uchar_t	*up = (uchar_t *)&addr;
7814 	ipaddr_t mask = 0;
7815 	uchar_t	*maskp = (uchar_t *)&mask;
7816 
7817 #if defined(__i386) || defined(__amd64)
7818 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7819 #endif
7820 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7821 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7822 #endif
7823 	if (CLASSD(addr)) {
7824 		maskp[0] = 0xF0;
7825 		return (mask);
7826 	}
7827 
7828 	/* We assume Class E default netmask to be 32 */
7829 	if (CLASSE(addr))
7830 		return (0xffffffffU);
7831 
7832 	if (addr == 0)
7833 		return (0);
7834 	maskp[0] = 0xFF;
7835 	if ((up[0] & 0x80) == 0)
7836 		return (mask);
7837 
7838 	maskp[1] = 0xFF;
7839 	if ((up[0] & 0xC0) == 0x80)
7840 		return (mask);
7841 
7842 	maskp[2] = 0xFF;
7843 	if ((up[0] & 0xE0) == 0xC0)
7844 		return (mask);
7845 
7846 	/* Otherwise return no mask */
7847 	return ((ipaddr_t)0);
7848 }
7849 
7850 /*
7851  * Helper ill lookup function used by IPsec.
7852  */
7853 ill_t *
7854 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7855 {
7856 	ill_t *ret_ill;
7857 
7858 	ASSERT(ifindex != 0);
7859 
7860 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7861 	    ipst);
7862 	if (ret_ill == NULL) {
7863 		if (isv6) {
7864 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7865 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7866 			    ifindex));
7867 		} else {
7868 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7869 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7870 			    ifindex));
7871 		}
7872 		freemsg(first_mp);
7873 		return (NULL);
7874 	}
7875 	return (ret_ill);
7876 }
7877 
7878 /*
7879  * IPv4 -
7880  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7881  * out a packet to a destination address for which we do not have specific
7882  * (or sufficient) routing information.
7883  *
7884  * NOTE : These are the scopes of some of the variables that point at IRE,
7885  *	  which needs to be followed while making any future modifications
7886  *	  to avoid memory leaks.
7887  *
7888  *	- ire and sire are the entries looked up initially by
7889  *	  ire_ftable_lookup.
7890  *	- ipif_ire is used to hold the interface ire associated with
7891  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7892  *	  it before branching out to error paths.
7893  *	- save_ire is initialized before ire_create, so that ire returned
7894  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7895  *	  before breaking out of the switch.
7896  *
7897  *	Thus on failures, we have to REFRELE only ire and sire, if they
7898  *	are not NULL.
7899  */
7900 void
7901 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7902     zoneid_t zoneid, ip_stack_t *ipst)
7903 {
7904 	areq_t	*areq;
7905 	ipaddr_t gw = 0;
7906 	ire_t	*ire = NULL;
7907 	mblk_t	*res_mp;
7908 	ipaddr_t *addrp;
7909 	ipaddr_t nexthop_addr;
7910 	ipif_t  *src_ipif = NULL;
7911 	ill_t	*dst_ill = NULL;
7912 	ipha_t  *ipha;
7913 	ire_t	*sire = NULL;
7914 	mblk_t	*first_mp;
7915 	ire_t	*save_ire;
7916 	ushort_t ire_marks = 0;
7917 	boolean_t mctl_present;
7918 	ipsec_out_t *io;
7919 	mblk_t	*saved_mp;
7920 	ire_t	*first_sire = NULL;
7921 	mblk_t	*copy_mp = NULL;
7922 	mblk_t	*xmit_mp = NULL;
7923 	ipaddr_t save_dst;
7924 	uint32_t multirt_flags =
7925 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7926 	boolean_t multirt_is_resolvable;
7927 	boolean_t multirt_resolve_next;
7928 	boolean_t unspec_src;
7929 	boolean_t ip_nexthop = B_FALSE;
7930 	tsol_ire_gw_secattr_t *attrp = NULL;
7931 	tsol_gcgrp_t *gcgrp = NULL;
7932 	tsol_gcgrp_addr_t ga;
7933 
7934 	if (ip_debug > 2) {
7935 		/* ip1dbg */
7936 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7937 	}
7938 
7939 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7940 	if (mctl_present) {
7941 		io = (ipsec_out_t *)first_mp->b_rptr;
7942 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7943 		ASSERT(zoneid == io->ipsec_out_zoneid);
7944 		ASSERT(zoneid != ALL_ZONES);
7945 	}
7946 
7947 	ipha = (ipha_t *)mp->b_rptr;
7948 
7949 	/* All multicast lookups come through ip_newroute_ipif() */
7950 	if (CLASSD(dst)) {
7951 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7952 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7953 		freemsg(first_mp);
7954 		return;
7955 	}
7956 
7957 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7958 		ip_nexthop = B_TRUE;
7959 		nexthop_addr = io->ipsec_out_nexthop_addr;
7960 	}
7961 	/*
7962 	 * If this IRE is created for forwarding or it is not for
7963 	 * traffic for congestion controlled protocols, mark it as temporary.
7964 	 */
7965 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7966 		ire_marks |= IRE_MARK_TEMPORARY;
7967 
7968 	/*
7969 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7970 	 * chain until it gets the most specific information available.
7971 	 * For example, we know that there is no IRE_CACHE for this dest,
7972 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7973 	 * ire_ftable_lookup will look up the gateway, etc.
7974 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7975 	 * to the destination, of equal netmask length in the forward table,
7976 	 * will be recursively explored. If no information is available
7977 	 * for the final gateway of that route, we force the returned ire
7978 	 * to be equal to sire using MATCH_IRE_PARENT.
7979 	 * At least, in this case we have a starting point (in the buckets)
7980 	 * to look for other routes to the destination in the forward table.
7981 	 * This is actually used only for multirouting, where a list
7982 	 * of routes has to be processed in sequence.
7983 	 *
7984 	 * In the process of coming up with the most specific information,
7985 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7986 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7987 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7988 	 * Two caveats when handling incomplete ire's in ip_newroute:
7989 	 * - we should be careful when accessing its ire_nce (specifically
7990 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7991 	 * - not all legacy code path callers are prepared to handle
7992 	 *   incomplete ire's, so we should not create/add incomplete
7993 	 *   ire_cache entries here. (See discussion about temporary solution
7994 	 *   further below).
7995 	 *
7996 	 * In order to minimize packet dropping, and to preserve existing
7997 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7998 	 * gateway, and instead use the IF_RESOLVER ire to send out
7999 	 * another request to ARP (this is achieved by passing the
8000 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8001 	 * arp response comes back in ip_wput_nondata, we will create
8002 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8003 	 *
8004 	 * Note that this is a temporary solution; the correct solution is
8005 	 * to create an incomplete  per-dst ire_cache entry, and send the
8006 	 * packet out when the gw's nce is resolved. In order to achieve this,
8007 	 * all packet processing must have been completed prior to calling
8008 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8009 	 * to be modified to accomodate this solution.
8010 	 */
8011 	if (ip_nexthop) {
8012 		/*
8013 		 * The first time we come here, we look for an IRE_INTERFACE
8014 		 * entry for the specified nexthop, set the dst to be the
8015 		 * nexthop address and create an IRE_CACHE entry for the
8016 		 * nexthop. The next time around, we are able to find an
8017 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8018 		 * nexthop address and create an IRE_CACHE entry for the
8019 		 * destination address via the specified nexthop.
8020 		 */
8021 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8022 		    msg_getlabel(mp), ipst);
8023 		if (ire != NULL) {
8024 			gw = nexthop_addr;
8025 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8026 		} else {
8027 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8028 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8029 			    msg_getlabel(mp),
8030 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8031 			    ipst);
8032 			if (ire != NULL) {
8033 				dst = nexthop_addr;
8034 			}
8035 		}
8036 	} else {
8037 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8038 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
8039 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8040 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8041 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8042 		    ipst);
8043 	}
8044 
8045 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8046 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8047 
8048 	/*
8049 	 * This loop is run only once in most cases.
8050 	 * We loop to resolve further routes only when the destination
8051 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8052 	 */
8053 	do {
8054 		/* Clear the previous iteration's values */
8055 		if (src_ipif != NULL) {
8056 			ipif_refrele(src_ipif);
8057 			src_ipif = NULL;
8058 		}
8059 		if (dst_ill != NULL) {
8060 			ill_refrele(dst_ill);
8061 			dst_ill = NULL;
8062 		}
8063 
8064 		multirt_resolve_next = B_FALSE;
8065 		/*
8066 		 * We check if packets have to be multirouted.
8067 		 * In this case, given the current <ire, sire> couple,
8068 		 * we look for the next suitable <ire, sire>.
8069 		 * This check is done in ire_multirt_lookup(),
8070 		 * which applies various criteria to find the next route
8071 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8072 		 * unchanged if it detects it has not been tried yet.
8073 		 */
8074 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8075 			ip3dbg(("ip_newroute: starting next_resolution "
8076 			    "with first_mp %p, tag %d\n",
8077 			    (void *)first_mp,
8078 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8079 
8080 			ASSERT(sire != NULL);
8081 			multirt_is_resolvable =
8082 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8083 			    msg_getlabel(mp), ipst);
8084 
8085 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8086 			    "ire %p, sire %p\n",
8087 			    multirt_is_resolvable,
8088 			    (void *)ire, (void *)sire));
8089 
8090 			if (!multirt_is_resolvable) {
8091 				/*
8092 				 * No more multirt route to resolve; give up
8093 				 * (all routes resolved or no more
8094 				 * resolvable routes).
8095 				 */
8096 				if (ire != NULL) {
8097 					ire_refrele(ire);
8098 					ire = NULL;
8099 				}
8100 			} else {
8101 				ASSERT(sire != NULL);
8102 				ASSERT(ire != NULL);
8103 				/*
8104 				 * We simply use first_sire as a flag that
8105 				 * indicates if a resolvable multirt route
8106 				 * has already been found.
8107 				 * If it is not the case, we may have to send
8108 				 * an ICMP error to report that the
8109 				 * destination is unreachable.
8110 				 * We do not IRE_REFHOLD first_sire.
8111 				 */
8112 				if (first_sire == NULL) {
8113 					first_sire = sire;
8114 				}
8115 			}
8116 		}
8117 		if (ire == NULL) {
8118 			if (ip_debug > 3) {
8119 				/* ip2dbg */
8120 				pr_addr_dbg("ip_newroute: "
8121 				    "can't resolve %s\n", AF_INET, &dst);
8122 			}
8123 			ip3dbg(("ip_newroute: "
8124 			    "ire %p, sire %p, first_sire %p\n",
8125 			    (void *)ire, (void *)sire, (void *)first_sire));
8126 
8127 			if (sire != NULL) {
8128 				ire_refrele(sire);
8129 				sire = NULL;
8130 			}
8131 
8132 			if (first_sire != NULL) {
8133 				/*
8134 				 * At least one multirt route has been found
8135 				 * in the same call to ip_newroute();
8136 				 * there is no need to report an ICMP error.
8137 				 * first_sire was not IRE_REFHOLDed.
8138 				 */
8139 				MULTIRT_DEBUG_UNTAG(first_mp);
8140 				freemsg(first_mp);
8141 				return;
8142 			}
8143 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8144 			    RTA_DST, ipst);
8145 			goto icmp_err_ret;
8146 		}
8147 
8148 		/*
8149 		 * Verify that the returned IRE does not have either
8150 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8151 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8152 		 */
8153 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8154 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8155 			goto icmp_err_ret;
8156 		}
8157 		/*
8158 		 * Increment the ire_ob_pkt_count field for ire if it is an
8159 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8160 		 * increment the same for the parent IRE, sire, if it is some
8161 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8162 		 */
8163 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8164 			UPDATE_OB_PKT_COUNT(ire);
8165 			ire->ire_last_used_time = lbolt;
8166 		}
8167 
8168 		if (sire != NULL) {
8169 			gw = sire->ire_gateway_addr;
8170 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8171 			    IRE_INTERFACE)) == 0);
8172 			UPDATE_OB_PKT_COUNT(sire);
8173 			sire->ire_last_used_time = lbolt;
8174 		}
8175 		/*
8176 		 * We have a route to reach the destination.  Find the
8177 		 * appropriate ill, then get a source address using
8178 		 * ipif_select_source().
8179 		 *
8180 		 * If we are here trying to create an IRE_CACHE for an offlink
8181 		 * destination and have an IRE_CACHE entry for VNI, then use
8182 		 * ire_stq instead since VNI's queue is a black hole.
8183 		 */
8184 		if ((ire->ire_type == IRE_CACHE) &&
8185 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8186 			dst_ill = ire->ire_stq->q_ptr;
8187 			ill_refhold(dst_ill);
8188 		} else {
8189 			ill_t *ill = ire->ire_ipif->ipif_ill;
8190 
8191 			if (IS_IPMP(ill)) {
8192 				dst_ill =
8193 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8194 			} else {
8195 				dst_ill = ill;
8196 				ill_refhold(dst_ill);
8197 			}
8198 		}
8199 
8200 		if (dst_ill == NULL) {
8201 			if (ip_debug > 2) {
8202 				pr_addr_dbg("ip_newroute: no dst "
8203 				    "ill for dst %s\n", AF_INET, &dst);
8204 			}
8205 			goto icmp_err_ret;
8206 		}
8207 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8208 
8209 		/*
8210 		 * Pick the best source address from dst_ill.
8211 		 *
8212 		 * 1) Try to pick the source address from the destination
8213 		 *    route. Clustering assumes that when we have multiple
8214 		 *    prefixes hosted on an interface, the prefix of the
8215 		 *    source address matches the prefix of the destination
8216 		 *    route. We do this only if the address is not
8217 		 *    DEPRECATED.
8218 		 *
8219 		 * 2) If the conn is in a different zone than the ire, we
8220 		 *    need to pick a source address from the right zone.
8221 		 */
8222 		ASSERT(src_ipif == NULL);
8223 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8224 			/*
8225 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8226 			 * Check that the ipif matching the requested source
8227 			 * address still exists.
8228 			 */
8229 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8230 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8231 		}
8232 
8233 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8234 
8235 		if (src_ipif == NULL &&
8236 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8237 			ire_marks |= IRE_MARK_USESRC_CHECK;
8238 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8239 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8240 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8241 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8242 			    ire->ire_zoneid != ALL_ZONES) ||
8243 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8244 				/*
8245 				 * If the destination is reachable via a
8246 				 * given gateway, the selected source address
8247 				 * should be in the same subnet as the gateway.
8248 				 * Otherwise, the destination is not reachable.
8249 				 *
8250 				 * If there are no interfaces on the same subnet
8251 				 * as the destination, ipif_select_source gives
8252 				 * first non-deprecated interface which might be
8253 				 * on a different subnet than the gateway.
8254 				 * This is not desirable. Hence pass the dst_ire
8255 				 * source address to ipif_select_source.
8256 				 * It is sure that the destination is reachable
8257 				 * with the dst_ire source address subnet.
8258 				 * So passing dst_ire source address to
8259 				 * ipif_select_source will make sure that the
8260 				 * selected source will be on the same subnet
8261 				 * as dst_ire source address.
8262 				 */
8263 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8264 
8265 				src_ipif = ipif_select_source(dst_ill, saddr,
8266 				    zoneid);
8267 				if (src_ipif == NULL) {
8268 					if (ip_debug > 2) {
8269 						pr_addr_dbg("ip_newroute: "
8270 						    "no src for dst %s ",
8271 						    AF_INET, &dst);
8272 						printf("on interface %s\n",
8273 						    dst_ill->ill_name);
8274 					}
8275 					goto icmp_err_ret;
8276 				}
8277 			} else {
8278 				src_ipif = ire->ire_ipif;
8279 				ASSERT(src_ipif != NULL);
8280 				/* hold src_ipif for uniformity */
8281 				ipif_refhold(src_ipif);
8282 			}
8283 		}
8284 
8285 		/*
8286 		 * Assign a source address while we have the conn.
8287 		 * We can't have ip_wput_ire pick a source address when the
8288 		 * packet returns from arp since we need to look at
8289 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8290 		 * going through arp.
8291 		 *
8292 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8293 		 *	  it uses ip6i to store this information.
8294 		 */
8295 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8296 			ipha->ipha_src = src_ipif->ipif_src_addr;
8297 
8298 		if (ip_debug > 3) {
8299 			/* ip2dbg */
8300 			pr_addr_dbg("ip_newroute: first hop %s\n",
8301 			    AF_INET, &gw);
8302 		}
8303 		ip2dbg(("\tire type %s (%d)\n",
8304 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8305 
8306 		/*
8307 		 * The TTL of multirouted packets is bounded by the
8308 		 * ip_multirt_ttl ndd variable.
8309 		 */
8310 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8311 			/* Force TTL of multirouted packets */
8312 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8313 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8314 				ip2dbg(("ip_newroute: forcing multirt TTL "
8315 				    "to %d (was %d), dst 0x%08x\n",
8316 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8317 				    ntohl(sire->ire_addr)));
8318 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8319 			}
8320 		}
8321 		/*
8322 		 * At this point in ip_newroute(), ire is either the
8323 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8324 		 * destination or an IRE_INTERFACE type that should be used
8325 		 * to resolve an on-subnet destination or an on-subnet
8326 		 * next-hop gateway.
8327 		 *
8328 		 * In the IRE_CACHE case, we have the following :
8329 		 *
8330 		 * 1) src_ipif - used for getting a source address.
8331 		 *
8332 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8333 		 *    means packets using this IRE_CACHE will go out on
8334 		 *    dst_ill.
8335 		 *
8336 		 * 3) The IRE sire will point to the prefix that is the
8337 		 *    longest  matching route for the destination. These
8338 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8339 		 *
8340 		 *    The newly created IRE_CACHE entry for the off-subnet
8341 		 *    destination is tied to both the prefix route and the
8342 		 *    interface route used to resolve the next-hop gateway
8343 		 *    via the ire_phandle and ire_ihandle fields,
8344 		 *    respectively.
8345 		 *
8346 		 * In the IRE_INTERFACE case, we have the following :
8347 		 *
8348 		 * 1) src_ipif - used for getting a source address.
8349 		 *
8350 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8351 		 *    means packets using the IRE_CACHE that we will build
8352 		 *    here will go out on dst_ill.
8353 		 *
8354 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8355 		 *    to be created will only be tied to the IRE_INTERFACE
8356 		 *    that was derived from the ire_ihandle field.
8357 		 *
8358 		 *    If sire is non-NULL, it means the destination is
8359 		 *    off-link and we will first create the IRE_CACHE for the
8360 		 *    gateway. Next time through ip_newroute, we will create
8361 		 *    the IRE_CACHE for the final destination as described
8362 		 *    above.
8363 		 *
8364 		 * In both cases, after the current resolution has been
8365 		 * completed (or possibly initialised, in the IRE_INTERFACE
8366 		 * case), the loop may be re-entered to attempt the resolution
8367 		 * of another RTF_MULTIRT route.
8368 		 *
8369 		 * When an IRE_CACHE entry for the off-subnet destination is
8370 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8371 		 * for further processing in emission loops.
8372 		 */
8373 		save_ire = ire;
8374 		switch (ire->ire_type) {
8375 		case IRE_CACHE: {
8376 			ire_t	*ipif_ire;
8377 
8378 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8379 			if (gw == 0)
8380 				gw = ire->ire_gateway_addr;
8381 			/*
8382 			 * We need 3 ire's to create a new cache ire for an
8383 			 * off-link destination from the cache ire of the
8384 			 * gateway.
8385 			 *
8386 			 *	1. The prefix ire 'sire' (Note that this does
8387 			 *	   not apply to the conn_nexthop_set case)
8388 			 *	2. The cache ire of the gateway 'ire'
8389 			 *	3. The interface ire 'ipif_ire'
8390 			 *
8391 			 * We have (1) and (2). We lookup (3) below.
8392 			 *
8393 			 * If there is no interface route to the gateway,
8394 			 * it is a race condition, where we found the cache
8395 			 * but the interface route has been deleted.
8396 			 */
8397 			if (ip_nexthop) {
8398 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8399 			} else {
8400 				ipif_ire =
8401 				    ire_ihandle_lookup_offlink(ire, sire);
8402 			}
8403 			if (ipif_ire == NULL) {
8404 				ip1dbg(("ip_newroute: "
8405 				    "ire_ihandle_lookup_offlink failed\n"));
8406 				goto icmp_err_ret;
8407 			}
8408 
8409 			/*
8410 			 * Check cached gateway IRE for any security
8411 			 * attributes; if found, associate the gateway
8412 			 * credentials group to the destination IRE.
8413 			 */
8414 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8415 				mutex_enter(&attrp->igsa_lock);
8416 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8417 					GCGRP_REFHOLD(gcgrp);
8418 				mutex_exit(&attrp->igsa_lock);
8419 			}
8420 
8421 			/*
8422 			 * XXX For the source of the resolver mp,
8423 			 * we are using the same DL_UNITDATA_REQ
8424 			 * (from save_ire->ire_nce->nce_res_mp)
8425 			 * though the save_ire is not pointing at the same ill.
8426 			 * This is incorrect. We need to send it up to the
8427 			 * resolver to get the right res_mp. For ethernets
8428 			 * this may be okay (ill_type == DL_ETHER).
8429 			 */
8430 
8431 			ire = ire_create(
8432 			    (uchar_t *)&dst,		/* dest address */
8433 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8434 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8435 			    (uchar_t *)&gw,		/* gateway address */
8436 			    &save_ire->ire_max_frag,
8437 			    save_ire->ire_nce,		/* src nce */
8438 			    dst_ill->ill_rq,		/* recv-from queue */
8439 			    dst_ill->ill_wq,		/* send-to queue */
8440 			    IRE_CACHE,			/* IRE type */
8441 			    src_ipif,
8442 			    (sire != NULL) ?
8443 			    sire->ire_mask : 0, 	/* Parent mask */
8444 			    (sire != NULL) ?
8445 			    sire->ire_phandle : 0,	/* Parent handle */
8446 			    ipif_ire->ire_ihandle,	/* Interface handle */
8447 			    (sire != NULL) ? (sire->ire_flags &
8448 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8449 			    (sire != NULL) ?
8450 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8451 			    NULL,
8452 			    gcgrp,
8453 			    ipst);
8454 
8455 			if (ire == NULL) {
8456 				if (gcgrp != NULL) {
8457 					GCGRP_REFRELE(gcgrp);
8458 					gcgrp = NULL;
8459 				}
8460 				ire_refrele(ipif_ire);
8461 				ire_refrele(save_ire);
8462 				break;
8463 			}
8464 
8465 			/* reference now held by IRE */
8466 			gcgrp = NULL;
8467 
8468 			ire->ire_marks |= ire_marks;
8469 
8470 			/*
8471 			 * Prevent sire and ipif_ire from getting deleted.
8472 			 * The newly created ire is tied to both of them via
8473 			 * the phandle and ihandle respectively.
8474 			 */
8475 			if (sire != NULL) {
8476 				IRB_REFHOLD(sire->ire_bucket);
8477 				/* Has it been removed already ? */
8478 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8479 					IRB_REFRELE(sire->ire_bucket);
8480 					ire_refrele(ipif_ire);
8481 					ire_refrele(save_ire);
8482 					break;
8483 				}
8484 			}
8485 
8486 			IRB_REFHOLD(ipif_ire->ire_bucket);
8487 			/* Has it been removed already ? */
8488 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8489 				IRB_REFRELE(ipif_ire->ire_bucket);
8490 				if (sire != NULL)
8491 					IRB_REFRELE(sire->ire_bucket);
8492 				ire_refrele(ipif_ire);
8493 				ire_refrele(save_ire);
8494 				break;
8495 			}
8496 
8497 			xmit_mp = first_mp;
8498 			/*
8499 			 * In the case of multirouting, a copy
8500 			 * of the packet is done before its sending.
8501 			 * The copy is used to attempt another
8502 			 * route resolution, in a next loop.
8503 			 */
8504 			if (ire->ire_flags & RTF_MULTIRT) {
8505 				copy_mp = copymsg(first_mp);
8506 				if (copy_mp != NULL) {
8507 					xmit_mp = copy_mp;
8508 					MULTIRT_DEBUG_TAG(first_mp);
8509 				}
8510 			}
8511 
8512 			ire_add_then_send(q, ire, xmit_mp);
8513 			ire_refrele(save_ire);
8514 
8515 			/* Assert that sire is not deleted yet. */
8516 			if (sire != NULL) {
8517 				ASSERT(sire->ire_ptpn != NULL);
8518 				IRB_REFRELE(sire->ire_bucket);
8519 			}
8520 
8521 			/* Assert that ipif_ire is not deleted yet. */
8522 			ASSERT(ipif_ire->ire_ptpn != NULL);
8523 			IRB_REFRELE(ipif_ire->ire_bucket);
8524 			ire_refrele(ipif_ire);
8525 
8526 			/*
8527 			 * If copy_mp is not NULL, multirouting was
8528 			 * requested. We loop to initiate a next
8529 			 * route resolution attempt, starting from sire.
8530 			 */
8531 			if (copy_mp != NULL) {
8532 				/*
8533 				 * Search for the next unresolved
8534 				 * multirt route.
8535 				 */
8536 				copy_mp = NULL;
8537 				ipif_ire = NULL;
8538 				ire = NULL;
8539 				multirt_resolve_next = B_TRUE;
8540 				continue;
8541 			}
8542 			if (sire != NULL)
8543 				ire_refrele(sire);
8544 			ipif_refrele(src_ipif);
8545 			ill_refrele(dst_ill);
8546 			return;
8547 		}
8548 		case IRE_IF_NORESOLVER: {
8549 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8550 			    dst_ill->ill_resolver_mp == NULL) {
8551 				ip1dbg(("ip_newroute: dst_ill %p "
8552 				    "for IRE_IF_NORESOLVER ire %p has "
8553 				    "no ill_resolver_mp\n",
8554 				    (void *)dst_ill, (void *)ire));
8555 				break;
8556 			}
8557 
8558 			/*
8559 			 * TSol note: We are creating the ire cache for the
8560 			 * destination 'dst'. If 'dst' is offlink, going
8561 			 * through the first hop 'gw', the security attributes
8562 			 * of 'dst' must be set to point to the gateway
8563 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8564 			 * is possible that 'dst' is a potential gateway that is
8565 			 * referenced by some route that has some security
8566 			 * attributes. Thus in the former case, we need to do a
8567 			 * gcgrp_lookup of 'gw' while in the latter case we
8568 			 * need to do gcgrp_lookup of 'dst' itself.
8569 			 */
8570 			ga.ga_af = AF_INET;
8571 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8572 			    &ga.ga_addr);
8573 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8574 
8575 			ire = ire_create(
8576 			    (uchar_t *)&dst,		/* dest address */
8577 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8578 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8579 			    (uchar_t *)&gw,		/* gateway address */
8580 			    &save_ire->ire_max_frag,
8581 			    NULL,			/* no src nce */
8582 			    dst_ill->ill_rq,		/* recv-from queue */
8583 			    dst_ill->ill_wq,		/* send-to queue */
8584 			    IRE_CACHE,
8585 			    src_ipif,
8586 			    save_ire->ire_mask,		/* Parent mask */
8587 			    (sire != NULL) ?		/* Parent handle */
8588 			    sire->ire_phandle : 0,
8589 			    save_ire->ire_ihandle,	/* Interface handle */
8590 			    (sire != NULL) ? sire->ire_flags &
8591 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8592 			    &(save_ire->ire_uinfo),
8593 			    NULL,
8594 			    gcgrp,
8595 			    ipst);
8596 
8597 			if (ire == NULL) {
8598 				if (gcgrp != NULL) {
8599 					GCGRP_REFRELE(gcgrp);
8600 					gcgrp = NULL;
8601 				}
8602 				ire_refrele(save_ire);
8603 				break;
8604 			}
8605 
8606 			/* reference now held by IRE */
8607 			gcgrp = NULL;
8608 
8609 			ire->ire_marks |= ire_marks;
8610 
8611 			/* Prevent save_ire from getting deleted */
8612 			IRB_REFHOLD(save_ire->ire_bucket);
8613 			/* Has it been removed already ? */
8614 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8615 				IRB_REFRELE(save_ire->ire_bucket);
8616 				ire_refrele(save_ire);
8617 				break;
8618 			}
8619 
8620 			/*
8621 			 * In the case of multirouting, a copy
8622 			 * of the packet is made before it is sent.
8623 			 * The copy is used in the next
8624 			 * loop to attempt another resolution.
8625 			 */
8626 			xmit_mp = first_mp;
8627 			if ((sire != NULL) &&
8628 			    (sire->ire_flags & RTF_MULTIRT)) {
8629 				copy_mp = copymsg(first_mp);
8630 				if (copy_mp != NULL) {
8631 					xmit_mp = copy_mp;
8632 					MULTIRT_DEBUG_TAG(first_mp);
8633 				}
8634 			}
8635 			ire_add_then_send(q, ire, xmit_mp);
8636 
8637 			/* Assert that it is not deleted yet. */
8638 			ASSERT(save_ire->ire_ptpn != NULL);
8639 			IRB_REFRELE(save_ire->ire_bucket);
8640 			ire_refrele(save_ire);
8641 
8642 			if (copy_mp != NULL) {
8643 				/*
8644 				 * If we found a (no)resolver, we ignore any
8645 				 * trailing top priority IRE_CACHE in further
8646 				 * loops. This ensures that we do not omit any
8647 				 * (no)resolver.
8648 				 * This IRE_CACHE, if any, will be processed
8649 				 * by another thread entering ip_newroute().
8650 				 * IRE_CACHE entries, if any, will be processed
8651 				 * by another thread entering ip_newroute(),
8652 				 * (upon resolver response, for instance).
8653 				 * This aims to force parallel multirt
8654 				 * resolutions as soon as a packet must be sent.
8655 				 * In the best case, after the tx of only one
8656 				 * packet, all reachable routes are resolved.
8657 				 * Otherwise, the resolution of all RTF_MULTIRT
8658 				 * routes would require several emissions.
8659 				 */
8660 				multirt_flags &= ~MULTIRT_CACHEGW;
8661 
8662 				/*
8663 				 * Search for the next unresolved multirt
8664 				 * route.
8665 				 */
8666 				copy_mp = NULL;
8667 				save_ire = NULL;
8668 				ire = NULL;
8669 				multirt_resolve_next = B_TRUE;
8670 				continue;
8671 			}
8672 
8673 			/*
8674 			 * Don't need sire anymore
8675 			 */
8676 			if (sire != NULL)
8677 				ire_refrele(sire);
8678 
8679 			ipif_refrele(src_ipif);
8680 			ill_refrele(dst_ill);
8681 			return;
8682 		}
8683 		case IRE_IF_RESOLVER:
8684 			/*
8685 			 * We can't build an IRE_CACHE yet, but at least we
8686 			 * found a resolver that can help.
8687 			 */
8688 			res_mp = dst_ill->ill_resolver_mp;
8689 			if (!OK_RESOLVER_MP(res_mp))
8690 				break;
8691 
8692 			/*
8693 			 * To be at this point in the code with a non-zero gw
8694 			 * means that dst is reachable through a gateway that
8695 			 * we have never resolved.  By changing dst to the gw
8696 			 * addr we resolve the gateway first.
8697 			 * When ire_add_then_send() tries to put the IP dg
8698 			 * to dst, it will reenter ip_newroute() at which
8699 			 * time we will find the IRE_CACHE for the gw and
8700 			 * create another IRE_CACHE in case IRE_CACHE above.
8701 			 */
8702 			if (gw != INADDR_ANY) {
8703 				/*
8704 				 * The source ipif that was determined above was
8705 				 * relative to the destination address, not the
8706 				 * gateway's. If src_ipif was not taken out of
8707 				 * the IRE_IF_RESOLVER entry, we'll need to call
8708 				 * ipif_select_source() again.
8709 				 */
8710 				if (src_ipif != ire->ire_ipif) {
8711 					ipif_refrele(src_ipif);
8712 					src_ipif = ipif_select_source(dst_ill,
8713 					    gw, zoneid);
8714 					if (src_ipif == NULL) {
8715 						if (ip_debug > 2) {
8716 							pr_addr_dbg(
8717 							    "ip_newroute: no "
8718 							    "src for gw %s ",
8719 							    AF_INET, &gw);
8720 							printf("on "
8721 							    "interface %s\n",
8722 							    dst_ill->ill_name);
8723 						}
8724 						goto icmp_err_ret;
8725 					}
8726 				}
8727 				save_dst = dst;
8728 				dst = gw;
8729 				gw = INADDR_ANY;
8730 			}
8731 
8732 			/*
8733 			 * We obtain a partial IRE_CACHE which we will pass
8734 			 * along with the resolver query.  When the response
8735 			 * comes back it will be there ready for us to add.
8736 			 * The ire_max_frag is atomically set under the
8737 			 * irebucket lock in ire_add_v[46].
8738 			 */
8739 
8740 			ire = ire_create_mp(
8741 			    (uchar_t *)&dst,		/* dest address */
8742 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8743 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8744 			    (uchar_t *)&gw,		/* gateway address */
8745 			    NULL,			/* ire_max_frag */
8746 			    NULL,			/* no src nce */
8747 			    dst_ill->ill_rq,		/* recv-from queue */
8748 			    dst_ill->ill_wq,		/* send-to queue */
8749 			    IRE_CACHE,
8750 			    src_ipif,			/* Interface ipif */
8751 			    save_ire->ire_mask,		/* Parent mask */
8752 			    0,
8753 			    save_ire->ire_ihandle,	/* Interface handle */
8754 			    0,				/* flags if any */
8755 			    &(save_ire->ire_uinfo),
8756 			    NULL,
8757 			    NULL,
8758 			    ipst);
8759 
8760 			if (ire == NULL) {
8761 				ire_refrele(save_ire);
8762 				break;
8763 			}
8764 
8765 			if ((sire != NULL) &&
8766 			    (sire->ire_flags & RTF_MULTIRT)) {
8767 				copy_mp = copymsg(first_mp);
8768 				if (copy_mp != NULL)
8769 					MULTIRT_DEBUG_TAG(copy_mp);
8770 			}
8771 
8772 			ire->ire_marks |= ire_marks;
8773 
8774 			/*
8775 			 * Construct message chain for the resolver
8776 			 * of the form:
8777 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8778 			 * Packet could contain a IPSEC_OUT mp.
8779 			 *
8780 			 * NOTE : ire will be added later when the response
8781 			 * comes back from ARP. If the response does not
8782 			 * come back, ARP frees the packet. For this reason,
8783 			 * we can't REFHOLD the bucket of save_ire to prevent
8784 			 * deletions. We may not be able to REFRELE the bucket
8785 			 * if the response never comes back. Thus, before
8786 			 * adding the ire, ire_add_v4 will make sure that the
8787 			 * interface route does not get deleted. This is the
8788 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8789 			 * where we can always prevent deletions because of
8790 			 * the synchronous nature of adding IRES i.e
8791 			 * ire_add_then_send is called after creating the IRE.
8792 			 */
8793 			ASSERT(ire->ire_mp != NULL);
8794 			ire->ire_mp->b_cont = first_mp;
8795 			/* Have saved_mp handy, for cleanup if canput fails */
8796 			saved_mp = mp;
8797 			mp = copyb(res_mp);
8798 			if (mp == NULL) {
8799 				/* Prepare for cleanup */
8800 				mp = saved_mp; /* pkt */
8801 				ire_delete(ire); /* ire_mp */
8802 				ire = NULL;
8803 				ire_refrele(save_ire);
8804 				if (copy_mp != NULL) {
8805 					MULTIRT_DEBUG_UNTAG(copy_mp);
8806 					freemsg(copy_mp);
8807 					copy_mp = NULL;
8808 				}
8809 				break;
8810 			}
8811 			linkb(mp, ire->ire_mp);
8812 
8813 			/*
8814 			 * Fill in the source and dest addrs for the resolver.
8815 			 * NOTE: this depends on memory layouts imposed by
8816 			 * ill_init().
8817 			 */
8818 			areq = (areq_t *)mp->b_rptr;
8819 			addrp = (ipaddr_t *)((char *)areq +
8820 			    areq->areq_sender_addr_offset);
8821 			*addrp = save_ire->ire_src_addr;
8822 
8823 			ire_refrele(save_ire);
8824 			addrp = (ipaddr_t *)((char *)areq +
8825 			    areq->areq_target_addr_offset);
8826 			*addrp = dst;
8827 			/* Up to the resolver. */
8828 			if (canputnext(dst_ill->ill_rq) &&
8829 			    !(dst_ill->ill_arp_closing)) {
8830 				putnext(dst_ill->ill_rq, mp);
8831 				ire = NULL;
8832 				if (copy_mp != NULL) {
8833 					/*
8834 					 * If we found a resolver, we ignore
8835 					 * any trailing top priority IRE_CACHE
8836 					 * in the further loops. This ensures
8837 					 * that we do not omit any resolver.
8838 					 * IRE_CACHE entries, if any, will be
8839 					 * processed next time we enter
8840 					 * ip_newroute().
8841 					 */
8842 					multirt_flags &= ~MULTIRT_CACHEGW;
8843 					/*
8844 					 * Search for the next unresolved
8845 					 * multirt route.
8846 					 */
8847 					first_mp = copy_mp;
8848 					copy_mp = NULL;
8849 					/* Prepare the next resolution loop. */
8850 					mp = first_mp;
8851 					EXTRACT_PKT_MP(mp, first_mp,
8852 					    mctl_present);
8853 					if (mctl_present)
8854 						io = (ipsec_out_t *)
8855 						    first_mp->b_rptr;
8856 					ipha = (ipha_t *)mp->b_rptr;
8857 
8858 					ASSERT(sire != NULL);
8859 
8860 					dst = save_dst;
8861 					multirt_resolve_next = B_TRUE;
8862 					continue;
8863 				}
8864 
8865 				if (sire != NULL)
8866 					ire_refrele(sire);
8867 
8868 				/*
8869 				 * The response will come back in ip_wput
8870 				 * with db_type IRE_DB_TYPE.
8871 				 */
8872 				ipif_refrele(src_ipif);
8873 				ill_refrele(dst_ill);
8874 				return;
8875 			} else {
8876 				/* Prepare for cleanup */
8877 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8878 				    mp);
8879 				mp->b_cont = NULL;
8880 				freeb(mp); /* areq */
8881 				/*
8882 				 * this is an ire that is not added to the
8883 				 * cache. ire_freemblk will handle the release
8884 				 * of any resources associated with the ire.
8885 				 */
8886 				ire_delete(ire); /* ire_mp */
8887 				mp = saved_mp; /* pkt */
8888 				ire = NULL;
8889 				if (copy_mp != NULL) {
8890 					MULTIRT_DEBUG_UNTAG(copy_mp);
8891 					freemsg(copy_mp);
8892 					copy_mp = NULL;
8893 				}
8894 				break;
8895 			}
8896 		default:
8897 			break;
8898 		}
8899 	} while (multirt_resolve_next);
8900 
8901 	ip1dbg(("ip_newroute: dropped\n"));
8902 	/* Did this packet originate externally? */
8903 	if (mp->b_prev) {
8904 		mp->b_next = NULL;
8905 		mp->b_prev = NULL;
8906 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8907 	} else {
8908 		if (dst_ill != NULL) {
8909 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8910 		} else {
8911 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8912 		}
8913 	}
8914 	ASSERT(copy_mp == NULL);
8915 	MULTIRT_DEBUG_UNTAG(first_mp);
8916 	freemsg(first_mp);
8917 	if (ire != NULL)
8918 		ire_refrele(ire);
8919 	if (sire != NULL)
8920 		ire_refrele(sire);
8921 	if (src_ipif != NULL)
8922 		ipif_refrele(src_ipif);
8923 	if (dst_ill != NULL)
8924 		ill_refrele(dst_ill);
8925 	return;
8926 
8927 icmp_err_ret:
8928 	ip1dbg(("ip_newroute: no route\n"));
8929 	if (src_ipif != NULL)
8930 		ipif_refrele(src_ipif);
8931 	if (dst_ill != NULL)
8932 		ill_refrele(dst_ill);
8933 	if (sire != NULL)
8934 		ire_refrele(sire);
8935 	/* Did this packet originate externally? */
8936 	if (mp->b_prev) {
8937 		mp->b_next = NULL;
8938 		mp->b_prev = NULL;
8939 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8940 		q = WR(q);
8941 	} else {
8942 		/*
8943 		 * There is no outgoing ill, so just increment the
8944 		 * system MIB.
8945 		 */
8946 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8947 		/*
8948 		 * Since ip_wput() isn't close to finished, we fill
8949 		 * in enough of the header for credible error reporting.
8950 		 */
8951 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8952 			/* Failed */
8953 			MULTIRT_DEBUG_UNTAG(first_mp);
8954 			freemsg(first_mp);
8955 			if (ire != NULL)
8956 				ire_refrele(ire);
8957 			return;
8958 		}
8959 	}
8960 
8961 	/*
8962 	 * At this point we will have ire only if RTF_BLACKHOLE
8963 	 * or RTF_REJECT flags are set on the IRE. It will not
8964 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8965 	 */
8966 	if (ire != NULL) {
8967 		if (ire->ire_flags & RTF_BLACKHOLE) {
8968 			ire_refrele(ire);
8969 			MULTIRT_DEBUG_UNTAG(first_mp);
8970 			freemsg(first_mp);
8971 			return;
8972 		}
8973 		ire_refrele(ire);
8974 	}
8975 	if (ip_source_routed(ipha, ipst)) {
8976 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8977 		    zoneid, ipst);
8978 		return;
8979 	}
8980 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8981 }
8982 
8983 ip_opt_info_t zero_info;
8984 
8985 /*
8986  * IPv4 -
8987  * ip_newroute_ipif is called by ip_wput_multicast and
8988  * ip_rput_forward_multicast whenever we need to send
8989  * out a packet to a destination address for which we do not have specific
8990  * routing information. It is used when the packet will be sent out
8991  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8992  * socket option is set or icmp error message wants to go out on a particular
8993  * interface for a unicast packet.
8994  *
8995  * In most cases, the destination address is resolved thanks to the ipif
8996  * intrinsic resolver. However, there are some cases where the call to
8997  * ip_newroute_ipif must take into account the potential presence of
8998  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8999  * that uses the interface. This is specified through flags,
9000  * which can be a combination of:
9001  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9002  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9003  *   and flags. Additionally, the packet source address has to be set to
9004  *   the specified address. The caller is thus expected to set this flag
9005  *   if the packet has no specific source address yet.
9006  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9007  *   flag, the resulting ire will inherit the flag. All unresolved routes
9008  *   to the destination must be explored in the same call to
9009  *   ip_newroute_ipif().
9010  */
9011 static void
9012 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9013     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9014 {
9015 	areq_t	*areq;
9016 	ire_t	*ire = NULL;
9017 	mblk_t	*res_mp;
9018 	ipaddr_t *addrp;
9019 	mblk_t *first_mp;
9020 	ire_t	*save_ire = NULL;
9021 	ipif_t	*src_ipif = NULL;
9022 	ushort_t ire_marks = 0;
9023 	ill_t	*dst_ill = NULL;
9024 	ipha_t *ipha;
9025 	mblk_t	*saved_mp;
9026 	ire_t   *fire = NULL;
9027 	mblk_t  *copy_mp = NULL;
9028 	boolean_t multirt_resolve_next;
9029 	boolean_t unspec_src;
9030 	ipaddr_t ipha_dst;
9031 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9032 
9033 	/*
9034 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9035 	 * here for uniformity
9036 	 */
9037 	ipif_refhold(ipif);
9038 
9039 	/*
9040 	 * This loop is run only once in most cases.
9041 	 * We loop to resolve further routes only when the destination
9042 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9043 	 */
9044 	do {
9045 		if (dst_ill != NULL) {
9046 			ill_refrele(dst_ill);
9047 			dst_ill = NULL;
9048 		}
9049 		if (src_ipif != NULL) {
9050 			ipif_refrele(src_ipif);
9051 			src_ipif = NULL;
9052 		}
9053 		multirt_resolve_next = B_FALSE;
9054 
9055 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9056 		    ipif->ipif_ill->ill_name));
9057 
9058 		first_mp = mp;
9059 		if (DB_TYPE(mp) == M_CTL)
9060 			mp = mp->b_cont;
9061 		ipha = (ipha_t *)mp->b_rptr;
9062 
9063 		/*
9064 		 * Save the packet destination address, we may need it after
9065 		 * the packet has been consumed.
9066 		 */
9067 		ipha_dst = ipha->ipha_dst;
9068 
9069 		/*
9070 		 * If the interface is a pt-pt interface we look for an
9071 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9072 		 * local_address and the pt-pt destination address. Otherwise
9073 		 * we just match the local address.
9074 		 * NOTE: dst could be different than ipha->ipha_dst in case
9075 		 * of sending igmp multicast packets over a point-to-point
9076 		 * connection.
9077 		 * Thus we must be careful enough to check ipha_dst to be a
9078 		 * multicast address, otherwise it will take xmit_if path for
9079 		 * multicast packets resulting into kernel stack overflow by
9080 		 * repeated calls to ip_newroute_ipif from ire_send().
9081 		 */
9082 		if (CLASSD(ipha_dst) &&
9083 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9084 			goto err_ret;
9085 		}
9086 
9087 		/*
9088 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9089 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9090 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9091 		 * propagate its flags to the new ire.
9092 		 */
9093 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9094 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9095 			ip2dbg(("ip_newroute_ipif: "
9096 			    "ipif_lookup_multi_ire("
9097 			    "ipif %p, dst %08x) = fire %p\n",
9098 			    (void *)ipif, ntohl(dst), (void *)fire));
9099 		}
9100 
9101 		/*
9102 		 * Note: While we pick a dst_ill we are really only
9103 		 * interested in the ill for load spreading. The source
9104 		 * ipif is determined by source address selection below.
9105 		 */
9106 		if (IS_IPMP(ipif->ipif_ill)) {
9107 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9108 
9109 			if (CLASSD(ipha_dst))
9110 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9111 			else
9112 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9113 		} else {
9114 			dst_ill = ipif->ipif_ill;
9115 			ill_refhold(dst_ill);
9116 		}
9117 
9118 		if (dst_ill == NULL) {
9119 			if (ip_debug > 2) {
9120 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9121 				    "for dst %s\n", AF_INET, &dst);
9122 			}
9123 			goto err_ret;
9124 		}
9125 
9126 		/*
9127 		 * Pick a source address preferring non-deprecated ones.
9128 		 * Unlike ip_newroute, we don't do any source address
9129 		 * selection here since for multicast it really does not help
9130 		 * in inbound load spreading as in the unicast case.
9131 		 */
9132 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9133 		    (fire->ire_flags & RTF_SETSRC)) {
9134 			/*
9135 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9136 			 * on that interface. This ire has RTF_SETSRC flag, so
9137 			 * the source address of the packet must be changed.
9138 			 * Check that the ipif matching the requested source
9139 			 * address still exists.
9140 			 */
9141 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9142 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9143 		}
9144 
9145 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9146 
9147 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9148 		    (IS_IPMP(ipif->ipif_ill) ||
9149 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9150 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9151 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9152 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9153 		    (src_ipif == NULL) &&
9154 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9155 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9156 			if (src_ipif == NULL) {
9157 				if (ip_debug > 2) {
9158 					/* ip1dbg */
9159 					pr_addr_dbg("ip_newroute_ipif: "
9160 					    "no src for dst %s",
9161 					    AF_INET, &dst);
9162 				}
9163 				ip1dbg((" on interface %s\n",
9164 				    dst_ill->ill_name));
9165 				goto err_ret;
9166 			}
9167 			ipif_refrele(ipif);
9168 			ipif = src_ipif;
9169 			ipif_refhold(ipif);
9170 		}
9171 		if (src_ipif == NULL) {
9172 			src_ipif = ipif;
9173 			ipif_refhold(src_ipif);
9174 		}
9175 
9176 		/*
9177 		 * Assign a source address while we have the conn.
9178 		 * We can't have ip_wput_ire pick a source address when the
9179 		 * packet returns from arp since conn_unspec_src might be set
9180 		 * and we lose the conn when going through arp.
9181 		 */
9182 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9183 			ipha->ipha_src = src_ipif->ipif_src_addr;
9184 
9185 		/*
9186 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9187 		 * that the outgoing interface does not have an interface ire.
9188 		 */
9189 		if (CLASSD(ipha_dst) && (connp == NULL ||
9190 		    connp->conn_outgoing_ill == NULL) &&
9191 		    infop->ip_opt_ill_index == 0) {
9192 			/* ipif_to_ire returns an held ire */
9193 			ire = ipif_to_ire(ipif);
9194 			if (ire == NULL)
9195 				goto err_ret;
9196 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9197 				goto err_ret;
9198 			save_ire = ire;
9199 
9200 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9201 			    "flags %04x\n",
9202 			    (void *)ire, (void *)ipif, flags));
9203 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9204 			    (fire->ire_flags & RTF_MULTIRT)) {
9205 				/*
9206 				 * As requested by flags, an IRE_OFFSUBNET was
9207 				 * looked up on that interface. This ire has
9208 				 * RTF_MULTIRT flag, so the resolution loop will
9209 				 * be re-entered to resolve additional routes on
9210 				 * other interfaces. For that purpose, a copy of
9211 				 * the packet is performed at this point.
9212 				 */
9213 				fire->ire_last_used_time = lbolt;
9214 				copy_mp = copymsg(first_mp);
9215 				if (copy_mp) {
9216 					MULTIRT_DEBUG_TAG(copy_mp);
9217 				}
9218 			}
9219 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9220 			    (fire->ire_flags & RTF_SETSRC)) {
9221 				/*
9222 				 * As requested by flags, an IRE_OFFSUBET was
9223 				 * looked up on that interface. This ire has
9224 				 * RTF_SETSRC flag, so the source address of the
9225 				 * packet must be changed.
9226 				 */
9227 				ipha->ipha_src = fire->ire_src_addr;
9228 			}
9229 		} else {
9230 			/*
9231 			 * The only ways we can come here are:
9232 			 * 1) IP_BOUND_IF socket option is set
9233 			 * 2) SO_DONTROUTE socket option is set
9234 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9235 			 * In all cases, the new ire will not be added
9236 			 * into cache table.
9237 			 */
9238 			ASSERT(connp == NULL || connp->conn_dontroute ||
9239 			    connp->conn_outgoing_ill != NULL ||
9240 			    infop->ip_opt_ill_index != 0);
9241 			ire_marks |= IRE_MARK_NOADD;
9242 		}
9243 
9244 		switch (ipif->ipif_net_type) {
9245 		case IRE_IF_NORESOLVER: {
9246 			/* We have what we need to build an IRE_CACHE. */
9247 
9248 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9249 			    (dst_ill->ill_resolver_mp == NULL)) {
9250 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9251 				    "for IRE_IF_NORESOLVER ire %p has "
9252 				    "no ill_resolver_mp\n",
9253 				    (void *)dst_ill, (void *)ire));
9254 				break;
9255 			}
9256 
9257 			/*
9258 			 * The new ire inherits the IRE_OFFSUBNET flags
9259 			 * and source address, if this was requested.
9260 			 */
9261 			ire = ire_create(
9262 			    (uchar_t *)&dst,		/* dest address */
9263 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9264 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9265 			    NULL,			/* gateway address */
9266 			    &ipif->ipif_mtu,
9267 			    NULL,			/* no src nce */
9268 			    dst_ill->ill_rq,		/* recv-from queue */
9269 			    dst_ill->ill_wq,		/* send-to queue */
9270 			    IRE_CACHE,
9271 			    src_ipif,
9272 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9273 			    (fire != NULL) ?		/* Parent handle */
9274 			    fire->ire_phandle : 0,
9275 			    (save_ire != NULL) ?	/* Interface handle */
9276 			    save_ire->ire_ihandle : 0,
9277 			    (fire != NULL) ?
9278 			    (fire->ire_flags &
9279 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9280 			    (save_ire == NULL ? &ire_uinfo_null :
9281 			    &save_ire->ire_uinfo),
9282 			    NULL,
9283 			    NULL,
9284 			    ipst);
9285 
9286 			if (ire == NULL) {
9287 				if (save_ire != NULL)
9288 					ire_refrele(save_ire);
9289 				break;
9290 			}
9291 
9292 			ire->ire_marks |= ire_marks;
9293 
9294 			/*
9295 			 * If IRE_MARK_NOADD is set then we need to convert
9296 			 * the max_fragp to a useable value now. This is
9297 			 * normally done in ire_add_v[46]. We also need to
9298 			 * associate the ire with an nce (normally would be
9299 			 * done in ip_wput_nondata()).
9300 			 *
9301 			 * Note that IRE_MARK_NOADD packets created here
9302 			 * do not have a non-null ire_mp pointer. The null
9303 			 * value of ire_bucket indicates that they were
9304 			 * never added.
9305 			 */
9306 			if (ire->ire_marks & IRE_MARK_NOADD) {
9307 				uint_t  max_frag;
9308 
9309 				max_frag = *ire->ire_max_fragp;
9310 				ire->ire_max_fragp = NULL;
9311 				ire->ire_max_frag = max_frag;
9312 
9313 				if ((ire->ire_nce = ndp_lookup_v4(
9314 				    ire_to_ill(ire),
9315 				    (ire->ire_gateway_addr != INADDR_ANY ?
9316 				    &ire->ire_gateway_addr : &ire->ire_addr),
9317 				    B_FALSE)) == NULL) {
9318 					if (save_ire != NULL)
9319 						ire_refrele(save_ire);
9320 					break;
9321 				}
9322 				ASSERT(ire->ire_nce->nce_state ==
9323 				    ND_REACHABLE);
9324 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9325 			}
9326 
9327 			/* Prevent save_ire from getting deleted */
9328 			if (save_ire != NULL) {
9329 				IRB_REFHOLD(save_ire->ire_bucket);
9330 				/* Has it been removed already ? */
9331 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9332 					IRB_REFRELE(save_ire->ire_bucket);
9333 					ire_refrele(save_ire);
9334 					break;
9335 				}
9336 			}
9337 
9338 			ire_add_then_send(q, ire, first_mp);
9339 
9340 			/* Assert that save_ire is not deleted yet. */
9341 			if (save_ire != NULL) {
9342 				ASSERT(save_ire->ire_ptpn != NULL);
9343 				IRB_REFRELE(save_ire->ire_bucket);
9344 				ire_refrele(save_ire);
9345 				save_ire = NULL;
9346 			}
9347 			if (fire != NULL) {
9348 				ire_refrele(fire);
9349 				fire = NULL;
9350 			}
9351 
9352 			/*
9353 			 * the resolution loop is re-entered if this
9354 			 * was requested through flags and if we
9355 			 * actually are in a multirouting case.
9356 			 */
9357 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9358 				boolean_t need_resolve =
9359 				    ire_multirt_need_resolve(ipha_dst,
9360 				    msg_getlabel(copy_mp), ipst);
9361 				if (!need_resolve) {
9362 					MULTIRT_DEBUG_UNTAG(copy_mp);
9363 					freemsg(copy_mp);
9364 					copy_mp = NULL;
9365 				} else {
9366 					/*
9367 					 * ipif_lookup_group() calls
9368 					 * ire_lookup_multi() that uses
9369 					 * ire_ftable_lookup() to find
9370 					 * an IRE_INTERFACE for the group.
9371 					 * In the multirt case,
9372 					 * ire_lookup_multi() then invokes
9373 					 * ire_multirt_lookup() to find
9374 					 * the next resolvable ire.
9375 					 * As a result, we obtain an new
9376 					 * interface, derived from the
9377 					 * next ire.
9378 					 */
9379 					ipif_refrele(ipif);
9380 					ipif = ipif_lookup_group(ipha_dst,
9381 					    zoneid, ipst);
9382 					ip2dbg(("ip_newroute_ipif: "
9383 					    "multirt dst %08x, ipif %p\n",
9384 					    htonl(dst), (void *)ipif));
9385 					if (ipif != NULL) {
9386 						mp = copy_mp;
9387 						copy_mp = NULL;
9388 						multirt_resolve_next = B_TRUE;
9389 						continue;
9390 					} else {
9391 						freemsg(copy_mp);
9392 					}
9393 				}
9394 			}
9395 			if (ipif != NULL)
9396 				ipif_refrele(ipif);
9397 			ill_refrele(dst_ill);
9398 			ipif_refrele(src_ipif);
9399 			return;
9400 		}
9401 		case IRE_IF_RESOLVER:
9402 			/*
9403 			 * We can't build an IRE_CACHE yet, but at least
9404 			 * we found a resolver that can help.
9405 			 */
9406 			res_mp = dst_ill->ill_resolver_mp;
9407 			if (!OK_RESOLVER_MP(res_mp))
9408 				break;
9409 
9410 			/*
9411 			 * We obtain a partial IRE_CACHE which we will pass
9412 			 * along with the resolver query.  When the response
9413 			 * comes back it will be there ready for us to add.
9414 			 * The new ire inherits the IRE_OFFSUBNET flags
9415 			 * and source address, if this was requested.
9416 			 * The ire_max_frag is atomically set under the
9417 			 * irebucket lock in ire_add_v[46]. Only in the
9418 			 * case of IRE_MARK_NOADD, we set it here itself.
9419 			 */
9420 			ire = ire_create_mp(
9421 			    (uchar_t *)&dst,		/* dest address */
9422 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9423 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9424 			    NULL,			/* gateway address */
9425 			    (ire_marks & IRE_MARK_NOADD) ?
9426 			    ipif->ipif_mtu : 0,		/* max_frag */
9427 			    NULL,			/* no src nce */
9428 			    dst_ill->ill_rq,		/* recv-from queue */
9429 			    dst_ill->ill_wq,		/* send-to queue */
9430 			    IRE_CACHE,
9431 			    src_ipif,
9432 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9433 			    (fire != NULL) ?		/* Parent handle */
9434 			    fire->ire_phandle : 0,
9435 			    (save_ire != NULL) ?	/* Interface handle */
9436 			    save_ire->ire_ihandle : 0,
9437 			    (fire != NULL) ?		/* flags if any */
9438 			    (fire->ire_flags &
9439 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9440 			    (save_ire == NULL ? &ire_uinfo_null :
9441 			    &save_ire->ire_uinfo),
9442 			    NULL,
9443 			    NULL,
9444 			    ipst);
9445 
9446 			if (save_ire != NULL) {
9447 				ire_refrele(save_ire);
9448 				save_ire = NULL;
9449 			}
9450 			if (ire == NULL)
9451 				break;
9452 
9453 			ire->ire_marks |= ire_marks;
9454 			/*
9455 			 * Construct message chain for the resolver of the
9456 			 * form:
9457 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9458 			 *
9459 			 * NOTE : ire will be added later when the response
9460 			 * comes back from ARP. If the response does not
9461 			 * come back, ARP frees the packet. For this reason,
9462 			 * we can't REFHOLD the bucket of save_ire to prevent
9463 			 * deletions. We may not be able to REFRELE the
9464 			 * bucket if the response never comes back.
9465 			 * Thus, before adding the ire, ire_add_v4 will make
9466 			 * sure that the interface route does not get deleted.
9467 			 * This is the only case unlike ip_newroute_v6,
9468 			 * ip_newroute_ipif_v6 where we can always prevent
9469 			 * deletions because ire_add_then_send is called after
9470 			 * creating the IRE.
9471 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9472 			 * does not add this IRE into the IRE CACHE.
9473 			 */
9474 			ASSERT(ire->ire_mp != NULL);
9475 			ire->ire_mp->b_cont = first_mp;
9476 			/* Have saved_mp handy, for cleanup if canput fails */
9477 			saved_mp = mp;
9478 			mp = copyb(res_mp);
9479 			if (mp == NULL) {
9480 				/* Prepare for cleanup */
9481 				mp = saved_mp; /* pkt */
9482 				ire_delete(ire); /* ire_mp */
9483 				ire = NULL;
9484 				if (copy_mp != NULL) {
9485 					MULTIRT_DEBUG_UNTAG(copy_mp);
9486 					freemsg(copy_mp);
9487 					copy_mp = NULL;
9488 				}
9489 				break;
9490 			}
9491 			linkb(mp, ire->ire_mp);
9492 
9493 			/*
9494 			 * Fill in the source and dest addrs for the resolver.
9495 			 * NOTE: this depends on memory layouts imposed by
9496 			 * ill_init().  There are corner cases above where we
9497 			 * might've created the IRE with an INADDR_ANY source
9498 			 * address (e.g., if the zeroth ipif on an underlying
9499 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9500 			 * on the ill has a usable test address).  If so, tell
9501 			 * ARP to use ipha_src as its sender address.
9502 			 */
9503 			areq = (areq_t *)mp->b_rptr;
9504 			addrp = (ipaddr_t *)((char *)areq +
9505 			    areq->areq_sender_addr_offset);
9506 			if (ire->ire_src_addr != INADDR_ANY)
9507 				*addrp = ire->ire_src_addr;
9508 			else
9509 				*addrp = ipha->ipha_src;
9510 			addrp = (ipaddr_t *)((char *)areq +
9511 			    areq->areq_target_addr_offset);
9512 			*addrp = dst;
9513 			/* Up to the resolver. */
9514 			if (canputnext(dst_ill->ill_rq) &&
9515 			    !(dst_ill->ill_arp_closing)) {
9516 				putnext(dst_ill->ill_rq, mp);
9517 				/*
9518 				 * The response will come back in ip_wput
9519 				 * with db_type IRE_DB_TYPE.
9520 				 */
9521 			} else {
9522 				mp->b_cont = NULL;
9523 				freeb(mp); /* areq */
9524 				ire_delete(ire); /* ire_mp */
9525 				saved_mp->b_next = NULL;
9526 				saved_mp->b_prev = NULL;
9527 				freemsg(first_mp); /* pkt */
9528 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9529 			}
9530 
9531 			if (fire != NULL) {
9532 				ire_refrele(fire);
9533 				fire = NULL;
9534 			}
9535 
9536 			/*
9537 			 * The resolution loop is re-entered if this was
9538 			 * requested through flags and we actually are
9539 			 * in a multirouting case.
9540 			 */
9541 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9542 				boolean_t need_resolve =
9543 				    ire_multirt_need_resolve(ipha_dst,
9544 				    msg_getlabel(copy_mp), ipst);
9545 				if (!need_resolve) {
9546 					MULTIRT_DEBUG_UNTAG(copy_mp);
9547 					freemsg(copy_mp);
9548 					copy_mp = NULL;
9549 				} else {
9550 					/*
9551 					 * ipif_lookup_group() calls
9552 					 * ire_lookup_multi() that uses
9553 					 * ire_ftable_lookup() to find
9554 					 * an IRE_INTERFACE for the group.
9555 					 * In the multirt case,
9556 					 * ire_lookup_multi() then invokes
9557 					 * ire_multirt_lookup() to find
9558 					 * the next resolvable ire.
9559 					 * As a result, we obtain an new
9560 					 * interface, derived from the
9561 					 * next ire.
9562 					 */
9563 					ipif_refrele(ipif);
9564 					ipif = ipif_lookup_group(ipha_dst,
9565 					    zoneid, ipst);
9566 					if (ipif != NULL) {
9567 						mp = copy_mp;
9568 						copy_mp = NULL;
9569 						multirt_resolve_next = B_TRUE;
9570 						continue;
9571 					} else {
9572 						freemsg(copy_mp);
9573 					}
9574 				}
9575 			}
9576 			if (ipif != NULL)
9577 				ipif_refrele(ipif);
9578 			ill_refrele(dst_ill);
9579 			ipif_refrele(src_ipif);
9580 			return;
9581 		default:
9582 			break;
9583 		}
9584 	} while (multirt_resolve_next);
9585 
9586 err_ret:
9587 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9588 	if (fire != NULL)
9589 		ire_refrele(fire);
9590 	ipif_refrele(ipif);
9591 	/* Did this packet originate externally? */
9592 	if (dst_ill != NULL)
9593 		ill_refrele(dst_ill);
9594 	if (src_ipif != NULL)
9595 		ipif_refrele(src_ipif);
9596 	if (mp->b_prev || mp->b_next) {
9597 		mp->b_next = NULL;
9598 		mp->b_prev = NULL;
9599 	} else {
9600 		/*
9601 		 * Since ip_wput() isn't close to finished, we fill
9602 		 * in enough of the header for credible error reporting.
9603 		 */
9604 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9605 			/* Failed */
9606 			freemsg(first_mp);
9607 			if (ire != NULL)
9608 				ire_refrele(ire);
9609 			return;
9610 		}
9611 	}
9612 	/*
9613 	 * At this point we will have ire only if RTF_BLACKHOLE
9614 	 * or RTF_REJECT flags are set on the IRE. It will not
9615 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9616 	 */
9617 	if (ire != NULL) {
9618 		if (ire->ire_flags & RTF_BLACKHOLE) {
9619 			ire_refrele(ire);
9620 			freemsg(first_mp);
9621 			return;
9622 		}
9623 		ire_refrele(ire);
9624 	}
9625 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9626 }
9627 
9628 /* Name/Value Table Lookup Routine */
9629 char *
9630 ip_nv_lookup(nv_t *nv, int value)
9631 {
9632 	if (!nv)
9633 		return (NULL);
9634 	for (; nv->nv_name; nv++) {
9635 		if (nv->nv_value == value)
9636 			return (nv->nv_name);
9637 	}
9638 	return ("unknown");
9639 }
9640 
9641 /*
9642  * This is a module open, i.e. this is a control stream for access
9643  * to a DLPI device.  We allocate an ill_t as the instance data in
9644  * this case.
9645  */
9646 int
9647 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9648 {
9649 	ill_t	*ill;
9650 	int	err;
9651 	zoneid_t zoneid;
9652 	netstack_t *ns;
9653 	ip_stack_t *ipst;
9654 
9655 	/*
9656 	 * Prevent unprivileged processes from pushing IP so that
9657 	 * they can't send raw IP.
9658 	 */
9659 	if (secpolicy_net_rawaccess(credp) != 0)
9660 		return (EPERM);
9661 
9662 	ns = netstack_find_by_cred(credp);
9663 	ASSERT(ns != NULL);
9664 	ipst = ns->netstack_ip;
9665 	ASSERT(ipst != NULL);
9666 
9667 	/*
9668 	 * For exclusive stacks we set the zoneid to zero
9669 	 * to make IP operate as if in the global zone.
9670 	 */
9671 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9672 		zoneid = GLOBAL_ZONEID;
9673 	else
9674 		zoneid = crgetzoneid(credp);
9675 
9676 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9677 	q->q_ptr = WR(q)->q_ptr = ill;
9678 	ill->ill_ipst = ipst;
9679 	ill->ill_zoneid = zoneid;
9680 
9681 	/*
9682 	 * ill_init initializes the ill fields and then sends down
9683 	 * down a DL_INFO_REQ after calling qprocson.
9684 	 */
9685 	err = ill_init(q, ill);
9686 	if (err != 0) {
9687 		mi_free(ill);
9688 		netstack_rele(ipst->ips_netstack);
9689 		q->q_ptr = NULL;
9690 		WR(q)->q_ptr = NULL;
9691 		return (err);
9692 	}
9693 
9694 	/* ill_init initializes the ipsq marking this thread as writer */
9695 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9696 	/* Wait for the DL_INFO_ACK */
9697 	mutex_enter(&ill->ill_lock);
9698 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9699 		/*
9700 		 * Return value of 0 indicates a pending signal.
9701 		 */
9702 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9703 		if (err == 0) {
9704 			mutex_exit(&ill->ill_lock);
9705 			(void) ip_close(q, 0);
9706 			return (EINTR);
9707 		}
9708 	}
9709 	mutex_exit(&ill->ill_lock);
9710 
9711 	/*
9712 	 * ip_rput_other could have set an error  in ill_error on
9713 	 * receipt of M_ERROR.
9714 	 */
9715 
9716 	err = ill->ill_error;
9717 	if (err != 0) {
9718 		(void) ip_close(q, 0);
9719 		return (err);
9720 	}
9721 
9722 	ill->ill_credp = credp;
9723 	crhold(credp);
9724 
9725 	mutex_enter(&ipst->ips_ip_mi_lock);
9726 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9727 	    credp);
9728 	mutex_exit(&ipst->ips_ip_mi_lock);
9729 	if (err) {
9730 		(void) ip_close(q, 0);
9731 		return (err);
9732 	}
9733 	return (0);
9734 }
9735 
9736 /* For /dev/ip aka AF_INET open */
9737 int
9738 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9739 {
9740 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9741 }
9742 
9743 /* For /dev/ip6 aka AF_INET6 open */
9744 int
9745 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9746 {
9747 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9748 }
9749 
9750 /* IP open routine. */
9751 int
9752 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9753     boolean_t isv6)
9754 {
9755 	conn_t 		*connp;
9756 	major_t		maj;
9757 	zoneid_t	zoneid;
9758 	netstack_t	*ns;
9759 	ip_stack_t	*ipst;
9760 
9761 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9762 
9763 	/* Allow reopen. */
9764 	if (q->q_ptr != NULL)
9765 		return (0);
9766 
9767 	if (sflag & MODOPEN) {
9768 		/* This is a module open */
9769 		return (ip_modopen(q, devp, flag, sflag, credp));
9770 	}
9771 
9772 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9773 		/*
9774 		 * Non streams based socket looking for a stream
9775 		 * to access IP
9776 		 */
9777 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9778 		    credp, isv6));
9779 	}
9780 
9781 	ns = netstack_find_by_cred(credp);
9782 	ASSERT(ns != NULL);
9783 	ipst = ns->netstack_ip;
9784 	ASSERT(ipst != NULL);
9785 
9786 	/*
9787 	 * For exclusive stacks we set the zoneid to zero
9788 	 * to make IP operate as if in the global zone.
9789 	 */
9790 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9791 		zoneid = GLOBAL_ZONEID;
9792 	else
9793 		zoneid = crgetzoneid(credp);
9794 
9795 	/*
9796 	 * We are opening as a device. This is an IP client stream, and we
9797 	 * allocate an conn_t as the instance data.
9798 	 */
9799 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9800 
9801 	/*
9802 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9803 	 * done by netstack_find_by_cred()
9804 	 */
9805 	netstack_rele(ipst->ips_netstack);
9806 
9807 	connp->conn_zoneid = zoneid;
9808 	connp->conn_sqp = NULL;
9809 	connp->conn_initial_sqp = NULL;
9810 	connp->conn_final_sqp = NULL;
9811 
9812 	connp->conn_upq = q;
9813 	q->q_ptr = WR(q)->q_ptr = connp;
9814 
9815 	if (flag & SO_SOCKSTR)
9816 		connp->conn_flags |= IPCL_SOCKET;
9817 
9818 	/* Minor tells us which /dev entry was opened */
9819 	if (isv6) {
9820 		connp->conn_flags |= IPCL_ISV6;
9821 		connp->conn_af_isv6 = B_TRUE;
9822 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9823 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9824 	} else {
9825 		connp->conn_af_isv6 = B_FALSE;
9826 		connp->conn_pkt_isv6 = B_FALSE;
9827 	}
9828 
9829 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9830 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9831 		connp->conn_minor_arena = ip_minor_arena_la;
9832 	} else {
9833 		/*
9834 		 * Either minor numbers in the large arena were exhausted
9835 		 * or a non socket application is doing the open.
9836 		 * Try to allocate from the small arena.
9837 		 */
9838 		if ((connp->conn_dev =
9839 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9840 			/* CONN_DEC_REF takes care of netstack_rele() */
9841 			q->q_ptr = WR(q)->q_ptr = NULL;
9842 			CONN_DEC_REF(connp);
9843 			return (EBUSY);
9844 		}
9845 		connp->conn_minor_arena = ip_minor_arena_sa;
9846 	}
9847 
9848 	maj = getemajor(*devp);
9849 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9850 
9851 	/*
9852 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9853 	 */
9854 	connp->conn_cred = credp;
9855 
9856 	/*
9857 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9858 	 */
9859 	connp->conn_recv = ip_conn_input;
9860 
9861 	crhold(connp->conn_cred);
9862 
9863 	/*
9864 	 * If the caller has the process-wide flag set, then default to MAC
9865 	 * exempt mode.  This allows read-down to unlabeled hosts.
9866 	 */
9867 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9868 		connp->conn_mac_exempt = B_TRUE;
9869 
9870 	connp->conn_rq = q;
9871 	connp->conn_wq = WR(q);
9872 
9873 	/* Non-zero default values */
9874 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9875 
9876 	/*
9877 	 * Make the conn globally visible to walkers
9878 	 */
9879 	ASSERT(connp->conn_ref == 1);
9880 	mutex_enter(&connp->conn_lock);
9881 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9882 	mutex_exit(&connp->conn_lock);
9883 
9884 	qprocson(q);
9885 
9886 	return (0);
9887 }
9888 
9889 /*
9890  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9891  * Note that there is no race since either ip_output function works - it
9892  * is just an optimization to enter the best ip_output routine directly.
9893  */
9894 void
9895 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9896     ip_stack_t *ipst)
9897 {
9898 	if (isv6)  {
9899 		if (bump_mib) {
9900 			BUMP_MIB(&ipst->ips_ip6_mib,
9901 			    ipIfStatsOutSwitchIPVersion);
9902 		}
9903 		connp->conn_send = ip_output_v6;
9904 		connp->conn_pkt_isv6 = B_TRUE;
9905 	} else {
9906 		if (bump_mib) {
9907 			BUMP_MIB(&ipst->ips_ip_mib,
9908 			    ipIfStatsOutSwitchIPVersion);
9909 		}
9910 		connp->conn_send = ip_output;
9911 		connp->conn_pkt_isv6 = B_FALSE;
9912 	}
9913 
9914 }
9915 
9916 /*
9917  * See if IPsec needs loading because of the options in mp.
9918  */
9919 static boolean_t
9920 ipsec_opt_present(mblk_t *mp)
9921 {
9922 	uint8_t *optcp, *next_optcp, *opt_endcp;
9923 	struct opthdr *opt;
9924 	struct T_opthdr *topt;
9925 	int opthdr_len;
9926 	t_uscalar_t optname, optlevel;
9927 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9928 	ipsec_req_t *ipsr;
9929 
9930 	/*
9931 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9932 	 * return TRUE.
9933 	 */
9934 
9935 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9936 	opt_endcp = optcp + tor->OPT_length;
9937 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9938 		opthdr_len = sizeof (struct T_opthdr);
9939 	} else {		/* O_OPTMGMT_REQ */
9940 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9941 		opthdr_len = sizeof (struct opthdr);
9942 	}
9943 	for (; optcp < opt_endcp; optcp = next_optcp) {
9944 		if (optcp + opthdr_len > opt_endcp)
9945 			return (B_FALSE);	/* Not enough option header. */
9946 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9947 			topt = (struct T_opthdr *)optcp;
9948 			optlevel = topt->level;
9949 			optname = topt->name;
9950 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9951 		} else {
9952 			opt = (struct opthdr *)optcp;
9953 			optlevel = opt->level;
9954 			optname = opt->name;
9955 			next_optcp = optcp + opthdr_len +
9956 			    _TPI_ALIGN_OPT(opt->len);
9957 		}
9958 		if ((next_optcp < optcp) || /* wraparound pointer space */
9959 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9960 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9961 			return (B_FALSE); /* bad option buffer */
9962 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9963 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9964 			/*
9965 			 * Check to see if it's an all-bypass or all-zeroes
9966 			 * IPsec request.  Don't bother loading IPsec if
9967 			 * the socket doesn't want to use it.  (A good example
9968 			 * is a bypass request.)
9969 			 *
9970 			 * Basically, if any of the non-NEVER bits are set,
9971 			 * load IPsec.
9972 			 */
9973 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9974 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9975 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9976 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9977 			    != 0)
9978 				return (B_TRUE);
9979 		}
9980 	}
9981 	return (B_FALSE);
9982 }
9983 
9984 /*
9985  * If conn is is waiting for ipsec to finish loading, kick it.
9986  */
9987 /* ARGSUSED */
9988 static void
9989 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9990 {
9991 	t_scalar_t	optreq_prim;
9992 	mblk_t		*mp;
9993 	cred_t		*cr;
9994 	int		err = 0;
9995 
9996 	/*
9997 	 * This function is called, after ipsec loading is complete.
9998 	 * Since IP checks exclusively and atomically (i.e it prevents
9999 	 * ipsec load from completing until ip_optcom_req completes)
10000 	 * whether ipsec load is complete, there cannot be a race with IP
10001 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10002 	 */
10003 	mutex_enter(&connp->conn_lock);
10004 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10005 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10006 		mp = connp->conn_ipsec_opt_mp;
10007 		connp->conn_ipsec_opt_mp = NULL;
10008 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10009 		mutex_exit(&connp->conn_lock);
10010 
10011 		/*
10012 		 * All Solaris components should pass a db_credp
10013 		 * for this TPI message, hence we ASSERT.
10014 		 * But in case there is some other M_PROTO that looks
10015 		 * like a TPI message sent by some other kernel
10016 		 * component, we check and return an error.
10017 		 */
10018 		cr = msg_getcred(mp, NULL);
10019 		ASSERT(cr != NULL);
10020 		if (cr == NULL) {
10021 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
10022 			if (mp != NULL)
10023 				qreply(connp->conn_wq, mp);
10024 			return;
10025 		}
10026 
10027 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10028 
10029 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10030 		if (optreq_prim == T_OPTMGMT_REQ) {
10031 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10032 			    &ip_opt_obj, B_FALSE);
10033 		} else {
10034 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10035 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10036 			    &ip_opt_obj, B_FALSE);
10037 		}
10038 		if (err != EINPROGRESS)
10039 			CONN_OPER_PENDING_DONE(connp);
10040 		return;
10041 	}
10042 	mutex_exit(&connp->conn_lock);
10043 }
10044 
10045 /*
10046  * Called from the ipsec_loader thread, outside any perimeter, to tell
10047  * ip qenable any of the queues waiting for the ipsec loader to
10048  * complete.
10049  */
10050 void
10051 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10052 {
10053 	netstack_t *ns = ipss->ipsec_netstack;
10054 
10055 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10056 }
10057 
10058 /*
10059  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10060  * determines the grp on which it has to become exclusive, queues the mp
10061  * and IPSQ draining restarts the optmgmt
10062  */
10063 static boolean_t
10064 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10065 {
10066 	conn_t *connp = Q_TO_CONN(q);
10067 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10068 
10069 	/*
10070 	 * Take IPsec requests and treat them special.
10071 	 */
10072 	if (ipsec_opt_present(mp)) {
10073 		/* First check if IPsec is loaded. */
10074 		mutex_enter(&ipss->ipsec_loader_lock);
10075 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10076 			mutex_exit(&ipss->ipsec_loader_lock);
10077 			return (B_FALSE);
10078 		}
10079 		mutex_enter(&connp->conn_lock);
10080 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10081 
10082 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10083 		connp->conn_ipsec_opt_mp = mp;
10084 		mutex_exit(&connp->conn_lock);
10085 		mutex_exit(&ipss->ipsec_loader_lock);
10086 
10087 		ipsec_loader_loadnow(ipss);
10088 		return (B_TRUE);
10089 	}
10090 	return (B_FALSE);
10091 }
10092 
10093 /*
10094  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10095  * all of them are copied to the conn_t. If the req is "zero", the policy is
10096  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10097  * fields.
10098  * We keep only the latest setting of the policy and thus policy setting
10099  * is not incremental/cumulative.
10100  *
10101  * Requests to set policies with multiple alternative actions will
10102  * go through a different API.
10103  */
10104 int
10105 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10106 {
10107 	uint_t ah_req = 0;
10108 	uint_t esp_req = 0;
10109 	uint_t se_req = 0;
10110 	ipsec_selkey_t sel;
10111 	ipsec_act_t *actp = NULL;
10112 	uint_t nact;
10113 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10114 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10115 	ipsec_policy_root_t *pr;
10116 	ipsec_policy_head_t *ph;
10117 	int fam;
10118 	boolean_t is_pol_reset;
10119 	int error = 0;
10120 	netstack_t	*ns = connp->conn_netstack;
10121 	ip_stack_t	*ipst = ns->netstack_ip;
10122 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10123 
10124 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10125 
10126 	/*
10127 	 * The IP_SEC_OPT option does not allow variable length parameters,
10128 	 * hence a request cannot be NULL.
10129 	 */
10130 	if (req == NULL)
10131 		return (EINVAL);
10132 
10133 	ah_req = req->ipsr_ah_req;
10134 	esp_req = req->ipsr_esp_req;
10135 	se_req = req->ipsr_self_encap_req;
10136 
10137 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10138 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10139 		return (EINVAL);
10140 
10141 	/*
10142 	 * Are we dealing with a request to reset the policy (i.e.
10143 	 * zero requests).
10144 	 */
10145 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10146 	    (esp_req & REQ_MASK) == 0 &&
10147 	    (se_req & REQ_MASK) == 0);
10148 
10149 	if (!is_pol_reset) {
10150 		/*
10151 		 * If we couldn't load IPsec, fail with "protocol
10152 		 * not supported".
10153 		 * IPsec may not have been loaded for a request with zero
10154 		 * policies, so we don't fail in this case.
10155 		 */
10156 		mutex_enter(&ipss->ipsec_loader_lock);
10157 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10158 			mutex_exit(&ipss->ipsec_loader_lock);
10159 			return (EPROTONOSUPPORT);
10160 		}
10161 		mutex_exit(&ipss->ipsec_loader_lock);
10162 
10163 		/*
10164 		 * Test for valid requests. Invalid algorithms
10165 		 * need to be tested by IPsec code because new
10166 		 * algorithms can be added dynamically.
10167 		 */
10168 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10169 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10170 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10171 			return (EINVAL);
10172 		}
10173 
10174 		/*
10175 		 * Only privileged users can issue these
10176 		 * requests.
10177 		 */
10178 		if (((ah_req & IPSEC_PREF_NEVER) ||
10179 		    (esp_req & IPSEC_PREF_NEVER) ||
10180 		    (se_req & IPSEC_PREF_NEVER)) &&
10181 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10182 			return (EPERM);
10183 		}
10184 
10185 		/*
10186 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10187 		 * are mutually exclusive.
10188 		 */
10189 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10190 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10191 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10192 			/* Both of them are set */
10193 			return (EINVAL);
10194 		}
10195 	}
10196 
10197 	mutex_enter(&connp->conn_lock);
10198 
10199 	/*
10200 	 * If we have already cached policies in ip_bind_connected*(), don't
10201 	 * let them change now. We cache policies for connections
10202 	 * whose src,dst [addr, port] is known.
10203 	 */
10204 	if (connp->conn_policy_cached) {
10205 		mutex_exit(&connp->conn_lock);
10206 		return (EINVAL);
10207 	}
10208 
10209 	/*
10210 	 * We have a zero policies, reset the connection policy if already
10211 	 * set. This will cause the connection to inherit the
10212 	 * global policy, if any.
10213 	 */
10214 	if (is_pol_reset) {
10215 		if (connp->conn_policy != NULL) {
10216 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10217 			connp->conn_policy = NULL;
10218 		}
10219 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10220 		connp->conn_in_enforce_policy = B_FALSE;
10221 		connp->conn_out_enforce_policy = B_FALSE;
10222 		mutex_exit(&connp->conn_lock);
10223 		return (0);
10224 	}
10225 
10226 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10227 	    ipst->ips_netstack);
10228 	if (ph == NULL)
10229 		goto enomem;
10230 
10231 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10232 	if (actp == NULL)
10233 		goto enomem;
10234 
10235 	/*
10236 	 * Always allocate IPv4 policy entries, since they can also
10237 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10238 	 */
10239 	bzero(&sel, sizeof (sel));
10240 	sel.ipsl_valid = IPSL_IPV4;
10241 
10242 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10243 	    ipst->ips_netstack);
10244 	if (pin4 == NULL)
10245 		goto enomem;
10246 
10247 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10248 	    ipst->ips_netstack);
10249 	if (pout4 == NULL)
10250 		goto enomem;
10251 
10252 	if (connp->conn_af_isv6) {
10253 		/*
10254 		 * We're looking at a v6 socket, also allocate the
10255 		 * v6-specific entries...
10256 		 */
10257 		sel.ipsl_valid = IPSL_IPV6;
10258 		pin6 = ipsec_policy_create(&sel, actp, nact,
10259 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10260 		if (pin6 == NULL)
10261 			goto enomem;
10262 
10263 		pout6 = ipsec_policy_create(&sel, actp, nact,
10264 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10265 		if (pout6 == NULL)
10266 			goto enomem;
10267 
10268 		/*
10269 		 * .. and file them away in the right place.
10270 		 */
10271 		fam = IPSEC_AF_V6;
10272 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10273 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10274 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10275 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10276 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10277 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10278 	}
10279 
10280 	ipsec_actvec_free(actp, nact);
10281 
10282 	/*
10283 	 * File the v4 policies.
10284 	 */
10285 	fam = IPSEC_AF_V4;
10286 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10287 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10288 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10289 
10290 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10291 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10292 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10293 
10294 	/*
10295 	 * If the requests need security, set enforce_policy.
10296 	 * If the requests are IPSEC_PREF_NEVER, one should
10297 	 * still set conn_out_enforce_policy so that an ipsec_out
10298 	 * gets attached in ip_wput. This is needed so that
10299 	 * for connections that we don't cache policy in ip_bind,
10300 	 * if global policy matches in ip_wput_attach_policy, we
10301 	 * don't wrongly inherit global policy. Similarly, we need
10302 	 * to set conn_in_enforce_policy also so that we don't verify
10303 	 * policy wrongly.
10304 	 */
10305 	if ((ah_req & REQ_MASK) != 0 ||
10306 	    (esp_req & REQ_MASK) != 0 ||
10307 	    (se_req & REQ_MASK) != 0) {
10308 		connp->conn_in_enforce_policy = B_TRUE;
10309 		connp->conn_out_enforce_policy = B_TRUE;
10310 		connp->conn_flags |= IPCL_CHECK_POLICY;
10311 	}
10312 
10313 	mutex_exit(&connp->conn_lock);
10314 	return (error);
10315 #undef REQ_MASK
10316 
10317 	/*
10318 	 * Common memory-allocation-failure exit path.
10319 	 */
10320 enomem:
10321 	mutex_exit(&connp->conn_lock);
10322 	if (actp != NULL)
10323 		ipsec_actvec_free(actp, nact);
10324 	if (pin4 != NULL)
10325 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10326 	if (pout4 != NULL)
10327 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10328 	if (pin6 != NULL)
10329 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10330 	if (pout6 != NULL)
10331 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10332 	return (ENOMEM);
10333 }
10334 
10335 /*
10336  * Only for options that pass in an IP addr. Currently only V4 options
10337  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10338  * So this function assumes level is IPPROTO_IP
10339  */
10340 int
10341 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10342     mblk_t *first_mp)
10343 {
10344 	ipif_t *ipif = NULL;
10345 	int error;
10346 	ill_t *ill;
10347 	int zoneid;
10348 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10349 
10350 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10351 
10352 	if (addr != INADDR_ANY || checkonly) {
10353 		ASSERT(connp != NULL);
10354 		zoneid = IPCL_ZONEID(connp);
10355 		if (option == IP_NEXTHOP) {
10356 			ipif = ipif_lookup_onlink_addr(addr,
10357 			    connp->conn_zoneid, ipst);
10358 		} else {
10359 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10360 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10361 			    &error, ipst);
10362 		}
10363 		if (ipif == NULL) {
10364 			if (error == EINPROGRESS)
10365 				return (error);
10366 			if ((option == IP_MULTICAST_IF) ||
10367 			    (option == IP_NEXTHOP))
10368 				return (EHOSTUNREACH);
10369 			else
10370 				return (EINVAL);
10371 		} else if (checkonly) {
10372 			if (option == IP_MULTICAST_IF) {
10373 				ill = ipif->ipif_ill;
10374 				/* not supported by the virtual network iface */
10375 				if (IS_VNI(ill)) {
10376 					ipif_refrele(ipif);
10377 					return (EINVAL);
10378 				}
10379 			}
10380 			ipif_refrele(ipif);
10381 			return (0);
10382 		}
10383 		ill = ipif->ipif_ill;
10384 		mutex_enter(&connp->conn_lock);
10385 		mutex_enter(&ill->ill_lock);
10386 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10387 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10388 			mutex_exit(&ill->ill_lock);
10389 			mutex_exit(&connp->conn_lock);
10390 			ipif_refrele(ipif);
10391 			return (option == IP_MULTICAST_IF ?
10392 			    EHOSTUNREACH : EINVAL);
10393 		}
10394 	} else {
10395 		mutex_enter(&connp->conn_lock);
10396 	}
10397 
10398 	/* None of the options below are supported on the VNI */
10399 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10400 		mutex_exit(&ill->ill_lock);
10401 		mutex_exit(&connp->conn_lock);
10402 		ipif_refrele(ipif);
10403 		return (EINVAL);
10404 	}
10405 
10406 	switch (option) {
10407 	case IP_MULTICAST_IF:
10408 		connp->conn_multicast_ipif = ipif;
10409 		break;
10410 	case IP_NEXTHOP:
10411 		connp->conn_nexthop_v4 = addr;
10412 		connp->conn_nexthop_set = B_TRUE;
10413 		break;
10414 	}
10415 
10416 	if (ipif != NULL) {
10417 		mutex_exit(&ill->ill_lock);
10418 		mutex_exit(&connp->conn_lock);
10419 		ipif_refrele(ipif);
10420 		return (0);
10421 	}
10422 	mutex_exit(&connp->conn_lock);
10423 	/* We succeded in cleared the option */
10424 	return (0);
10425 }
10426 
10427 /*
10428  * For options that pass in an ifindex specifying the ill. V6 options always
10429  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10430  */
10431 int
10432 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10433     int level, int option, mblk_t *first_mp)
10434 {
10435 	ill_t *ill = NULL;
10436 	int error = 0;
10437 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10438 
10439 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10440 	if (ifindex != 0) {
10441 		ASSERT(connp != NULL);
10442 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10443 		    first_mp, ip_restart_optmgmt, &error, ipst);
10444 		if (ill != NULL) {
10445 			if (checkonly) {
10446 				/* not supported by the virtual network iface */
10447 				if (IS_VNI(ill)) {
10448 					ill_refrele(ill);
10449 					return (EINVAL);
10450 				}
10451 				ill_refrele(ill);
10452 				return (0);
10453 			}
10454 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10455 			    0, NULL)) {
10456 				ill_refrele(ill);
10457 				ill = NULL;
10458 				mutex_enter(&connp->conn_lock);
10459 				goto setit;
10460 			}
10461 			mutex_enter(&connp->conn_lock);
10462 			mutex_enter(&ill->ill_lock);
10463 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10464 				mutex_exit(&ill->ill_lock);
10465 				mutex_exit(&connp->conn_lock);
10466 				ill_refrele(ill);
10467 				ill = NULL;
10468 				mutex_enter(&connp->conn_lock);
10469 			}
10470 			goto setit;
10471 		} else if (error == EINPROGRESS) {
10472 			return (error);
10473 		} else {
10474 			error = 0;
10475 		}
10476 	}
10477 	mutex_enter(&connp->conn_lock);
10478 setit:
10479 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10480 
10481 	/*
10482 	 * The options below assume that the ILL (if any) transmits and/or
10483 	 * receives traffic. Neither of which is true for the virtual network
10484 	 * interface, so fail setting these on a VNI.
10485 	 */
10486 	if (IS_VNI(ill)) {
10487 		ASSERT(ill != NULL);
10488 		mutex_exit(&ill->ill_lock);
10489 		mutex_exit(&connp->conn_lock);
10490 		ill_refrele(ill);
10491 		return (EINVAL);
10492 	}
10493 
10494 	if (level == IPPROTO_IP) {
10495 		switch (option) {
10496 		case IP_BOUND_IF:
10497 			connp->conn_incoming_ill = ill;
10498 			connp->conn_outgoing_ill = ill;
10499 			break;
10500 
10501 		case IP_MULTICAST_IF:
10502 			/*
10503 			 * This option is an internal special. The socket
10504 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10505 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10506 			 * specifies an ifindex and we try first on V6 ill's.
10507 			 * If we don't find one, we they try using on v4 ill's
10508 			 * intenally and we come here.
10509 			 */
10510 			if (!checkonly && ill != NULL) {
10511 				ipif_t	*ipif;
10512 				ipif = ill->ill_ipif;
10513 
10514 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10515 					mutex_exit(&ill->ill_lock);
10516 					mutex_exit(&connp->conn_lock);
10517 					ill_refrele(ill);
10518 					ill = NULL;
10519 					mutex_enter(&connp->conn_lock);
10520 				} else {
10521 					connp->conn_multicast_ipif = ipif;
10522 				}
10523 			}
10524 			break;
10525 
10526 		case IP_DHCPINIT_IF:
10527 			if (connp->conn_dhcpinit_ill != NULL) {
10528 				/*
10529 				 * We've locked the conn so conn_cleanup_ill()
10530 				 * cannot clear conn_dhcpinit_ill -- so it's
10531 				 * safe to access the ill.
10532 				 */
10533 				ill_t *oill = connp->conn_dhcpinit_ill;
10534 
10535 				ASSERT(oill->ill_dhcpinit != 0);
10536 				atomic_dec_32(&oill->ill_dhcpinit);
10537 				connp->conn_dhcpinit_ill = NULL;
10538 			}
10539 
10540 			if (ill != NULL) {
10541 				connp->conn_dhcpinit_ill = ill;
10542 				atomic_inc_32(&ill->ill_dhcpinit);
10543 			}
10544 			break;
10545 		}
10546 	} else {
10547 		switch (option) {
10548 		case IPV6_BOUND_IF:
10549 			connp->conn_incoming_ill = ill;
10550 			connp->conn_outgoing_ill = ill;
10551 			break;
10552 
10553 		case IPV6_MULTICAST_IF:
10554 			/*
10555 			 * Set conn_multicast_ill to be the IPv6 ill.
10556 			 * Set conn_multicast_ipif to be an IPv4 ipif
10557 			 * for ifindex to make IPv4 mapped addresses
10558 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10559 			 * Even if no IPv6 ill exists for the ifindex
10560 			 * we need to check for an IPv4 ifindex in order
10561 			 * for this to work with mapped addresses. In that
10562 			 * case only set conn_multicast_ipif.
10563 			 */
10564 			if (!checkonly) {
10565 				if (ifindex == 0) {
10566 					connp->conn_multicast_ill = NULL;
10567 					connp->conn_multicast_ipif = NULL;
10568 				} else if (ill != NULL) {
10569 					connp->conn_multicast_ill = ill;
10570 				}
10571 			}
10572 			break;
10573 		}
10574 	}
10575 
10576 	if (ill != NULL) {
10577 		mutex_exit(&ill->ill_lock);
10578 		mutex_exit(&connp->conn_lock);
10579 		ill_refrele(ill);
10580 		return (0);
10581 	}
10582 	mutex_exit(&connp->conn_lock);
10583 	/*
10584 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10585 	 * locate the ill and could not set the option (ifindex != 0)
10586 	 */
10587 	return (ifindex == 0 ? 0 : EINVAL);
10588 }
10589 
10590 /* This routine sets socket options. */
10591 /* ARGSUSED */
10592 int
10593 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10594     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10595     void *dummy, cred_t *cr, mblk_t *first_mp)
10596 {
10597 	int		*i1 = (int *)invalp;
10598 	conn_t		*connp = Q_TO_CONN(q);
10599 	int		error = 0;
10600 	boolean_t	checkonly;
10601 	ire_t		*ire;
10602 	boolean_t	found;
10603 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10604 
10605 	switch (optset_context) {
10606 
10607 	case SETFN_OPTCOM_CHECKONLY:
10608 		checkonly = B_TRUE;
10609 		/*
10610 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10611 		 * inlen != 0 implies value supplied and
10612 		 * 	we have to "pretend" to set it.
10613 		 * inlen == 0 implies that there is no
10614 		 * 	value part in T_CHECK request and just validation
10615 		 * done elsewhere should be enough, we just return here.
10616 		 */
10617 		if (inlen == 0) {
10618 			*outlenp = 0;
10619 			return (0);
10620 		}
10621 		break;
10622 	case SETFN_OPTCOM_NEGOTIATE:
10623 	case SETFN_UD_NEGOTIATE:
10624 	case SETFN_CONN_NEGOTIATE:
10625 		checkonly = B_FALSE;
10626 		break;
10627 	default:
10628 		/*
10629 		 * We should never get here
10630 		 */
10631 		*outlenp = 0;
10632 		return (EINVAL);
10633 	}
10634 
10635 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10636 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10637 
10638 	/*
10639 	 * For fixed length options, no sanity check
10640 	 * of passed in length is done. It is assumed *_optcom_req()
10641 	 * routines do the right thing.
10642 	 */
10643 
10644 	switch (level) {
10645 	case SOL_SOCKET:
10646 		/*
10647 		 * conn_lock protects the bitfields, and is used to
10648 		 * set the fields atomically.
10649 		 */
10650 		switch (name) {
10651 		case SO_BROADCAST:
10652 			if (!checkonly) {
10653 				/* TODO: use value someplace? */
10654 				mutex_enter(&connp->conn_lock);
10655 				connp->conn_broadcast = *i1 ? 1 : 0;
10656 				mutex_exit(&connp->conn_lock);
10657 			}
10658 			break;	/* goto sizeof (int) option return */
10659 		case SO_USELOOPBACK:
10660 			if (!checkonly) {
10661 				/* TODO: use value someplace? */
10662 				mutex_enter(&connp->conn_lock);
10663 				connp->conn_loopback = *i1 ? 1 : 0;
10664 				mutex_exit(&connp->conn_lock);
10665 			}
10666 			break;	/* goto sizeof (int) option return */
10667 		case SO_DONTROUTE:
10668 			if (!checkonly) {
10669 				mutex_enter(&connp->conn_lock);
10670 				connp->conn_dontroute = *i1 ? 1 : 0;
10671 				mutex_exit(&connp->conn_lock);
10672 			}
10673 			break;	/* goto sizeof (int) option return */
10674 		case SO_REUSEADDR:
10675 			if (!checkonly) {
10676 				mutex_enter(&connp->conn_lock);
10677 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10678 				mutex_exit(&connp->conn_lock);
10679 			}
10680 			break;	/* goto sizeof (int) option return */
10681 		case SO_PROTOTYPE:
10682 			if (!checkonly) {
10683 				mutex_enter(&connp->conn_lock);
10684 				connp->conn_proto = *i1;
10685 				mutex_exit(&connp->conn_lock);
10686 			}
10687 			break;	/* goto sizeof (int) option return */
10688 		case SO_ALLZONES:
10689 			if (!checkonly) {
10690 				mutex_enter(&connp->conn_lock);
10691 				if (IPCL_IS_BOUND(connp)) {
10692 					mutex_exit(&connp->conn_lock);
10693 					return (EINVAL);
10694 				}
10695 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10696 				mutex_exit(&connp->conn_lock);
10697 			}
10698 			break;	/* goto sizeof (int) option return */
10699 		case SO_ANON_MLP:
10700 			if (!checkonly) {
10701 				mutex_enter(&connp->conn_lock);
10702 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10703 				mutex_exit(&connp->conn_lock);
10704 			}
10705 			break;	/* goto sizeof (int) option return */
10706 		case SO_MAC_EXEMPT:
10707 			if (secpolicy_net_mac_aware(cr) != 0 ||
10708 			    IPCL_IS_BOUND(connp))
10709 				return (EACCES);
10710 			if (!checkonly) {
10711 				mutex_enter(&connp->conn_lock);
10712 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10713 				mutex_exit(&connp->conn_lock);
10714 			}
10715 			break;	/* goto sizeof (int) option return */
10716 		default:
10717 			/*
10718 			 * "soft" error (negative)
10719 			 * option not handled at this level
10720 			 * Note: Do not modify *outlenp
10721 			 */
10722 			return (-EINVAL);
10723 		}
10724 		break;
10725 	case IPPROTO_IP:
10726 		switch (name) {
10727 		case IP_NEXTHOP:
10728 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10729 				return (EPERM);
10730 			/* FALLTHRU */
10731 		case IP_MULTICAST_IF: {
10732 			ipaddr_t addr = *i1;
10733 
10734 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10735 			    first_mp);
10736 			if (error != 0)
10737 				return (error);
10738 			break;	/* goto sizeof (int) option return */
10739 		}
10740 
10741 		case IP_MULTICAST_TTL:
10742 			/* Recorded in transport above IP */
10743 			*outvalp = *invalp;
10744 			*outlenp = sizeof (uchar_t);
10745 			return (0);
10746 		case IP_MULTICAST_LOOP:
10747 			if (!checkonly) {
10748 				mutex_enter(&connp->conn_lock);
10749 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10750 				mutex_exit(&connp->conn_lock);
10751 			}
10752 			*outvalp = *invalp;
10753 			*outlenp = sizeof (uchar_t);
10754 			return (0);
10755 		case IP_ADD_MEMBERSHIP:
10756 		case MCAST_JOIN_GROUP:
10757 		case IP_DROP_MEMBERSHIP:
10758 		case MCAST_LEAVE_GROUP: {
10759 			struct ip_mreq *mreqp;
10760 			struct group_req *greqp;
10761 			ire_t *ire;
10762 			boolean_t done = B_FALSE;
10763 			ipaddr_t group, ifaddr;
10764 			struct sockaddr_in *sin;
10765 			uint32_t *ifindexp;
10766 			boolean_t mcast_opt = B_TRUE;
10767 			mcast_record_t fmode;
10768 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10769 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10770 
10771 			switch (name) {
10772 			case IP_ADD_MEMBERSHIP:
10773 				mcast_opt = B_FALSE;
10774 				/* FALLTHRU */
10775 			case MCAST_JOIN_GROUP:
10776 				fmode = MODE_IS_EXCLUDE;
10777 				optfn = ip_opt_add_group;
10778 				break;
10779 
10780 			case IP_DROP_MEMBERSHIP:
10781 				mcast_opt = B_FALSE;
10782 				/* FALLTHRU */
10783 			case MCAST_LEAVE_GROUP:
10784 				fmode = MODE_IS_INCLUDE;
10785 				optfn = ip_opt_delete_group;
10786 				break;
10787 			}
10788 
10789 			if (mcast_opt) {
10790 				greqp = (struct group_req *)i1;
10791 				sin = (struct sockaddr_in *)&greqp->gr_group;
10792 				if (sin->sin_family != AF_INET) {
10793 					*outlenp = 0;
10794 					return (ENOPROTOOPT);
10795 				}
10796 				group = (ipaddr_t)sin->sin_addr.s_addr;
10797 				ifaddr = INADDR_ANY;
10798 				ifindexp = &greqp->gr_interface;
10799 			} else {
10800 				mreqp = (struct ip_mreq *)i1;
10801 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10802 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10803 				ifindexp = NULL;
10804 			}
10805 
10806 			/*
10807 			 * In the multirouting case, we need to replicate
10808 			 * the request on all interfaces that will take part
10809 			 * in replication.  We do so because multirouting is
10810 			 * reflective, thus we will probably receive multi-
10811 			 * casts on those interfaces.
10812 			 * The ip_multirt_apply_membership() succeeds if the
10813 			 * operation succeeds on at least one interface.
10814 			 */
10815 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10816 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10817 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10818 			if (ire != NULL) {
10819 				if (ire->ire_flags & RTF_MULTIRT) {
10820 					error = ip_multirt_apply_membership(
10821 					    optfn, ire, connp, checkonly, group,
10822 					    fmode, INADDR_ANY, first_mp);
10823 					done = B_TRUE;
10824 				}
10825 				ire_refrele(ire);
10826 			}
10827 			if (!done) {
10828 				error = optfn(connp, checkonly, group, ifaddr,
10829 				    ifindexp, fmode, INADDR_ANY, first_mp);
10830 			}
10831 			if (error) {
10832 				/*
10833 				 * EINPROGRESS is a soft error, needs retry
10834 				 * so don't make *outlenp zero.
10835 				 */
10836 				if (error != EINPROGRESS)
10837 					*outlenp = 0;
10838 				return (error);
10839 			}
10840 			/* OK return - copy input buffer into output buffer */
10841 			if (invalp != outvalp) {
10842 				/* don't trust bcopy for identical src/dst */
10843 				bcopy(invalp, outvalp, inlen);
10844 			}
10845 			*outlenp = inlen;
10846 			return (0);
10847 		}
10848 		case IP_BLOCK_SOURCE:
10849 		case IP_UNBLOCK_SOURCE:
10850 		case IP_ADD_SOURCE_MEMBERSHIP:
10851 		case IP_DROP_SOURCE_MEMBERSHIP:
10852 		case MCAST_BLOCK_SOURCE:
10853 		case MCAST_UNBLOCK_SOURCE:
10854 		case MCAST_JOIN_SOURCE_GROUP:
10855 		case MCAST_LEAVE_SOURCE_GROUP: {
10856 			struct ip_mreq_source *imreqp;
10857 			struct group_source_req *gsreqp;
10858 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10859 			uint32_t ifindex = 0;
10860 			mcast_record_t fmode;
10861 			struct sockaddr_in *sin;
10862 			ire_t *ire;
10863 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10864 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10865 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10866 
10867 			switch (name) {
10868 			case IP_BLOCK_SOURCE:
10869 				mcast_opt = B_FALSE;
10870 				/* FALLTHRU */
10871 			case MCAST_BLOCK_SOURCE:
10872 				fmode = MODE_IS_EXCLUDE;
10873 				optfn = ip_opt_add_group;
10874 				break;
10875 
10876 			case IP_UNBLOCK_SOURCE:
10877 				mcast_opt = B_FALSE;
10878 				/* FALLTHRU */
10879 			case MCAST_UNBLOCK_SOURCE:
10880 				fmode = MODE_IS_EXCLUDE;
10881 				optfn = ip_opt_delete_group;
10882 				break;
10883 
10884 			case IP_ADD_SOURCE_MEMBERSHIP:
10885 				mcast_opt = B_FALSE;
10886 				/* FALLTHRU */
10887 			case MCAST_JOIN_SOURCE_GROUP:
10888 				fmode = MODE_IS_INCLUDE;
10889 				optfn = ip_opt_add_group;
10890 				break;
10891 
10892 			case IP_DROP_SOURCE_MEMBERSHIP:
10893 				mcast_opt = B_FALSE;
10894 				/* FALLTHRU */
10895 			case MCAST_LEAVE_SOURCE_GROUP:
10896 				fmode = MODE_IS_INCLUDE;
10897 				optfn = ip_opt_delete_group;
10898 				break;
10899 			}
10900 
10901 			if (mcast_opt) {
10902 				gsreqp = (struct group_source_req *)i1;
10903 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10904 					*outlenp = 0;
10905 					return (ENOPROTOOPT);
10906 				}
10907 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10908 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10909 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10910 				src = (ipaddr_t)sin->sin_addr.s_addr;
10911 				ifindex = gsreqp->gsr_interface;
10912 			} else {
10913 				imreqp = (struct ip_mreq_source *)i1;
10914 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10915 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10916 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10917 			}
10918 
10919 			/*
10920 			 * In the multirouting case, we need to replicate
10921 			 * the request as noted in the mcast cases above.
10922 			 */
10923 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10924 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10925 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10926 			if (ire != NULL) {
10927 				if (ire->ire_flags & RTF_MULTIRT) {
10928 					error = ip_multirt_apply_membership(
10929 					    optfn, ire, connp, checkonly, grp,
10930 					    fmode, src, first_mp);
10931 					done = B_TRUE;
10932 				}
10933 				ire_refrele(ire);
10934 			}
10935 			if (!done) {
10936 				error = optfn(connp, checkonly, grp, ifaddr,
10937 				    &ifindex, fmode, src, first_mp);
10938 			}
10939 			if (error != 0) {
10940 				/*
10941 				 * EINPROGRESS is a soft error, needs retry
10942 				 * so don't make *outlenp zero.
10943 				 */
10944 				if (error != EINPROGRESS)
10945 					*outlenp = 0;
10946 				return (error);
10947 			}
10948 			/* OK return - copy input buffer into output buffer */
10949 			if (invalp != outvalp) {
10950 				bcopy(invalp, outvalp, inlen);
10951 			}
10952 			*outlenp = inlen;
10953 			return (0);
10954 		}
10955 		case IP_SEC_OPT:
10956 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10957 			if (error != 0) {
10958 				*outlenp = 0;
10959 				return (error);
10960 			}
10961 			break;
10962 		case IP_HDRINCL:
10963 		case IP_OPTIONS:
10964 		case T_IP_OPTIONS:
10965 		case IP_TOS:
10966 		case T_IP_TOS:
10967 		case IP_TTL:
10968 		case IP_RECVDSTADDR:
10969 		case IP_RECVOPTS:
10970 			/* OK return - copy input buffer into output buffer */
10971 			if (invalp != outvalp) {
10972 				/* don't trust bcopy for identical src/dst */
10973 				bcopy(invalp, outvalp, inlen);
10974 			}
10975 			*outlenp = inlen;
10976 			return (0);
10977 		case IP_RECVIF:
10978 			/* Retrieve the inbound interface index */
10979 			if (!checkonly) {
10980 				mutex_enter(&connp->conn_lock);
10981 				connp->conn_recvif = *i1 ? 1 : 0;
10982 				mutex_exit(&connp->conn_lock);
10983 			}
10984 			break;	/* goto sizeof (int) option return */
10985 		case IP_RECVPKTINFO:
10986 			if (!checkonly) {
10987 				mutex_enter(&connp->conn_lock);
10988 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10989 				mutex_exit(&connp->conn_lock);
10990 			}
10991 			break;	/* goto sizeof (int) option return */
10992 		case IP_RECVSLLA:
10993 			/* Retrieve the source link layer address */
10994 			if (!checkonly) {
10995 				mutex_enter(&connp->conn_lock);
10996 				connp->conn_recvslla = *i1 ? 1 : 0;
10997 				mutex_exit(&connp->conn_lock);
10998 			}
10999 			break;	/* goto sizeof (int) option return */
11000 		case MRT_INIT:
11001 		case MRT_DONE:
11002 		case MRT_ADD_VIF:
11003 		case MRT_DEL_VIF:
11004 		case MRT_ADD_MFC:
11005 		case MRT_DEL_MFC:
11006 		case MRT_ASSERT:
11007 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11008 				*outlenp = 0;
11009 				return (error);
11010 			}
11011 			error = ip_mrouter_set((int)name, q, checkonly,
11012 			    (uchar_t *)invalp, inlen, first_mp);
11013 			if (error) {
11014 				*outlenp = 0;
11015 				return (error);
11016 			}
11017 			/* OK return - copy input buffer into output buffer */
11018 			if (invalp != outvalp) {
11019 				/* don't trust bcopy for identical src/dst */
11020 				bcopy(invalp, outvalp, inlen);
11021 			}
11022 			*outlenp = inlen;
11023 			return (0);
11024 		case IP_BOUND_IF:
11025 		case IP_DHCPINIT_IF:
11026 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11027 			    level, name, first_mp);
11028 			if (error != 0)
11029 				return (error);
11030 			break; 		/* goto sizeof (int) option return */
11031 
11032 		case IP_UNSPEC_SRC:
11033 			/* Allow sending with a zero source address */
11034 			if (!checkonly) {
11035 				mutex_enter(&connp->conn_lock);
11036 				connp->conn_unspec_src = *i1 ? 1 : 0;
11037 				mutex_exit(&connp->conn_lock);
11038 			}
11039 			break;	/* goto sizeof (int) option return */
11040 		default:
11041 			/*
11042 			 * "soft" error (negative)
11043 			 * option not handled at this level
11044 			 * Note: Do not modify *outlenp
11045 			 */
11046 			return (-EINVAL);
11047 		}
11048 		break;
11049 	case IPPROTO_IPV6:
11050 		switch (name) {
11051 		case IPV6_BOUND_IF:
11052 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11053 			    level, name, first_mp);
11054 			if (error != 0)
11055 				return (error);
11056 			break; 		/* goto sizeof (int) option return */
11057 
11058 		case IPV6_MULTICAST_IF:
11059 			/*
11060 			 * The only possible errors are EINPROGRESS and
11061 			 * EINVAL. EINPROGRESS will be restarted and is not
11062 			 * a hard error. We call this option on both V4 and V6
11063 			 * If both return EINVAL, then this call returns
11064 			 * EINVAL. If at least one of them succeeds we
11065 			 * return success.
11066 			 */
11067 			found = B_FALSE;
11068 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11069 			    level, name, first_mp);
11070 			if (error == EINPROGRESS)
11071 				return (error);
11072 			if (error == 0)
11073 				found = B_TRUE;
11074 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11075 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11076 			if (error == 0)
11077 				found = B_TRUE;
11078 			if (!found)
11079 				return (error);
11080 			break; 		/* goto sizeof (int) option return */
11081 
11082 		case IPV6_MULTICAST_HOPS:
11083 			/* Recorded in transport above IP */
11084 			break;	/* goto sizeof (int) option return */
11085 		case IPV6_MULTICAST_LOOP:
11086 			if (!checkonly) {
11087 				mutex_enter(&connp->conn_lock);
11088 				connp->conn_multicast_loop = *i1;
11089 				mutex_exit(&connp->conn_lock);
11090 			}
11091 			break;	/* goto sizeof (int) option return */
11092 		case IPV6_JOIN_GROUP:
11093 		case MCAST_JOIN_GROUP:
11094 		case IPV6_LEAVE_GROUP:
11095 		case MCAST_LEAVE_GROUP: {
11096 			struct ipv6_mreq *ip_mreqp;
11097 			struct group_req *greqp;
11098 			ire_t *ire;
11099 			boolean_t done = B_FALSE;
11100 			in6_addr_t groupv6;
11101 			uint32_t ifindex;
11102 			boolean_t mcast_opt = B_TRUE;
11103 			mcast_record_t fmode;
11104 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11105 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11106 
11107 			switch (name) {
11108 			case IPV6_JOIN_GROUP:
11109 				mcast_opt = B_FALSE;
11110 				/* FALLTHRU */
11111 			case MCAST_JOIN_GROUP:
11112 				fmode = MODE_IS_EXCLUDE;
11113 				optfn = ip_opt_add_group_v6;
11114 				break;
11115 
11116 			case IPV6_LEAVE_GROUP:
11117 				mcast_opt = B_FALSE;
11118 				/* FALLTHRU */
11119 			case MCAST_LEAVE_GROUP:
11120 				fmode = MODE_IS_INCLUDE;
11121 				optfn = ip_opt_delete_group_v6;
11122 				break;
11123 			}
11124 
11125 			if (mcast_opt) {
11126 				struct sockaddr_in *sin;
11127 				struct sockaddr_in6 *sin6;
11128 				greqp = (struct group_req *)i1;
11129 				if (greqp->gr_group.ss_family == AF_INET) {
11130 					sin = (struct sockaddr_in *)
11131 					    &(greqp->gr_group);
11132 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11133 					    &groupv6);
11134 				} else {
11135 					sin6 = (struct sockaddr_in6 *)
11136 					    &(greqp->gr_group);
11137 					groupv6 = sin6->sin6_addr;
11138 				}
11139 				ifindex = greqp->gr_interface;
11140 			} else {
11141 				ip_mreqp = (struct ipv6_mreq *)i1;
11142 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11143 				ifindex = ip_mreqp->ipv6mr_interface;
11144 			}
11145 			/*
11146 			 * In the multirouting case, we need to replicate
11147 			 * the request on all interfaces that will take part
11148 			 * in replication.  We do so because multirouting is
11149 			 * reflective, thus we will probably receive multi-
11150 			 * casts on those interfaces.
11151 			 * The ip_multirt_apply_membership_v6() succeeds if
11152 			 * the operation succeeds on at least one interface.
11153 			 */
11154 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11155 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11156 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11157 			if (ire != NULL) {
11158 				if (ire->ire_flags & RTF_MULTIRT) {
11159 					error = ip_multirt_apply_membership_v6(
11160 					    optfn, ire, connp, checkonly,
11161 					    &groupv6, fmode, &ipv6_all_zeros,
11162 					    first_mp);
11163 					done = B_TRUE;
11164 				}
11165 				ire_refrele(ire);
11166 			}
11167 			if (!done) {
11168 				error = optfn(connp, checkonly, &groupv6,
11169 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11170 			}
11171 			if (error) {
11172 				/*
11173 				 * EINPROGRESS is a soft error, needs retry
11174 				 * so don't make *outlenp zero.
11175 				 */
11176 				if (error != EINPROGRESS)
11177 					*outlenp = 0;
11178 				return (error);
11179 			}
11180 			/* OK return - copy input buffer into output buffer */
11181 			if (invalp != outvalp) {
11182 				/* don't trust bcopy for identical src/dst */
11183 				bcopy(invalp, outvalp, inlen);
11184 			}
11185 			*outlenp = inlen;
11186 			return (0);
11187 		}
11188 		case MCAST_BLOCK_SOURCE:
11189 		case MCAST_UNBLOCK_SOURCE:
11190 		case MCAST_JOIN_SOURCE_GROUP:
11191 		case MCAST_LEAVE_SOURCE_GROUP: {
11192 			struct group_source_req *gsreqp;
11193 			in6_addr_t v6grp, v6src;
11194 			uint32_t ifindex;
11195 			mcast_record_t fmode;
11196 			ire_t *ire;
11197 			boolean_t done = B_FALSE;
11198 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11199 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11200 
11201 			switch (name) {
11202 			case MCAST_BLOCK_SOURCE:
11203 				fmode = MODE_IS_EXCLUDE;
11204 				optfn = ip_opt_add_group_v6;
11205 				break;
11206 			case MCAST_UNBLOCK_SOURCE:
11207 				fmode = MODE_IS_EXCLUDE;
11208 				optfn = ip_opt_delete_group_v6;
11209 				break;
11210 			case MCAST_JOIN_SOURCE_GROUP:
11211 				fmode = MODE_IS_INCLUDE;
11212 				optfn = ip_opt_add_group_v6;
11213 				break;
11214 			case MCAST_LEAVE_SOURCE_GROUP:
11215 				fmode = MODE_IS_INCLUDE;
11216 				optfn = ip_opt_delete_group_v6;
11217 				break;
11218 			}
11219 
11220 			gsreqp = (struct group_source_req *)i1;
11221 			ifindex = gsreqp->gsr_interface;
11222 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11223 				struct sockaddr_in *s;
11224 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11225 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11226 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11227 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11228 			} else {
11229 				struct sockaddr_in6 *s6;
11230 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11231 				v6grp = s6->sin6_addr;
11232 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11233 				v6src = s6->sin6_addr;
11234 			}
11235 
11236 			/*
11237 			 * In the multirouting case, we need to replicate
11238 			 * the request as noted in the mcast cases above.
11239 			 */
11240 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11241 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11242 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11243 			if (ire != NULL) {
11244 				if (ire->ire_flags & RTF_MULTIRT) {
11245 					error = ip_multirt_apply_membership_v6(
11246 					    optfn, ire, connp, checkonly,
11247 					    &v6grp, fmode, &v6src, first_mp);
11248 					done = B_TRUE;
11249 				}
11250 				ire_refrele(ire);
11251 			}
11252 			if (!done) {
11253 				error = optfn(connp, checkonly, &v6grp,
11254 				    ifindex, fmode, &v6src, first_mp);
11255 			}
11256 			if (error != 0) {
11257 				/*
11258 				 * EINPROGRESS is a soft error, needs retry
11259 				 * so don't make *outlenp zero.
11260 				 */
11261 				if (error != EINPROGRESS)
11262 					*outlenp = 0;
11263 				return (error);
11264 			}
11265 			/* OK return - copy input buffer into output buffer */
11266 			if (invalp != outvalp) {
11267 				bcopy(invalp, outvalp, inlen);
11268 			}
11269 			*outlenp = inlen;
11270 			return (0);
11271 		}
11272 		case IPV6_UNICAST_HOPS:
11273 			/* Recorded in transport above IP */
11274 			break;	/* goto sizeof (int) option return */
11275 		case IPV6_UNSPEC_SRC:
11276 			/* Allow sending with a zero source address */
11277 			if (!checkonly) {
11278 				mutex_enter(&connp->conn_lock);
11279 				connp->conn_unspec_src = *i1 ? 1 : 0;
11280 				mutex_exit(&connp->conn_lock);
11281 			}
11282 			break;	/* goto sizeof (int) option return */
11283 		case IPV6_RECVPKTINFO:
11284 			if (!checkonly) {
11285 				mutex_enter(&connp->conn_lock);
11286 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11287 				mutex_exit(&connp->conn_lock);
11288 			}
11289 			break;	/* goto sizeof (int) option return */
11290 		case IPV6_RECVTCLASS:
11291 			if (!checkonly) {
11292 				if (*i1 < 0 || *i1 > 1) {
11293 					return (EINVAL);
11294 				}
11295 				mutex_enter(&connp->conn_lock);
11296 				connp->conn_ipv6_recvtclass = *i1;
11297 				mutex_exit(&connp->conn_lock);
11298 			}
11299 			break;
11300 		case IPV6_RECVPATHMTU:
11301 			if (!checkonly) {
11302 				if (*i1 < 0 || *i1 > 1) {
11303 					return (EINVAL);
11304 				}
11305 				mutex_enter(&connp->conn_lock);
11306 				connp->conn_ipv6_recvpathmtu = *i1;
11307 				mutex_exit(&connp->conn_lock);
11308 			}
11309 			break;
11310 		case IPV6_RECVHOPLIMIT:
11311 			if (!checkonly) {
11312 				mutex_enter(&connp->conn_lock);
11313 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11314 				mutex_exit(&connp->conn_lock);
11315 			}
11316 			break;	/* goto sizeof (int) option return */
11317 		case IPV6_RECVHOPOPTS:
11318 			if (!checkonly) {
11319 				mutex_enter(&connp->conn_lock);
11320 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11321 				mutex_exit(&connp->conn_lock);
11322 			}
11323 			break;	/* goto sizeof (int) option return */
11324 		case IPV6_RECVDSTOPTS:
11325 			if (!checkonly) {
11326 				mutex_enter(&connp->conn_lock);
11327 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11328 				mutex_exit(&connp->conn_lock);
11329 			}
11330 			break;	/* goto sizeof (int) option return */
11331 		case IPV6_RECVRTHDR:
11332 			if (!checkonly) {
11333 				mutex_enter(&connp->conn_lock);
11334 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11335 				mutex_exit(&connp->conn_lock);
11336 			}
11337 			break;	/* goto sizeof (int) option return */
11338 		case IPV6_RECVRTHDRDSTOPTS:
11339 			if (!checkonly) {
11340 				mutex_enter(&connp->conn_lock);
11341 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11342 				mutex_exit(&connp->conn_lock);
11343 			}
11344 			break;	/* goto sizeof (int) option return */
11345 		case IPV6_PKTINFO:
11346 			if (inlen == 0)
11347 				return (-EINVAL);	/* clearing option */
11348 			error = ip6_set_pktinfo(cr, connp,
11349 			    (struct in6_pktinfo *)invalp);
11350 			if (error != 0)
11351 				*outlenp = 0;
11352 			else
11353 				*outlenp = inlen;
11354 			return (error);
11355 		case IPV6_NEXTHOP: {
11356 			struct sockaddr_in6 *sin6;
11357 
11358 			/* Verify that the nexthop is reachable */
11359 			if (inlen == 0)
11360 				return (-EINVAL);	/* clearing option */
11361 
11362 			sin6 = (struct sockaddr_in6 *)invalp;
11363 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11364 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11365 			    NULL, MATCH_IRE_DEFAULT, ipst);
11366 
11367 			if (ire == NULL) {
11368 				*outlenp = 0;
11369 				return (EHOSTUNREACH);
11370 			}
11371 			ire_refrele(ire);
11372 			return (-EINVAL);
11373 		}
11374 		case IPV6_SEC_OPT:
11375 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11376 			if (error != 0) {
11377 				*outlenp = 0;
11378 				return (error);
11379 			}
11380 			break;
11381 		case IPV6_SRC_PREFERENCES: {
11382 			/*
11383 			 * This is implemented strictly in the ip module
11384 			 * (here and in tcp_opt_*() to accomodate tcp
11385 			 * sockets).  Modules above ip pass this option
11386 			 * down here since ip is the only one that needs to
11387 			 * be aware of source address preferences.
11388 			 *
11389 			 * This socket option only affects connected
11390 			 * sockets that haven't already bound to a specific
11391 			 * IPv6 address.  In other words, sockets that
11392 			 * don't call bind() with an address other than the
11393 			 * unspecified address and that call connect().
11394 			 * ip_bind_connected_v6() passes these preferences
11395 			 * to the ipif_select_source_v6() function.
11396 			 */
11397 			if (inlen != sizeof (uint32_t))
11398 				return (EINVAL);
11399 			error = ip6_set_src_preferences(connp,
11400 			    *(uint32_t *)invalp);
11401 			if (error != 0) {
11402 				*outlenp = 0;
11403 				return (error);
11404 			} else {
11405 				*outlenp = sizeof (uint32_t);
11406 			}
11407 			break;
11408 		}
11409 		case IPV6_V6ONLY:
11410 			if (*i1 < 0 || *i1 > 1) {
11411 				return (EINVAL);
11412 			}
11413 			mutex_enter(&connp->conn_lock);
11414 			connp->conn_ipv6_v6only = *i1;
11415 			mutex_exit(&connp->conn_lock);
11416 			break;
11417 		default:
11418 			return (-EINVAL);
11419 		}
11420 		break;
11421 	default:
11422 		/*
11423 		 * "soft" error (negative)
11424 		 * option not handled at this level
11425 		 * Note: Do not modify *outlenp
11426 		 */
11427 		return (-EINVAL);
11428 	}
11429 	/*
11430 	 * Common case of return from an option that is sizeof (int)
11431 	 */
11432 	*(int *)outvalp = *i1;
11433 	*outlenp = sizeof (int);
11434 	return (0);
11435 }
11436 
11437 /*
11438  * This routine gets default values of certain options whose default
11439  * values are maintained by protocol specific code
11440  */
11441 /* ARGSUSED */
11442 int
11443 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11444 {
11445 	int *i1 = (int *)ptr;
11446 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11447 
11448 	switch (level) {
11449 	case IPPROTO_IP:
11450 		switch (name) {
11451 		case IP_MULTICAST_TTL:
11452 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11453 			return (sizeof (uchar_t));
11454 		case IP_MULTICAST_LOOP:
11455 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11456 			return (sizeof (uchar_t));
11457 		default:
11458 			return (-1);
11459 		}
11460 	case IPPROTO_IPV6:
11461 		switch (name) {
11462 		case IPV6_UNICAST_HOPS:
11463 			*i1 = ipst->ips_ipv6_def_hops;
11464 			return (sizeof (int));
11465 		case IPV6_MULTICAST_HOPS:
11466 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11467 			return (sizeof (int));
11468 		case IPV6_MULTICAST_LOOP:
11469 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11470 			return (sizeof (int));
11471 		case IPV6_V6ONLY:
11472 			*i1 = 1;
11473 			return (sizeof (int));
11474 		default:
11475 			return (-1);
11476 		}
11477 	default:
11478 		return (-1);
11479 	}
11480 	/* NOTREACHED */
11481 }
11482 
11483 /*
11484  * Given a destination address and a pointer to where to put the information
11485  * this routine fills in the mtuinfo.
11486  */
11487 int
11488 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11489     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11490 {
11491 	ire_t *ire;
11492 	ip_stack_t	*ipst = ns->netstack_ip;
11493 
11494 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11495 		return (-1);
11496 
11497 	bzero(mtuinfo, sizeof (*mtuinfo));
11498 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11499 	mtuinfo->ip6m_addr.sin6_port = port;
11500 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11501 
11502 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11503 	if (ire != NULL) {
11504 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11505 		ire_refrele(ire);
11506 	} else {
11507 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11508 	}
11509 	return (sizeof (struct ip6_mtuinfo));
11510 }
11511 
11512 /*
11513  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11514  * checking of cred and that ip_g_mrouter is set should be done and
11515  * isn't.  This doesn't matter as the error checking is done properly for the
11516  * other MRT options coming in through ip_opt_set.
11517  */
11518 int
11519 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11520 {
11521 	conn_t		*connp = Q_TO_CONN(q);
11522 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11523 
11524 	switch (level) {
11525 	case IPPROTO_IP:
11526 		switch (name) {
11527 		case MRT_VERSION:
11528 		case MRT_ASSERT:
11529 			(void) ip_mrouter_get(name, q, ptr);
11530 			return (sizeof (int));
11531 		case IP_SEC_OPT:
11532 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11533 		case IP_NEXTHOP:
11534 			if (connp->conn_nexthop_set) {
11535 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11536 				return (sizeof (ipaddr_t));
11537 			} else
11538 				return (0);
11539 		case IP_RECVPKTINFO:
11540 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11541 			return (sizeof (int));
11542 		default:
11543 			break;
11544 		}
11545 		break;
11546 	case IPPROTO_IPV6:
11547 		switch (name) {
11548 		case IPV6_SEC_OPT:
11549 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11550 		case IPV6_SRC_PREFERENCES: {
11551 			return (ip6_get_src_preferences(connp,
11552 			    (uint32_t *)ptr));
11553 		}
11554 		case IPV6_V6ONLY:
11555 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11556 			return (sizeof (int));
11557 		case IPV6_PATHMTU:
11558 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11559 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11560 		default:
11561 			break;
11562 		}
11563 		break;
11564 	default:
11565 		break;
11566 	}
11567 	return (-1);
11568 }
11569 /* Named Dispatch routine to get a current value out of our parameter table. */
11570 /* ARGSUSED */
11571 static int
11572 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11573 {
11574 	ipparam_t *ippa = (ipparam_t *)cp;
11575 
11576 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11577 	return (0);
11578 }
11579 
11580 /* ARGSUSED */
11581 static int
11582 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11583 {
11584 
11585 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11586 	return (0);
11587 }
11588 
11589 /*
11590  * Set ip{,6}_forwarding values.  This means walking through all of the
11591  * ill's and toggling their forwarding values.
11592  */
11593 /* ARGSUSED */
11594 static int
11595 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11596 {
11597 	long new_value;
11598 	int *forwarding_value = (int *)cp;
11599 	ill_t *ill;
11600 	boolean_t isv6;
11601 	ill_walk_context_t ctx;
11602 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11603 
11604 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11605 
11606 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11607 	    new_value < 0 || new_value > 1) {
11608 		return (EINVAL);
11609 	}
11610 
11611 	*forwarding_value = new_value;
11612 
11613 	/*
11614 	 * Regardless of the current value of ip_forwarding, set all per-ill
11615 	 * values of ip_forwarding to the value being set.
11616 	 *
11617 	 * Bring all the ill's up to date with the new global value.
11618 	 */
11619 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11620 
11621 	if (isv6)
11622 		ill = ILL_START_WALK_V6(&ctx, ipst);
11623 	else
11624 		ill = ILL_START_WALK_V4(&ctx, ipst);
11625 
11626 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11627 		(void) ill_forward_set(ill, new_value != 0);
11628 
11629 	rw_exit(&ipst->ips_ill_g_lock);
11630 	return (0);
11631 }
11632 
11633 /*
11634  * Walk through the param array specified registering each element with the
11635  * Named Dispatch handler. This is called only during init. So it is ok
11636  * not to acquire any locks
11637  */
11638 static boolean_t
11639 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11640     ipndp_t *ipnd, size_t ipnd_cnt)
11641 {
11642 	for (; ippa_cnt-- > 0; ippa++) {
11643 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11644 			if (!nd_load(ndp, ippa->ip_param_name,
11645 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11646 				nd_free(ndp);
11647 				return (B_FALSE);
11648 			}
11649 		}
11650 	}
11651 
11652 	for (; ipnd_cnt-- > 0; ipnd++) {
11653 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11654 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11655 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11656 			    ipnd->ip_ndp_data)) {
11657 				nd_free(ndp);
11658 				return (B_FALSE);
11659 			}
11660 		}
11661 	}
11662 
11663 	return (B_TRUE);
11664 }
11665 
11666 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11667 /* ARGSUSED */
11668 static int
11669 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11670 {
11671 	long		new_value;
11672 	ipparam_t	*ippa = (ipparam_t *)cp;
11673 
11674 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11675 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11676 		return (EINVAL);
11677 	}
11678 	ippa->ip_param_value = new_value;
11679 	return (0);
11680 }
11681 
11682 /*
11683  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11684  * When an ipf is passed here for the first time, if
11685  * we already have in-order fragments on the queue, we convert from the fast-
11686  * path reassembly scheme to the hard-case scheme.  From then on, additional
11687  * fragments are reassembled here.  We keep track of the start and end offsets
11688  * of each piece, and the number of holes in the chain.  When the hole count
11689  * goes to zero, we are done!
11690  *
11691  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11692  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11693  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11694  * after the call to ip_reassemble().
11695  */
11696 int
11697 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11698     size_t msg_len)
11699 {
11700 	uint_t	end;
11701 	mblk_t	*next_mp;
11702 	mblk_t	*mp1;
11703 	uint_t	offset;
11704 	boolean_t incr_dups = B_TRUE;
11705 	boolean_t offset_zero_seen = B_FALSE;
11706 	boolean_t pkt_boundary_checked = B_FALSE;
11707 
11708 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11709 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11710 
11711 	/* Add in byte count */
11712 	ipf->ipf_count += msg_len;
11713 	if (ipf->ipf_end) {
11714 		/*
11715 		 * We were part way through in-order reassembly, but now there
11716 		 * is a hole.  We walk through messages already queued, and
11717 		 * mark them for hard case reassembly.  We know that up till
11718 		 * now they were in order starting from offset zero.
11719 		 */
11720 		offset = 0;
11721 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11722 			IP_REASS_SET_START(mp1, offset);
11723 			if (offset == 0) {
11724 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11725 				offset = -ipf->ipf_nf_hdr_len;
11726 			}
11727 			offset += mp1->b_wptr - mp1->b_rptr;
11728 			IP_REASS_SET_END(mp1, offset);
11729 		}
11730 		/* One hole at the end. */
11731 		ipf->ipf_hole_cnt = 1;
11732 		/* Brand it as a hard case, forever. */
11733 		ipf->ipf_end = 0;
11734 	}
11735 	/* Walk through all the new pieces. */
11736 	do {
11737 		end = start + (mp->b_wptr - mp->b_rptr);
11738 		/*
11739 		 * If start is 0, decrease 'end' only for the first mblk of
11740 		 * the fragment. Otherwise 'end' can get wrong value in the
11741 		 * second pass of the loop if first mblk is exactly the
11742 		 * size of ipf_nf_hdr_len.
11743 		 */
11744 		if (start == 0 && !offset_zero_seen) {
11745 			/* First segment */
11746 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11747 			end -= ipf->ipf_nf_hdr_len;
11748 			offset_zero_seen = B_TRUE;
11749 		}
11750 		next_mp = mp->b_cont;
11751 		/*
11752 		 * We are checking to see if there is any interesing data
11753 		 * to process.  If there isn't and the mblk isn't the
11754 		 * one which carries the unfragmentable header then we
11755 		 * drop it.  It's possible to have just the unfragmentable
11756 		 * header come through without any data.  That needs to be
11757 		 * saved.
11758 		 *
11759 		 * If the assert at the top of this function holds then the
11760 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11761 		 * is infrequently traveled enough that the test is left in
11762 		 * to protect against future code changes which break that
11763 		 * invariant.
11764 		 */
11765 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11766 			/* Empty.  Blast it. */
11767 			IP_REASS_SET_START(mp, 0);
11768 			IP_REASS_SET_END(mp, 0);
11769 			/*
11770 			 * If the ipf points to the mblk we are about to free,
11771 			 * update ipf to point to the next mblk (or NULL
11772 			 * if none).
11773 			 */
11774 			if (ipf->ipf_mp->b_cont == mp)
11775 				ipf->ipf_mp->b_cont = next_mp;
11776 			freeb(mp);
11777 			continue;
11778 		}
11779 		mp->b_cont = NULL;
11780 		IP_REASS_SET_START(mp, start);
11781 		IP_REASS_SET_END(mp, end);
11782 		if (!ipf->ipf_tail_mp) {
11783 			ipf->ipf_tail_mp = mp;
11784 			ipf->ipf_mp->b_cont = mp;
11785 			if (start == 0 || !more) {
11786 				ipf->ipf_hole_cnt = 1;
11787 				/*
11788 				 * if the first fragment comes in more than one
11789 				 * mblk, this loop will be executed for each
11790 				 * mblk. Need to adjust hole count so exiting
11791 				 * this routine will leave hole count at 1.
11792 				 */
11793 				if (next_mp)
11794 					ipf->ipf_hole_cnt++;
11795 			} else
11796 				ipf->ipf_hole_cnt = 2;
11797 			continue;
11798 		} else if (ipf->ipf_last_frag_seen && !more &&
11799 		    !pkt_boundary_checked) {
11800 			/*
11801 			 * We check datagram boundary only if this fragment
11802 			 * claims to be the last fragment and we have seen a
11803 			 * last fragment in the past too. We do this only
11804 			 * once for a given fragment.
11805 			 *
11806 			 * start cannot be 0 here as fragments with start=0
11807 			 * and MF=0 gets handled as a complete packet. These
11808 			 * fragments should not reach here.
11809 			 */
11810 
11811 			if (start + msgdsize(mp) !=
11812 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11813 				/*
11814 				 * We have two fragments both of which claim
11815 				 * to be the last fragment but gives conflicting
11816 				 * information about the whole datagram size.
11817 				 * Something fishy is going on. Drop the
11818 				 * fragment and free up the reassembly list.
11819 				 */
11820 				return (IP_REASS_FAILED);
11821 			}
11822 
11823 			/*
11824 			 * We shouldn't come to this code block again for this
11825 			 * particular fragment.
11826 			 */
11827 			pkt_boundary_checked = B_TRUE;
11828 		}
11829 
11830 		/* New stuff at or beyond tail? */
11831 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11832 		if (start >= offset) {
11833 			if (ipf->ipf_last_frag_seen) {
11834 				/* current fragment is beyond last fragment */
11835 				return (IP_REASS_FAILED);
11836 			}
11837 			/* Link it on end. */
11838 			ipf->ipf_tail_mp->b_cont = mp;
11839 			ipf->ipf_tail_mp = mp;
11840 			if (more) {
11841 				if (start != offset)
11842 					ipf->ipf_hole_cnt++;
11843 			} else if (start == offset && next_mp == NULL)
11844 					ipf->ipf_hole_cnt--;
11845 			continue;
11846 		}
11847 		mp1 = ipf->ipf_mp->b_cont;
11848 		offset = IP_REASS_START(mp1);
11849 		/* New stuff at the front? */
11850 		if (start < offset) {
11851 			if (start == 0) {
11852 				if (end >= offset) {
11853 					/* Nailed the hole at the begining. */
11854 					ipf->ipf_hole_cnt--;
11855 				}
11856 			} else if (end < offset) {
11857 				/*
11858 				 * A hole, stuff, and a hole where there used
11859 				 * to be just a hole.
11860 				 */
11861 				ipf->ipf_hole_cnt++;
11862 			}
11863 			mp->b_cont = mp1;
11864 			/* Check for overlap. */
11865 			while (end > offset) {
11866 				if (end < IP_REASS_END(mp1)) {
11867 					mp->b_wptr -= end - offset;
11868 					IP_REASS_SET_END(mp, offset);
11869 					BUMP_MIB(ill->ill_ip_mib,
11870 					    ipIfStatsReasmPartDups);
11871 					break;
11872 				}
11873 				/* Did we cover another hole? */
11874 				if ((mp1->b_cont &&
11875 				    IP_REASS_END(mp1) !=
11876 				    IP_REASS_START(mp1->b_cont) &&
11877 				    end >= IP_REASS_START(mp1->b_cont)) ||
11878 				    (!ipf->ipf_last_frag_seen && !more)) {
11879 					ipf->ipf_hole_cnt--;
11880 				}
11881 				/* Clip out mp1. */
11882 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11883 					/*
11884 					 * After clipping out mp1, this guy
11885 					 * is now hanging off the end.
11886 					 */
11887 					ipf->ipf_tail_mp = mp;
11888 				}
11889 				IP_REASS_SET_START(mp1, 0);
11890 				IP_REASS_SET_END(mp1, 0);
11891 				/* Subtract byte count */
11892 				ipf->ipf_count -= mp1->b_datap->db_lim -
11893 				    mp1->b_datap->db_base;
11894 				freeb(mp1);
11895 				BUMP_MIB(ill->ill_ip_mib,
11896 				    ipIfStatsReasmPartDups);
11897 				mp1 = mp->b_cont;
11898 				if (!mp1)
11899 					break;
11900 				offset = IP_REASS_START(mp1);
11901 			}
11902 			ipf->ipf_mp->b_cont = mp;
11903 			continue;
11904 		}
11905 		/*
11906 		 * The new piece starts somewhere between the start of the head
11907 		 * and before the end of the tail.
11908 		 */
11909 		for (; mp1; mp1 = mp1->b_cont) {
11910 			offset = IP_REASS_END(mp1);
11911 			if (start < offset) {
11912 				if (end <= offset) {
11913 					/* Nothing new. */
11914 					IP_REASS_SET_START(mp, 0);
11915 					IP_REASS_SET_END(mp, 0);
11916 					/* Subtract byte count */
11917 					ipf->ipf_count -= mp->b_datap->db_lim -
11918 					    mp->b_datap->db_base;
11919 					if (incr_dups) {
11920 						ipf->ipf_num_dups++;
11921 						incr_dups = B_FALSE;
11922 					}
11923 					freeb(mp);
11924 					BUMP_MIB(ill->ill_ip_mib,
11925 					    ipIfStatsReasmDuplicates);
11926 					break;
11927 				}
11928 				/*
11929 				 * Trim redundant stuff off beginning of new
11930 				 * piece.
11931 				 */
11932 				IP_REASS_SET_START(mp, offset);
11933 				mp->b_rptr += offset - start;
11934 				BUMP_MIB(ill->ill_ip_mib,
11935 				    ipIfStatsReasmPartDups);
11936 				start = offset;
11937 				if (!mp1->b_cont) {
11938 					/*
11939 					 * After trimming, this guy is now
11940 					 * hanging off the end.
11941 					 */
11942 					mp1->b_cont = mp;
11943 					ipf->ipf_tail_mp = mp;
11944 					if (!more) {
11945 						ipf->ipf_hole_cnt--;
11946 					}
11947 					break;
11948 				}
11949 			}
11950 			if (start >= IP_REASS_START(mp1->b_cont))
11951 				continue;
11952 			/* Fill a hole */
11953 			if (start > offset)
11954 				ipf->ipf_hole_cnt++;
11955 			mp->b_cont = mp1->b_cont;
11956 			mp1->b_cont = mp;
11957 			mp1 = mp->b_cont;
11958 			offset = IP_REASS_START(mp1);
11959 			if (end >= offset) {
11960 				ipf->ipf_hole_cnt--;
11961 				/* Check for overlap. */
11962 				while (end > offset) {
11963 					if (end < IP_REASS_END(mp1)) {
11964 						mp->b_wptr -= end - offset;
11965 						IP_REASS_SET_END(mp, offset);
11966 						/*
11967 						 * TODO we might bump
11968 						 * this up twice if there is
11969 						 * overlap at both ends.
11970 						 */
11971 						BUMP_MIB(ill->ill_ip_mib,
11972 						    ipIfStatsReasmPartDups);
11973 						break;
11974 					}
11975 					/* Did we cover another hole? */
11976 					if ((mp1->b_cont &&
11977 					    IP_REASS_END(mp1)
11978 					    != IP_REASS_START(mp1->b_cont) &&
11979 					    end >=
11980 					    IP_REASS_START(mp1->b_cont)) ||
11981 					    (!ipf->ipf_last_frag_seen &&
11982 					    !more)) {
11983 						ipf->ipf_hole_cnt--;
11984 					}
11985 					/* Clip out mp1. */
11986 					if ((mp->b_cont = mp1->b_cont) ==
11987 					    NULL) {
11988 						/*
11989 						 * After clipping out mp1,
11990 						 * this guy is now hanging
11991 						 * off the end.
11992 						 */
11993 						ipf->ipf_tail_mp = mp;
11994 					}
11995 					IP_REASS_SET_START(mp1, 0);
11996 					IP_REASS_SET_END(mp1, 0);
11997 					/* Subtract byte count */
11998 					ipf->ipf_count -=
11999 					    mp1->b_datap->db_lim -
12000 					    mp1->b_datap->db_base;
12001 					freeb(mp1);
12002 					BUMP_MIB(ill->ill_ip_mib,
12003 					    ipIfStatsReasmPartDups);
12004 					mp1 = mp->b_cont;
12005 					if (!mp1)
12006 						break;
12007 					offset = IP_REASS_START(mp1);
12008 				}
12009 			}
12010 			break;
12011 		}
12012 	} while (start = end, mp = next_mp);
12013 
12014 	/* Fragment just processed could be the last one. Remember this fact */
12015 	if (!more)
12016 		ipf->ipf_last_frag_seen = B_TRUE;
12017 
12018 	/* Still got holes? */
12019 	if (ipf->ipf_hole_cnt)
12020 		return (IP_REASS_PARTIAL);
12021 	/* Clean up overloaded fields to avoid upstream disasters. */
12022 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12023 		IP_REASS_SET_START(mp1, 0);
12024 		IP_REASS_SET_END(mp1, 0);
12025 	}
12026 	return (IP_REASS_COMPLETE);
12027 }
12028 
12029 /*
12030  * ipsec processing for the fast path, used for input UDP Packets
12031  * Returns true if ready for passup to UDP.
12032  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12033  * was an ESP-in-UDP packet, etc.).
12034  */
12035 static boolean_t
12036 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12037     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12038 {
12039 	uint32_t	ill_index;
12040 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12041 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12042 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12043 	udp_t		*udp = connp->conn_udp;
12044 
12045 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12046 	/* The ill_index of the incoming ILL */
12047 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12048 
12049 	/* pass packet up to the transport */
12050 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12051 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12052 		    NULL, mctl_present);
12053 		if (*first_mpp == NULL) {
12054 			return (B_FALSE);
12055 		}
12056 	}
12057 
12058 	/* Initiate IPPF processing for fastpath UDP */
12059 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12060 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12061 		if (*mpp == NULL) {
12062 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12063 			    "deferred/dropped during IPPF processing\n"));
12064 			return (B_FALSE);
12065 		}
12066 	}
12067 	/*
12068 	 * Remove 0-spi if it's 0, or move everything behind
12069 	 * the UDP header over it and forward to ESP via
12070 	 * ip_proto_input().
12071 	 */
12072 	if (udp->udp_nat_t_endpoint) {
12073 		if (mctl_present) {
12074 			/* mctl_present *shouldn't* happen. */
12075 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12076 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12077 			    &ipss->ipsec_dropper);
12078 			*first_mpp = NULL;
12079 			return (B_FALSE);
12080 		}
12081 
12082 		/* "ill" is "recv_ill" in actuality. */
12083 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12084 			return (B_FALSE);
12085 
12086 		/* Else continue like a normal UDP packet. */
12087 	}
12088 
12089 	/*
12090 	 * We make the checks as below since we are in the fast path
12091 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12092 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12093 	 */
12094 	if (connp->conn_recvif || connp->conn_recvslla ||
12095 	    connp->conn_ip_recvpktinfo) {
12096 		if (connp->conn_recvif) {
12097 			in_flags = IPF_RECVIF;
12098 		}
12099 		/*
12100 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12101 		 * so the flag passed to ip_add_info is based on IP version
12102 		 * of connp.
12103 		 */
12104 		if (connp->conn_ip_recvpktinfo) {
12105 			if (connp->conn_af_isv6) {
12106 				/*
12107 				 * V6 only needs index
12108 				 */
12109 				in_flags |= IPF_RECVIF;
12110 			} else {
12111 				/*
12112 				 * V4 needs index + matching address.
12113 				 */
12114 				in_flags |= IPF_RECVADDR;
12115 			}
12116 		}
12117 		if (connp->conn_recvslla) {
12118 			in_flags |= IPF_RECVSLLA;
12119 		}
12120 		/*
12121 		 * since in_flags are being set ill will be
12122 		 * referenced in ip_add_info, so it better not
12123 		 * be NULL.
12124 		 */
12125 		/*
12126 		 * the actual data will be contained in b_cont
12127 		 * upon successful return of the following call.
12128 		 * If the call fails then the original mblk is
12129 		 * returned.
12130 		 */
12131 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12132 		    ipst);
12133 	}
12134 
12135 	return (B_TRUE);
12136 }
12137 
12138 /*
12139  * Fragmentation reassembly.  Each ILL has a hash table for
12140  * queuing packets undergoing reassembly for all IPIFs
12141  * associated with the ILL.  The hash is based on the packet
12142  * IP ident field.  The ILL frag hash table was allocated
12143  * as a timer block at the time the ILL was created.  Whenever
12144  * there is anything on the reassembly queue, the timer will
12145  * be running.  Returns B_TRUE if successful else B_FALSE;
12146  * frees mp on failure.
12147  */
12148 static boolean_t
12149 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12150     uint32_t *cksum_val, uint16_t *cksum_flags)
12151 {
12152 	uint32_t	frag_offset_flags;
12153 	mblk_t		*mp = *mpp;
12154 	mblk_t		*t_mp;
12155 	ipaddr_t	dst;
12156 	uint8_t		proto = ipha->ipha_protocol;
12157 	uint32_t	sum_val;
12158 	uint16_t	sum_flags;
12159 	ipf_t		*ipf;
12160 	ipf_t		**ipfp;
12161 	ipfb_t		*ipfb;
12162 	uint16_t	ident;
12163 	uint32_t	offset;
12164 	ipaddr_t	src;
12165 	uint_t		hdr_length;
12166 	uint32_t	end;
12167 	mblk_t		*mp1;
12168 	mblk_t		*tail_mp;
12169 	size_t		count;
12170 	size_t		msg_len;
12171 	uint8_t		ecn_info = 0;
12172 	uint32_t	packet_size;
12173 	boolean_t	pruned = B_FALSE;
12174 	ip_stack_t *ipst = ill->ill_ipst;
12175 
12176 	if (cksum_val != NULL)
12177 		*cksum_val = 0;
12178 	if (cksum_flags != NULL)
12179 		*cksum_flags = 0;
12180 
12181 	/*
12182 	 * Drop the fragmented as early as possible, if
12183 	 * we don't have resource(s) to re-assemble.
12184 	 */
12185 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12186 		freemsg(mp);
12187 		return (B_FALSE);
12188 	}
12189 
12190 	/* Check for fragmentation offset; return if there's none */
12191 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12192 	    (IPH_MF | IPH_OFFSET)) == 0)
12193 		return (B_TRUE);
12194 
12195 	/*
12196 	 * We utilize hardware computed checksum info only for UDP since
12197 	 * IP fragmentation is a normal occurrence for the protocol.  In
12198 	 * addition, checksum offload support for IP fragments carrying
12199 	 * UDP payload is commonly implemented across network adapters.
12200 	 */
12201 	ASSERT(recv_ill != NULL);
12202 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12203 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12204 		mblk_t *mp1 = mp->b_cont;
12205 		int32_t len;
12206 
12207 		/* Record checksum information from the packet */
12208 		sum_val = (uint32_t)DB_CKSUM16(mp);
12209 		sum_flags = DB_CKSUMFLAGS(mp);
12210 
12211 		/* IP payload offset from beginning of mblk */
12212 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12213 
12214 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12215 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12216 		    offset >= DB_CKSUMSTART(mp) &&
12217 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12218 			uint32_t adj;
12219 			/*
12220 			 * Partial checksum has been calculated by hardware
12221 			 * and attached to the packet; in addition, any
12222 			 * prepended extraneous data is even byte aligned.
12223 			 * If any such data exists, we adjust the checksum;
12224 			 * this would also handle any postpended data.
12225 			 */
12226 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12227 			    mp, mp1, len, adj);
12228 
12229 			/* One's complement subtract extraneous checksum */
12230 			if (adj >= sum_val)
12231 				sum_val = ~(adj - sum_val) & 0xFFFF;
12232 			else
12233 				sum_val -= adj;
12234 		}
12235 	} else {
12236 		sum_val = 0;
12237 		sum_flags = 0;
12238 	}
12239 
12240 	/* Clear hardware checksumming flag */
12241 	DB_CKSUMFLAGS(mp) = 0;
12242 
12243 	ident = ipha->ipha_ident;
12244 	offset = (frag_offset_flags << 3) & 0xFFFF;
12245 	src = ipha->ipha_src;
12246 	dst = ipha->ipha_dst;
12247 	hdr_length = IPH_HDR_LENGTH(ipha);
12248 	end = ntohs(ipha->ipha_length) - hdr_length;
12249 
12250 	/* If end == 0 then we have a packet with no data, so just free it */
12251 	if (end == 0) {
12252 		freemsg(mp);
12253 		return (B_FALSE);
12254 	}
12255 
12256 	/* Record the ECN field info. */
12257 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12258 	if (offset != 0) {
12259 		/*
12260 		 * If this isn't the first piece, strip the header, and
12261 		 * add the offset to the end value.
12262 		 */
12263 		mp->b_rptr += hdr_length;
12264 		end += offset;
12265 	}
12266 
12267 	msg_len = MBLKSIZE(mp);
12268 	tail_mp = mp;
12269 	while (tail_mp->b_cont != NULL) {
12270 		tail_mp = tail_mp->b_cont;
12271 		msg_len += MBLKSIZE(tail_mp);
12272 	}
12273 
12274 	/* If the reassembly list for this ILL will get too big, prune it */
12275 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12276 	    ipst->ips_ip_reass_queue_bytes) {
12277 		ill_frag_prune(ill,
12278 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12279 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12280 		pruned = B_TRUE;
12281 	}
12282 
12283 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12284 	mutex_enter(&ipfb->ipfb_lock);
12285 
12286 	ipfp = &ipfb->ipfb_ipf;
12287 	/* Try to find an existing fragment queue for this packet. */
12288 	for (;;) {
12289 		ipf = ipfp[0];
12290 		if (ipf != NULL) {
12291 			/*
12292 			 * It has to match on ident and src/dst address.
12293 			 */
12294 			if (ipf->ipf_ident == ident &&
12295 			    ipf->ipf_src == src &&
12296 			    ipf->ipf_dst == dst &&
12297 			    ipf->ipf_protocol == proto) {
12298 				/*
12299 				 * If we have received too many
12300 				 * duplicate fragments for this packet
12301 				 * free it.
12302 				 */
12303 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12304 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12305 					freemsg(mp);
12306 					mutex_exit(&ipfb->ipfb_lock);
12307 					return (B_FALSE);
12308 				}
12309 				/* Found it. */
12310 				break;
12311 			}
12312 			ipfp = &ipf->ipf_hash_next;
12313 			continue;
12314 		}
12315 
12316 		/*
12317 		 * If we pruned the list, do we want to store this new
12318 		 * fragment?. We apply an optimization here based on the
12319 		 * fact that most fragments will be received in order.
12320 		 * So if the offset of this incoming fragment is zero,
12321 		 * it is the first fragment of a new packet. We will
12322 		 * keep it.  Otherwise drop the fragment, as we have
12323 		 * probably pruned the packet already (since the
12324 		 * packet cannot be found).
12325 		 */
12326 		if (pruned && offset != 0) {
12327 			mutex_exit(&ipfb->ipfb_lock);
12328 			freemsg(mp);
12329 			return (B_FALSE);
12330 		}
12331 
12332 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12333 			/*
12334 			 * Too many fragmented packets in this hash
12335 			 * bucket. Free the oldest.
12336 			 */
12337 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12338 		}
12339 
12340 		/* New guy.  Allocate a frag message. */
12341 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12342 		if (mp1 == NULL) {
12343 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12344 			freemsg(mp);
12345 reass_done:
12346 			mutex_exit(&ipfb->ipfb_lock);
12347 			return (B_FALSE);
12348 		}
12349 
12350 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12351 		mp1->b_cont = mp;
12352 
12353 		/* Initialize the fragment header. */
12354 		ipf = (ipf_t *)mp1->b_rptr;
12355 		ipf->ipf_mp = mp1;
12356 		ipf->ipf_ptphn = ipfp;
12357 		ipfp[0] = ipf;
12358 		ipf->ipf_hash_next = NULL;
12359 		ipf->ipf_ident = ident;
12360 		ipf->ipf_protocol = proto;
12361 		ipf->ipf_src = src;
12362 		ipf->ipf_dst = dst;
12363 		ipf->ipf_nf_hdr_len = 0;
12364 		/* Record reassembly start time. */
12365 		ipf->ipf_timestamp = gethrestime_sec();
12366 		/* Record ipf generation and account for frag header */
12367 		ipf->ipf_gen = ill->ill_ipf_gen++;
12368 		ipf->ipf_count = MBLKSIZE(mp1);
12369 		ipf->ipf_last_frag_seen = B_FALSE;
12370 		ipf->ipf_ecn = ecn_info;
12371 		ipf->ipf_num_dups = 0;
12372 		ipfb->ipfb_frag_pkts++;
12373 		ipf->ipf_checksum = 0;
12374 		ipf->ipf_checksum_flags = 0;
12375 
12376 		/* Store checksum value in fragment header */
12377 		if (sum_flags != 0) {
12378 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12379 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12380 			ipf->ipf_checksum = sum_val;
12381 			ipf->ipf_checksum_flags = sum_flags;
12382 		}
12383 
12384 		/*
12385 		 * We handle reassembly two ways.  In the easy case,
12386 		 * where all the fragments show up in order, we do
12387 		 * minimal bookkeeping, and just clip new pieces on
12388 		 * the end.  If we ever see a hole, then we go off
12389 		 * to ip_reassemble which has to mark the pieces and
12390 		 * keep track of the number of holes, etc.  Obviously,
12391 		 * the point of having both mechanisms is so we can
12392 		 * handle the easy case as efficiently as possible.
12393 		 */
12394 		if (offset == 0) {
12395 			/* Easy case, in-order reassembly so far. */
12396 			ipf->ipf_count += msg_len;
12397 			ipf->ipf_tail_mp = tail_mp;
12398 			/*
12399 			 * Keep track of next expected offset in
12400 			 * ipf_end.
12401 			 */
12402 			ipf->ipf_end = end;
12403 			ipf->ipf_nf_hdr_len = hdr_length;
12404 		} else {
12405 			/* Hard case, hole at the beginning. */
12406 			ipf->ipf_tail_mp = NULL;
12407 			/*
12408 			 * ipf_end == 0 means that we have given up
12409 			 * on easy reassembly.
12410 			 */
12411 			ipf->ipf_end = 0;
12412 
12413 			/* Forget checksum offload from now on */
12414 			ipf->ipf_checksum_flags = 0;
12415 
12416 			/*
12417 			 * ipf_hole_cnt is set by ip_reassemble.
12418 			 * ipf_count is updated by ip_reassemble.
12419 			 * No need to check for return value here
12420 			 * as we don't expect reassembly to complete
12421 			 * or fail for the first fragment itself.
12422 			 */
12423 			(void) ip_reassemble(mp, ipf,
12424 			    (frag_offset_flags & IPH_OFFSET) << 3,
12425 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12426 		}
12427 		/* Update per ipfb and ill byte counts */
12428 		ipfb->ipfb_count += ipf->ipf_count;
12429 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12430 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12431 		/* If the frag timer wasn't already going, start it. */
12432 		mutex_enter(&ill->ill_lock);
12433 		ill_frag_timer_start(ill);
12434 		mutex_exit(&ill->ill_lock);
12435 		goto reass_done;
12436 	}
12437 
12438 	/*
12439 	 * If the packet's flag has changed (it could be coming up
12440 	 * from an interface different than the previous, therefore
12441 	 * possibly different checksum capability), then forget about
12442 	 * any stored checksum states.  Otherwise add the value to
12443 	 * the existing one stored in the fragment header.
12444 	 */
12445 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12446 		sum_val += ipf->ipf_checksum;
12447 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12448 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12449 		ipf->ipf_checksum = sum_val;
12450 	} else if (ipf->ipf_checksum_flags != 0) {
12451 		/* Forget checksum offload from now on */
12452 		ipf->ipf_checksum_flags = 0;
12453 	}
12454 
12455 	/*
12456 	 * We have a new piece of a datagram which is already being
12457 	 * reassembled.  Update the ECN info if all IP fragments
12458 	 * are ECN capable.  If there is one which is not, clear
12459 	 * all the info.  If there is at least one which has CE
12460 	 * code point, IP needs to report that up to transport.
12461 	 */
12462 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12463 		if (ecn_info == IPH_ECN_CE)
12464 			ipf->ipf_ecn = IPH_ECN_CE;
12465 	} else {
12466 		ipf->ipf_ecn = IPH_ECN_NECT;
12467 	}
12468 	if (offset && ipf->ipf_end == offset) {
12469 		/* The new fragment fits at the end */
12470 		ipf->ipf_tail_mp->b_cont = mp;
12471 		/* Update the byte count */
12472 		ipf->ipf_count += msg_len;
12473 		/* Update per ipfb and ill byte counts */
12474 		ipfb->ipfb_count += msg_len;
12475 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12476 		atomic_add_32(&ill->ill_frag_count, msg_len);
12477 		if (frag_offset_flags & IPH_MF) {
12478 			/* More to come. */
12479 			ipf->ipf_end = end;
12480 			ipf->ipf_tail_mp = tail_mp;
12481 			goto reass_done;
12482 		}
12483 	} else {
12484 		/* Go do the hard cases. */
12485 		int ret;
12486 
12487 		if (offset == 0)
12488 			ipf->ipf_nf_hdr_len = hdr_length;
12489 
12490 		/* Save current byte count */
12491 		count = ipf->ipf_count;
12492 		ret = ip_reassemble(mp, ipf,
12493 		    (frag_offset_flags & IPH_OFFSET) << 3,
12494 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12495 		/* Count of bytes added and subtracted (freeb()ed) */
12496 		count = ipf->ipf_count - count;
12497 		if (count) {
12498 			/* Update per ipfb and ill byte counts */
12499 			ipfb->ipfb_count += count;
12500 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12501 			atomic_add_32(&ill->ill_frag_count, count);
12502 		}
12503 		if (ret == IP_REASS_PARTIAL) {
12504 			goto reass_done;
12505 		} else if (ret == IP_REASS_FAILED) {
12506 			/* Reassembly failed. Free up all resources */
12507 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12508 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12509 				IP_REASS_SET_START(t_mp, 0);
12510 				IP_REASS_SET_END(t_mp, 0);
12511 			}
12512 			freemsg(mp);
12513 			goto reass_done;
12514 		}
12515 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12516 	}
12517 	/*
12518 	 * We have completed reassembly.  Unhook the frag header from
12519 	 * the reassembly list.
12520 	 *
12521 	 * Before we free the frag header, record the ECN info
12522 	 * to report back to the transport.
12523 	 */
12524 	ecn_info = ipf->ipf_ecn;
12525 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12526 	ipfp = ipf->ipf_ptphn;
12527 
12528 	/* We need to supply these to caller */
12529 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12530 		sum_val = ipf->ipf_checksum;
12531 	else
12532 		sum_val = 0;
12533 
12534 	mp1 = ipf->ipf_mp;
12535 	count = ipf->ipf_count;
12536 	ipf = ipf->ipf_hash_next;
12537 	if (ipf != NULL)
12538 		ipf->ipf_ptphn = ipfp;
12539 	ipfp[0] = ipf;
12540 	atomic_add_32(&ill->ill_frag_count, -count);
12541 	ASSERT(ipfb->ipfb_count >= count);
12542 	ipfb->ipfb_count -= count;
12543 	ipfb->ipfb_frag_pkts--;
12544 	mutex_exit(&ipfb->ipfb_lock);
12545 	/* Ditch the frag header. */
12546 	mp = mp1->b_cont;
12547 
12548 	freeb(mp1);
12549 
12550 	/* Restore original IP length in header. */
12551 	packet_size = (uint32_t)msgdsize(mp);
12552 	if (packet_size > IP_MAXPACKET) {
12553 		freemsg(mp);
12554 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12555 		return (B_FALSE);
12556 	}
12557 
12558 	if (DB_REF(mp) > 1) {
12559 		mblk_t *mp2 = copymsg(mp);
12560 
12561 		freemsg(mp);
12562 		if (mp2 == NULL) {
12563 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12564 			return (B_FALSE);
12565 		}
12566 		mp = mp2;
12567 	}
12568 	ipha = (ipha_t *)mp->b_rptr;
12569 
12570 	ipha->ipha_length = htons((uint16_t)packet_size);
12571 	/* We're now complete, zip the frag state */
12572 	ipha->ipha_fragment_offset_and_flags = 0;
12573 	/* Record the ECN info. */
12574 	ipha->ipha_type_of_service &= 0xFC;
12575 	ipha->ipha_type_of_service |= ecn_info;
12576 	*mpp = mp;
12577 
12578 	/* Reassembly is successful; return checksum information if needed */
12579 	if (cksum_val != NULL)
12580 		*cksum_val = sum_val;
12581 	if (cksum_flags != NULL)
12582 		*cksum_flags = sum_flags;
12583 
12584 	return (B_TRUE);
12585 }
12586 
12587 /*
12588  * Perform ip header check sum update local options.
12589  * return B_TRUE if all is well, else return B_FALSE and release
12590  * the mp. caller is responsible for decrementing ire ref cnt.
12591  */
12592 static boolean_t
12593 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12594     ip_stack_t *ipst)
12595 {
12596 	mblk_t		*first_mp;
12597 	boolean_t	mctl_present;
12598 	uint16_t	sum;
12599 
12600 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12601 	/*
12602 	 * Don't do the checksum if it has gone through AH/ESP
12603 	 * processing.
12604 	 */
12605 	if (!mctl_present) {
12606 		sum = ip_csum_hdr(ipha);
12607 		if (sum != 0) {
12608 			if (ill != NULL) {
12609 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12610 			} else {
12611 				BUMP_MIB(&ipst->ips_ip_mib,
12612 				    ipIfStatsInCksumErrs);
12613 			}
12614 			freemsg(first_mp);
12615 			return (B_FALSE);
12616 		}
12617 	}
12618 
12619 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12620 		if (mctl_present)
12621 			freeb(first_mp);
12622 		return (B_FALSE);
12623 	}
12624 
12625 	return (B_TRUE);
12626 }
12627 
12628 /*
12629  * All udp packet are delivered to the local host via this routine.
12630  */
12631 void
12632 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12633     ill_t *recv_ill)
12634 {
12635 	uint32_t	sum;
12636 	uint32_t	u1;
12637 	boolean_t	mctl_present;
12638 	conn_t		*connp;
12639 	mblk_t		*first_mp;
12640 	uint16_t	*up;
12641 	ill_t		*ill = (ill_t *)q->q_ptr;
12642 	uint16_t	reass_hck_flags = 0;
12643 	ip_stack_t	*ipst;
12644 
12645 	ASSERT(recv_ill != NULL);
12646 	ipst = recv_ill->ill_ipst;
12647 
12648 #define	rptr    ((uchar_t *)ipha)
12649 
12650 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12651 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12652 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12653 	ASSERT(ill != NULL);
12654 
12655 	/*
12656 	 * FAST PATH for udp packets
12657 	 */
12658 
12659 	/* u1 is # words of IP options */
12660 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12661 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12662 
12663 	/* IP options present */
12664 	if (u1 != 0)
12665 		goto ipoptions;
12666 
12667 	/* Check the IP header checksum.  */
12668 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12669 		/* Clear the IP header h/w cksum flag */
12670 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12671 	} else if (!mctl_present) {
12672 		/*
12673 		 * Don't verify header checksum if this packet is coming
12674 		 * back from AH/ESP as we already did it.
12675 		 */
12676 #define	uph	((uint16_t *)ipha)
12677 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12678 		    uph[6] + uph[7] + uph[8] + uph[9];
12679 #undef	uph
12680 		/* finish doing IP checksum */
12681 		sum = (sum & 0xFFFF) + (sum >> 16);
12682 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12683 		if (sum != 0 && sum != 0xFFFF) {
12684 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12685 			freemsg(first_mp);
12686 			return;
12687 		}
12688 	}
12689 
12690 	/*
12691 	 * Count for SNMP of inbound packets for ire.
12692 	 * if mctl is present this might be a secure packet and
12693 	 * has already been counted for in ip_proto_input().
12694 	 */
12695 	if (!mctl_present) {
12696 		UPDATE_IB_PKT_COUNT(ire);
12697 		ire->ire_last_used_time = lbolt;
12698 	}
12699 
12700 	/* packet part of fragmented IP packet? */
12701 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12702 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12703 		goto fragmented;
12704 	}
12705 
12706 	/* u1 = IP header length (20 bytes) */
12707 	u1 = IP_SIMPLE_HDR_LENGTH;
12708 
12709 	/* packet does not contain complete IP & UDP headers */
12710 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12711 		goto udppullup;
12712 
12713 	/* up points to UDP header */
12714 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12715 #define	iphs    ((uint16_t *)ipha)
12716 
12717 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12718 	if (up[3] != 0) {
12719 		mblk_t *mp1 = mp->b_cont;
12720 		boolean_t cksum_err;
12721 		uint16_t hck_flags = 0;
12722 
12723 		/* Pseudo-header checksum */
12724 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12725 		    iphs[9] + up[2];
12726 
12727 		/*
12728 		 * Revert to software checksum calculation if the interface
12729 		 * isn't capable of checksum offload or if IPsec is present.
12730 		 */
12731 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12732 			hck_flags = DB_CKSUMFLAGS(mp);
12733 
12734 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12735 			IP_STAT(ipst, ip_in_sw_cksum);
12736 
12737 		IP_CKSUM_RECV(hck_flags, u1,
12738 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12739 		    (int32_t)((uchar_t *)up - rptr),
12740 		    mp, mp1, cksum_err);
12741 
12742 		if (cksum_err) {
12743 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12744 			if (hck_flags & HCK_FULLCKSUM)
12745 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12746 			else if (hck_flags & HCK_PARTIALCKSUM)
12747 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12748 			else
12749 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12750 
12751 			freemsg(first_mp);
12752 			return;
12753 		}
12754 	}
12755 
12756 	/* Non-fragmented broadcast or multicast packet? */
12757 	if (ire->ire_type == IRE_BROADCAST)
12758 		goto udpslowpath;
12759 
12760 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12761 	    ire->ire_zoneid, ipst)) != NULL) {
12762 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12763 		IP_STAT(ipst, ip_udp_fast_path);
12764 
12765 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12766 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12767 			freemsg(mp);
12768 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12769 		} else {
12770 			if (!mctl_present) {
12771 				BUMP_MIB(ill->ill_ip_mib,
12772 				    ipIfStatsHCInDelivers);
12773 			}
12774 			/*
12775 			 * mp and first_mp can change.
12776 			 */
12777 			if (ip_udp_check(q, connp, recv_ill,
12778 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12779 				/* Send it upstream */
12780 				(connp->conn_recv)(connp, mp, NULL);
12781 			}
12782 		}
12783 		/*
12784 		 * freeb() cannot deal with null mblk being passed
12785 		 * in and first_mp can be set to null in the call
12786 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12787 		 */
12788 		if (mctl_present && first_mp != NULL) {
12789 			freeb(first_mp);
12790 		}
12791 		CONN_DEC_REF(connp);
12792 		return;
12793 	}
12794 
12795 	/*
12796 	 * if we got here we know the packet is not fragmented and
12797 	 * has no options. The classifier could not find a conn_t and
12798 	 * most likely its an icmp packet so send it through slow path.
12799 	 */
12800 
12801 	goto udpslowpath;
12802 
12803 ipoptions:
12804 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12805 		goto slow_done;
12806 	}
12807 
12808 	UPDATE_IB_PKT_COUNT(ire);
12809 	ire->ire_last_used_time = lbolt;
12810 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12811 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12812 fragmented:
12813 		/*
12814 		 * "sum" and "reass_hck_flags" are non-zero if the
12815 		 * reassembled packet has a valid hardware computed
12816 		 * checksum information associated with it.
12817 		 */
12818 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12819 		    &reass_hck_flags)) {
12820 			goto slow_done;
12821 		}
12822 
12823 		/*
12824 		 * Make sure that first_mp points back to mp as
12825 		 * the mp we came in with could have changed in
12826 		 * ip_rput_fragment().
12827 		 */
12828 		ASSERT(!mctl_present);
12829 		ipha = (ipha_t *)mp->b_rptr;
12830 		first_mp = mp;
12831 	}
12832 
12833 	/* Now we have a complete datagram, destined for this machine. */
12834 	u1 = IPH_HDR_LENGTH(ipha);
12835 	/* Pull up the UDP header, if necessary. */
12836 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12837 udppullup:
12838 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12839 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12840 			freemsg(first_mp);
12841 			goto slow_done;
12842 		}
12843 		ipha = (ipha_t *)mp->b_rptr;
12844 	}
12845 
12846 	/*
12847 	 * Validate the checksum for the reassembled packet; for the
12848 	 * pullup case we calculate the payload checksum in software.
12849 	 */
12850 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12851 	if (up[3] != 0) {
12852 		boolean_t cksum_err;
12853 
12854 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12855 			IP_STAT(ipst, ip_in_sw_cksum);
12856 
12857 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12858 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12859 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12860 		    iphs[9] + up[2], sum, cksum_err);
12861 
12862 		if (cksum_err) {
12863 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12864 
12865 			if (reass_hck_flags & HCK_FULLCKSUM)
12866 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12867 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12868 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12869 			else
12870 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12871 
12872 			freemsg(first_mp);
12873 			goto slow_done;
12874 		}
12875 	}
12876 udpslowpath:
12877 
12878 	/* Clear hardware checksum flag to be safe */
12879 	DB_CKSUMFLAGS(mp) = 0;
12880 
12881 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12882 	    (ire->ire_type == IRE_BROADCAST),
12883 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12884 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12885 
12886 slow_done:
12887 	IP_STAT(ipst, ip_udp_slow_path);
12888 	return;
12889 
12890 #undef  iphs
12891 #undef  rptr
12892 }
12893 
12894 /* ARGSUSED */
12895 static mblk_t *
12896 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12897     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12898     ill_rx_ring_t *ill_ring)
12899 {
12900 	conn_t		*connp;
12901 	uint32_t	sum;
12902 	uint32_t	u1;
12903 	uint16_t	*up;
12904 	int		offset;
12905 	ssize_t		len;
12906 	mblk_t		*mp1;
12907 	boolean_t	syn_present = B_FALSE;
12908 	tcph_t		*tcph;
12909 	uint_t		tcph_flags;
12910 	uint_t		ip_hdr_len;
12911 	ill_t		*ill = (ill_t *)q->q_ptr;
12912 	zoneid_t	zoneid = ire->ire_zoneid;
12913 	boolean_t	cksum_err;
12914 	uint16_t	hck_flags = 0;
12915 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12916 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12917 
12918 #define	rptr	((uchar_t *)ipha)
12919 
12920 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12921 	ASSERT(ill != NULL);
12922 
12923 	/*
12924 	 * FAST PATH for tcp packets
12925 	 */
12926 
12927 	/* u1 is # words of IP options */
12928 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12929 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12930 
12931 	/* IP options present */
12932 	if (u1) {
12933 		goto ipoptions;
12934 	} else if (!mctl_present) {
12935 		/* Check the IP header checksum.  */
12936 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12937 			/* Clear the IP header h/w cksum flag */
12938 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12939 		} else if (!mctl_present) {
12940 			/*
12941 			 * Don't verify header checksum if this packet
12942 			 * is coming back from AH/ESP as we already did it.
12943 			 */
12944 #define	uph	((uint16_t *)ipha)
12945 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12946 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12947 #undef	uph
12948 			/* finish doing IP checksum */
12949 			sum = (sum & 0xFFFF) + (sum >> 16);
12950 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12951 			if (sum != 0 && sum != 0xFFFF) {
12952 				BUMP_MIB(ill->ill_ip_mib,
12953 				    ipIfStatsInCksumErrs);
12954 				goto error;
12955 			}
12956 		}
12957 	}
12958 
12959 	if (!mctl_present) {
12960 		UPDATE_IB_PKT_COUNT(ire);
12961 		ire->ire_last_used_time = lbolt;
12962 	}
12963 
12964 	/* packet part of fragmented IP packet? */
12965 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12966 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12967 		goto fragmented;
12968 	}
12969 
12970 	/* u1 = IP header length (20 bytes) */
12971 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12972 
12973 	/* does packet contain IP+TCP headers? */
12974 	len = mp->b_wptr - rptr;
12975 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12976 		IP_STAT(ipst, ip_tcppullup);
12977 		goto tcppullup;
12978 	}
12979 
12980 	/* TCP options present? */
12981 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12982 
12983 	/*
12984 	 * If options need to be pulled up, then goto tcpoptions.
12985 	 * otherwise we are still in the fast path
12986 	 */
12987 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12988 		IP_STAT(ipst, ip_tcpoptions);
12989 		goto tcpoptions;
12990 	}
12991 
12992 	/* multiple mblks of tcp data? */
12993 	if ((mp1 = mp->b_cont) != NULL) {
12994 		IP_STAT(ipst, ip_multipkttcp);
12995 		len += msgdsize(mp1);
12996 	}
12997 
12998 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12999 
13000 	/* part of pseudo checksum */
13001 
13002 	/* TCP datagram length */
13003 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13004 
13005 #define	iphs    ((uint16_t *)ipha)
13006 
13007 #ifdef	_BIG_ENDIAN
13008 	u1 += IPPROTO_TCP;
13009 #else
13010 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13011 #endif
13012 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13013 
13014 	/*
13015 	 * Revert to software checksum calculation if the interface
13016 	 * isn't capable of checksum offload or if IPsec is present.
13017 	 */
13018 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
13019 		hck_flags = DB_CKSUMFLAGS(mp);
13020 
13021 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13022 		IP_STAT(ipst, ip_in_sw_cksum);
13023 
13024 	IP_CKSUM_RECV(hck_flags, u1,
13025 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13026 	    (int32_t)((uchar_t *)up - rptr),
13027 	    mp, mp1, cksum_err);
13028 
13029 	if (cksum_err) {
13030 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13031 
13032 		if (hck_flags & HCK_FULLCKSUM)
13033 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13034 		else if (hck_flags & HCK_PARTIALCKSUM)
13035 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13036 		else
13037 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13038 
13039 		goto error;
13040 	}
13041 
13042 try_again:
13043 
13044 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13045 	    zoneid, ipst)) == NULL) {
13046 		/* Send the TH_RST */
13047 		goto no_conn;
13048 	}
13049 
13050 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13051 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13052 
13053 	/*
13054 	 * TCP FAST PATH for AF_INET socket.
13055 	 *
13056 	 * TCP fast path to avoid extra work. An AF_INET socket type
13057 	 * does not have facility to receive extra information via
13058 	 * ip_process or ip_add_info. Also, when the connection was
13059 	 * established, we made a check if this connection is impacted
13060 	 * by any global IPsec policy or per connection policy (a
13061 	 * policy that comes in effect later will not apply to this
13062 	 * connection). Since all this can be determined at the
13063 	 * connection establishment time, a quick check of flags
13064 	 * can avoid extra work.
13065 	 */
13066 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13067 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13068 		ASSERT(first_mp == mp);
13069 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13070 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13071 			SET_SQUEUE(mp, tcp_rput_data, connp);
13072 			return (mp);
13073 		}
13074 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13075 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13076 		SET_SQUEUE(mp, tcp_input, connp);
13077 		return (mp);
13078 	}
13079 
13080 	if (tcph_flags == TH_SYN) {
13081 		if (IPCL_IS_TCP(connp)) {
13082 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13083 			DB_CKSUMSTART(mp) =
13084 			    (intptr_t)ip_squeue_get(ill_ring);
13085 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13086 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13087 				BUMP_MIB(ill->ill_ip_mib,
13088 				    ipIfStatsHCInDelivers);
13089 				SET_SQUEUE(mp, connp->conn_recv, connp);
13090 				return (mp);
13091 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13092 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13093 				BUMP_MIB(ill->ill_ip_mib,
13094 				    ipIfStatsHCInDelivers);
13095 				ip_squeue_enter_unbound++;
13096 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13097 				    connp);
13098 				return (mp);
13099 			}
13100 			syn_present = B_TRUE;
13101 		}
13102 	}
13103 
13104 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13105 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13106 
13107 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13108 		/* No need to send this packet to TCP */
13109 		if ((flags & TH_RST) || (flags & TH_URG)) {
13110 			CONN_DEC_REF(connp);
13111 			freemsg(first_mp);
13112 			return (NULL);
13113 		}
13114 		if (flags & TH_ACK) {
13115 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13116 			    ipst->ips_netstack->netstack_tcp, connp);
13117 			CONN_DEC_REF(connp);
13118 			return (NULL);
13119 		}
13120 
13121 		CONN_DEC_REF(connp);
13122 		freemsg(first_mp);
13123 		return (NULL);
13124 	}
13125 
13126 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13127 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13128 		    ipha, NULL, mctl_present);
13129 		if (first_mp == NULL) {
13130 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13131 			CONN_DEC_REF(connp);
13132 			return (NULL);
13133 		}
13134 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13135 			ASSERT(syn_present);
13136 			if (mctl_present) {
13137 				ASSERT(first_mp != mp);
13138 				first_mp->b_datap->db_struioflag |=
13139 				    STRUIO_POLICY;
13140 			} else {
13141 				ASSERT(first_mp == mp);
13142 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13143 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13144 			}
13145 		} else {
13146 			/*
13147 			 * Discard first_mp early since we're dealing with a
13148 			 * fully-connected conn_t and tcp doesn't do policy in
13149 			 * this case.
13150 			 */
13151 			if (mctl_present) {
13152 				freeb(first_mp);
13153 				mctl_present = B_FALSE;
13154 			}
13155 			first_mp = mp;
13156 		}
13157 	}
13158 
13159 	/* Initiate IPPF processing for fastpath */
13160 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13161 		uint32_t	ill_index;
13162 
13163 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13164 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13165 		if (mp == NULL) {
13166 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13167 			    "deferred/dropped during IPPF processing\n"));
13168 			CONN_DEC_REF(connp);
13169 			if (mctl_present)
13170 				freeb(first_mp);
13171 			return (NULL);
13172 		} else if (mctl_present) {
13173 			/*
13174 			 * ip_process might return a new mp.
13175 			 */
13176 			ASSERT(first_mp != mp);
13177 			first_mp->b_cont = mp;
13178 		} else {
13179 			first_mp = mp;
13180 		}
13181 
13182 	}
13183 
13184 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13185 		/*
13186 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13187 		 * make sure IPF_RECVIF is passed to ip_add_info.
13188 		 */
13189 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13190 		    IPCL_ZONEID(connp), ipst);
13191 		if (mp == NULL) {
13192 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13193 			CONN_DEC_REF(connp);
13194 			if (mctl_present)
13195 				freeb(first_mp);
13196 			return (NULL);
13197 		} else if (mctl_present) {
13198 			/*
13199 			 * ip_add_info might return a new mp.
13200 			 */
13201 			ASSERT(first_mp != mp);
13202 			first_mp->b_cont = mp;
13203 		} else {
13204 			first_mp = mp;
13205 		}
13206 	}
13207 
13208 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13209 	if (IPCL_IS_TCP(connp)) {
13210 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13211 		return (first_mp);
13212 	} else {
13213 		/* SOCK_RAW, IPPROTO_TCP case */
13214 		(connp->conn_recv)(connp, first_mp, NULL);
13215 		CONN_DEC_REF(connp);
13216 		return (NULL);
13217 	}
13218 
13219 no_conn:
13220 	/* Initiate IPPf processing, if needed. */
13221 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13222 		uint32_t ill_index;
13223 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13224 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13225 		if (first_mp == NULL) {
13226 			return (NULL);
13227 		}
13228 	}
13229 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13230 
13231 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13232 	    ipst->ips_netstack->netstack_tcp, NULL);
13233 	return (NULL);
13234 ipoptions:
13235 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13236 		goto slow_done;
13237 	}
13238 
13239 	UPDATE_IB_PKT_COUNT(ire);
13240 	ire->ire_last_used_time = lbolt;
13241 
13242 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13243 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13244 fragmented:
13245 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13246 			if (mctl_present)
13247 				freeb(first_mp);
13248 			goto slow_done;
13249 		}
13250 		/*
13251 		 * Make sure that first_mp points back to mp as
13252 		 * the mp we came in with could have changed in
13253 		 * ip_rput_fragment().
13254 		 */
13255 		ASSERT(!mctl_present);
13256 		ipha = (ipha_t *)mp->b_rptr;
13257 		first_mp = mp;
13258 	}
13259 
13260 	/* Now we have a complete datagram, destined for this machine. */
13261 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13262 
13263 	len = mp->b_wptr - mp->b_rptr;
13264 	/* Pull up a minimal TCP header, if necessary. */
13265 	if (len < (u1 + 20)) {
13266 tcppullup:
13267 		if (!pullupmsg(mp, u1 + 20)) {
13268 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13269 			goto error;
13270 		}
13271 		ipha = (ipha_t *)mp->b_rptr;
13272 		len = mp->b_wptr - mp->b_rptr;
13273 	}
13274 
13275 	/*
13276 	 * Extract the offset field from the TCP header.  As usual, we
13277 	 * try to help the compiler more than the reader.
13278 	 */
13279 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13280 	if (offset != 5) {
13281 tcpoptions:
13282 		if (offset < 5) {
13283 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13284 			goto error;
13285 		}
13286 		/*
13287 		 * There must be TCP options.
13288 		 * Make sure we can grab them.
13289 		 */
13290 		offset <<= 2;
13291 		offset += u1;
13292 		if (len < offset) {
13293 			if (!pullupmsg(mp, offset)) {
13294 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13295 				goto error;
13296 			}
13297 			ipha = (ipha_t *)mp->b_rptr;
13298 			len = mp->b_wptr - rptr;
13299 		}
13300 	}
13301 
13302 	/* Get the total packet length in len, including headers. */
13303 	if (mp->b_cont)
13304 		len = msgdsize(mp);
13305 
13306 	/*
13307 	 * Check the TCP checksum by pulling together the pseudo-
13308 	 * header checksum, and passing it to ip_csum to be added in
13309 	 * with the TCP datagram.
13310 	 *
13311 	 * Since we are not using the hwcksum if available we must
13312 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13313 	 * If either of these fails along the way the mblk is freed.
13314 	 * If this logic ever changes and mblk is reused to say send
13315 	 * ICMP's back, then this flag may need to be cleared in
13316 	 * other places as well.
13317 	 */
13318 	DB_CKSUMFLAGS(mp) = 0;
13319 
13320 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13321 
13322 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13323 #ifdef	_BIG_ENDIAN
13324 	u1 += IPPROTO_TCP;
13325 #else
13326 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13327 #endif
13328 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13329 	/*
13330 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13331 	 */
13332 	IP_STAT(ipst, ip_in_sw_cksum);
13333 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13334 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13335 		goto error;
13336 	}
13337 
13338 	IP_STAT(ipst, ip_tcp_slow_path);
13339 	goto try_again;
13340 #undef  iphs
13341 #undef  rptr
13342 
13343 error:
13344 	freemsg(first_mp);
13345 slow_done:
13346 	return (NULL);
13347 }
13348 
13349 /* ARGSUSED */
13350 static void
13351 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13352     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13353 {
13354 	conn_t		*connp;
13355 	uint32_t	sum;
13356 	uint32_t	u1;
13357 	ssize_t		len;
13358 	sctp_hdr_t	*sctph;
13359 	zoneid_t	zoneid = ire->ire_zoneid;
13360 	uint32_t	pktsum;
13361 	uint32_t	calcsum;
13362 	uint32_t	ports;
13363 	in6_addr_t	map_src, map_dst;
13364 	ill_t		*ill = (ill_t *)q->q_ptr;
13365 	ip_stack_t	*ipst;
13366 	sctp_stack_t	*sctps;
13367 	boolean_t	sctp_csum_err = B_FALSE;
13368 
13369 	ASSERT(recv_ill != NULL);
13370 	ipst = recv_ill->ill_ipst;
13371 	sctps = ipst->ips_netstack->netstack_sctp;
13372 
13373 #define	rptr	((uchar_t *)ipha)
13374 
13375 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13376 	ASSERT(ill != NULL);
13377 
13378 	/* u1 is # words of IP options */
13379 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13380 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13381 
13382 	/* IP options present */
13383 	if (u1 > 0) {
13384 		goto ipoptions;
13385 	} else {
13386 		/* Check the IP header checksum.  */
13387 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13388 		    !mctl_present) {
13389 #define	uph	((uint16_t *)ipha)
13390 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13391 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13392 #undef	uph
13393 			/* finish doing IP checksum */
13394 			sum = (sum & 0xFFFF) + (sum >> 16);
13395 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13396 			/*
13397 			 * Don't verify header checksum if this packet
13398 			 * is coming back from AH/ESP as we already did it.
13399 			 */
13400 			if (sum != 0 && sum != 0xFFFF) {
13401 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13402 				goto error;
13403 			}
13404 		}
13405 		/*
13406 		 * Since there is no SCTP h/w cksum support yet, just
13407 		 * clear the flag.
13408 		 */
13409 		DB_CKSUMFLAGS(mp) = 0;
13410 	}
13411 
13412 	/*
13413 	 * Don't verify header checksum if this packet is coming
13414 	 * back from AH/ESP as we already did it.
13415 	 */
13416 	if (!mctl_present) {
13417 		UPDATE_IB_PKT_COUNT(ire);
13418 		ire->ire_last_used_time = lbolt;
13419 	}
13420 
13421 	/* packet part of fragmented IP packet? */
13422 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13423 	if (u1 & (IPH_MF | IPH_OFFSET))
13424 		goto fragmented;
13425 
13426 	/* u1 = IP header length (20 bytes) */
13427 	u1 = IP_SIMPLE_HDR_LENGTH;
13428 
13429 find_sctp_client:
13430 	/* Pullup if we don't have the sctp common header. */
13431 	len = MBLKL(mp);
13432 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13433 		if (mp->b_cont == NULL ||
13434 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13435 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13436 			goto error;
13437 		}
13438 		ipha = (ipha_t *)mp->b_rptr;
13439 		len = MBLKL(mp);
13440 	}
13441 
13442 	sctph = (sctp_hdr_t *)(rptr + u1);
13443 #ifdef	DEBUG
13444 	if (!skip_sctp_cksum) {
13445 #endif
13446 		pktsum = sctph->sh_chksum;
13447 		sctph->sh_chksum = 0;
13448 		calcsum = sctp_cksum(mp, u1);
13449 		sctph->sh_chksum = pktsum;
13450 		if (calcsum != pktsum)
13451 			sctp_csum_err = B_TRUE;
13452 #ifdef	DEBUG	/* skip_sctp_cksum */
13453 	}
13454 #endif
13455 	/* get the ports */
13456 	ports = *(uint32_t *)&sctph->sh_sport;
13457 
13458 	IRE_REFRELE(ire);
13459 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13460 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13461 	if (sctp_csum_err) {
13462 		/*
13463 		 * No potential sctp checksum errors go to the Sun
13464 		 * sctp stack however they might be Adler-32 summed
13465 		 * packets a userland stack bound to a raw IP socket
13466 		 * could reasonably use. Note though that Adler-32 is
13467 		 * a long deprecated algorithm and customer sctp
13468 		 * networks should eventually migrate to CRC-32 at
13469 		 * which time this facility should be removed.
13470 		 */
13471 		flags |= IP_FF_SCTP_CSUM_ERR;
13472 		goto no_conn;
13473 	}
13474 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13475 	    sctps)) == NULL) {
13476 		/* Check for raw socket or OOTB handling */
13477 		goto no_conn;
13478 	}
13479 
13480 	/* Found a client; up it goes */
13481 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13482 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13483 	return;
13484 
13485 no_conn:
13486 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13487 	    ports, mctl_present, flags, B_TRUE, zoneid);
13488 	return;
13489 
13490 ipoptions:
13491 	DB_CKSUMFLAGS(mp) = 0;
13492 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13493 		goto slow_done;
13494 
13495 	UPDATE_IB_PKT_COUNT(ire);
13496 	ire->ire_last_used_time = lbolt;
13497 
13498 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13499 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13500 fragmented:
13501 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13502 			goto slow_done;
13503 		/*
13504 		 * Make sure that first_mp points back to mp as
13505 		 * the mp we came in with could have changed in
13506 		 * ip_rput_fragment().
13507 		 */
13508 		ASSERT(!mctl_present);
13509 		ipha = (ipha_t *)mp->b_rptr;
13510 		first_mp = mp;
13511 	}
13512 
13513 	/* Now we have a complete datagram, destined for this machine. */
13514 	u1 = IPH_HDR_LENGTH(ipha);
13515 	goto find_sctp_client;
13516 #undef  iphs
13517 #undef  rptr
13518 
13519 error:
13520 	freemsg(first_mp);
13521 slow_done:
13522 	IRE_REFRELE(ire);
13523 }
13524 
13525 #define	VER_BITS	0xF0
13526 #define	VERSION_6	0x60
13527 
13528 static boolean_t
13529 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13530     ipaddr_t *dstp, ip_stack_t *ipst)
13531 {
13532 	uint_t	opt_len;
13533 	ipha_t *ipha;
13534 	ssize_t len;
13535 	uint_t	pkt_len;
13536 
13537 	ASSERT(ill != NULL);
13538 	IP_STAT(ipst, ip_ipoptions);
13539 	ipha = *iphapp;
13540 
13541 #define	rptr    ((uchar_t *)ipha)
13542 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13543 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13544 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13545 		freemsg(mp);
13546 		return (B_FALSE);
13547 	}
13548 
13549 	/* multiple mblk or too short */
13550 	pkt_len = ntohs(ipha->ipha_length);
13551 
13552 	/* Get the number of words of IP options in the IP header. */
13553 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13554 	if (opt_len) {
13555 		/* IP Options present!  Validate and process. */
13556 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13557 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13558 			goto done;
13559 		}
13560 		/*
13561 		 * Recompute complete header length and make sure we
13562 		 * have access to all of it.
13563 		 */
13564 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13565 		if (len > (mp->b_wptr - rptr)) {
13566 			if (len > pkt_len) {
13567 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13568 				goto done;
13569 			}
13570 			if (!pullupmsg(mp, len)) {
13571 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13572 				goto done;
13573 			}
13574 			ipha = (ipha_t *)mp->b_rptr;
13575 		}
13576 		/*
13577 		 * Go off to ip_rput_options which returns the next hop
13578 		 * destination address, which may have been affected
13579 		 * by source routing.
13580 		 */
13581 		IP_STAT(ipst, ip_opt);
13582 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13583 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13584 			return (B_FALSE);
13585 		}
13586 	}
13587 	*iphapp = ipha;
13588 	return (B_TRUE);
13589 done:
13590 	/* clear b_prev - used by ip_mroute_decap */
13591 	mp->b_prev = NULL;
13592 	freemsg(mp);
13593 	return (B_FALSE);
13594 #undef  rptr
13595 }
13596 
13597 /*
13598  * Deal with the fact that there is no ire for the destination.
13599  */
13600 static ire_t *
13601 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13602 {
13603 	ipha_t	*ipha;
13604 	ill_t	*ill;
13605 	ire_t	*ire;
13606 	ip_stack_t *ipst;
13607 	enum	ire_forward_action ret_action;
13608 
13609 	ipha = (ipha_t *)mp->b_rptr;
13610 	ill = (ill_t *)q->q_ptr;
13611 
13612 	ASSERT(ill != NULL);
13613 	ipst = ill->ill_ipst;
13614 
13615 	/*
13616 	 * No IRE for this destination, so it can't be for us.
13617 	 * Unless we are forwarding, drop the packet.
13618 	 * We have to let source routed packets through
13619 	 * since we don't yet know if they are 'ping -l'
13620 	 * packets i.e. if they will go out over the
13621 	 * same interface as they came in on.
13622 	 */
13623 	if (ll_multicast) {
13624 		freemsg(mp);
13625 		return (NULL);
13626 	}
13627 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13628 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13629 		freemsg(mp);
13630 		return (NULL);
13631 	}
13632 
13633 	/*
13634 	 * Mark this packet as having originated externally.
13635 	 *
13636 	 * For non-forwarding code path, ire_send later double
13637 	 * checks this interface to see if it is still exists
13638 	 * post-ARP resolution.
13639 	 *
13640 	 * Also, IPQOS uses this to differentiate between
13641 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13642 	 * QOS packet processing in ip_wput_attach_llhdr().
13643 	 * The QoS module can mark the b_band for a fastpath message
13644 	 * or the dl_priority field in a unitdata_req header for
13645 	 * CoS marking. This info can only be found in
13646 	 * ip_wput_attach_llhdr().
13647 	 */
13648 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13649 	/*
13650 	 * Clear the indication that this may have a hardware checksum
13651 	 * as we are not using it
13652 	 */
13653 	DB_CKSUMFLAGS(mp) = 0;
13654 
13655 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13656 	    msg_getlabel(mp), ipst);
13657 
13658 	if (ire == NULL && ret_action == Forward_check_multirt) {
13659 		/* Let ip_newroute handle CGTP  */
13660 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13661 		return (NULL);
13662 	}
13663 
13664 	if (ire != NULL)
13665 		return (ire);
13666 
13667 	mp->b_prev = mp->b_next = 0;
13668 
13669 	if (ret_action == Forward_blackhole) {
13670 		freemsg(mp);
13671 		return (NULL);
13672 	}
13673 	/* send icmp unreachable */
13674 	q = WR(q);
13675 	/* Sent by forwarding path, and router is global zone */
13676 	if (ip_source_routed(ipha, ipst)) {
13677 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13678 		    GLOBAL_ZONEID, ipst);
13679 	} else {
13680 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13681 		    ipst);
13682 	}
13683 
13684 	return (NULL);
13685 
13686 }
13687 
13688 /*
13689  * check ip header length and align it.
13690  */
13691 static boolean_t
13692 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13693 {
13694 	ssize_t len;
13695 	ill_t *ill;
13696 	ipha_t	*ipha;
13697 
13698 	len = MBLKL(mp);
13699 
13700 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13701 		ill = (ill_t *)q->q_ptr;
13702 
13703 		if (!OK_32PTR(mp->b_rptr))
13704 			IP_STAT(ipst, ip_notaligned1);
13705 		else
13706 			IP_STAT(ipst, ip_notaligned2);
13707 		/* Guard against bogus device drivers */
13708 		if (len < 0) {
13709 			/* clear b_prev - used by ip_mroute_decap */
13710 			mp->b_prev = NULL;
13711 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13712 			freemsg(mp);
13713 			return (B_FALSE);
13714 		}
13715 
13716 		if (ip_rput_pullups++ == 0) {
13717 			ipha = (ipha_t *)mp->b_rptr;
13718 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13719 			    "ip_check_and_align_header: %s forced us to "
13720 			    " pullup pkt, hdr len %ld, hdr addr %p",
13721 			    ill->ill_name, len, (void *)ipha);
13722 		}
13723 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13724 			/* clear b_prev - used by ip_mroute_decap */
13725 			mp->b_prev = NULL;
13726 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13727 			freemsg(mp);
13728 			return (B_FALSE);
13729 		}
13730 	}
13731 	return (B_TRUE);
13732 }
13733 
13734 /*
13735  * Handle the situation where a packet came in on `ill' but matched an IRE
13736  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13737  * for interface statistics.
13738  */
13739 ire_t *
13740 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13741 {
13742 	ire_t		*new_ire;
13743 	ill_t		*ire_ill;
13744 	uint_t		ifindex;
13745 	ip_stack_t	*ipst = ill->ill_ipst;
13746 	boolean_t	strict_check = B_FALSE;
13747 
13748 	/*
13749 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13750 	 * issue (e.g. packet received on an underlying interface matched an
13751 	 * IRE_LOCAL on its associated group interface).
13752 	 */
13753 	if (ire->ire_rfq != NULL &&
13754 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13755 		return (ire);
13756 	}
13757 
13758 	/*
13759 	 * Do another ire lookup here, using the ingress ill, to see if the
13760 	 * interface is in a usesrc group.
13761 	 * As long as the ills belong to the same group, we don't consider
13762 	 * them to be arriving on the wrong interface. Thus, if the switch
13763 	 * is doing inbound load spreading, we won't drop packets when the
13764 	 * ip*_strict_dst_multihoming switch is on.
13765 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13766 	 * where the local address may not be unique. In this case we were
13767 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13768 	 * actually returned. The new lookup, which is more specific, should
13769 	 * only find the IRE_LOCAL associated with the ingress ill if one
13770 	 * exists.
13771 	 */
13772 
13773 	if (ire->ire_ipversion == IPV4_VERSION) {
13774 		if (ipst->ips_ip_strict_dst_multihoming)
13775 			strict_check = B_TRUE;
13776 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13777 		    ill->ill_ipif, ALL_ZONES, NULL,
13778 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13779 	} else {
13780 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13781 		if (ipst->ips_ipv6_strict_dst_multihoming)
13782 			strict_check = B_TRUE;
13783 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13784 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13785 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13786 	}
13787 	/*
13788 	 * If the same ire that was returned in ip_input() is found then this
13789 	 * is an indication that usesrc groups are in use. The packet
13790 	 * arrived on a different ill in the group than the one associated with
13791 	 * the destination address.  If a different ire was found then the same
13792 	 * IP address must be hosted on multiple ills. This is possible with
13793 	 * unnumbered point2point interfaces. We switch to use this new ire in
13794 	 * order to have accurate interface statistics.
13795 	 */
13796 	if (new_ire != NULL) {
13797 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13798 			ire_refrele(ire);
13799 			ire = new_ire;
13800 		} else {
13801 			ire_refrele(new_ire);
13802 		}
13803 		return (ire);
13804 	} else if ((ire->ire_rfq == NULL) &&
13805 	    (ire->ire_ipversion == IPV4_VERSION)) {
13806 		/*
13807 		 * The best match could have been the original ire which
13808 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13809 		 * the strict multihoming checks are irrelevant as we consider
13810 		 * local addresses hosted on lo0 to be interface agnostic. We
13811 		 * only expect a null ire_rfq on IREs which are associated with
13812 		 * lo0 hence we can return now.
13813 		 */
13814 		return (ire);
13815 	}
13816 
13817 	/*
13818 	 * Chase pointers once and store locally.
13819 	 */
13820 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13821 	    (ill_t *)(ire->ire_rfq->q_ptr);
13822 	ifindex = ill->ill_usesrc_ifindex;
13823 
13824 	/*
13825 	 * Check if it's a legal address on the 'usesrc' interface.
13826 	 */
13827 	if ((ifindex != 0) && (ire_ill != NULL) &&
13828 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13829 		return (ire);
13830 	}
13831 
13832 	/*
13833 	 * If the ip*_strict_dst_multihoming switch is on then we can
13834 	 * only accept this packet if the interface is marked as routing.
13835 	 */
13836 	if (!(strict_check))
13837 		return (ire);
13838 
13839 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13840 	    ILLF_ROUTER) != 0) {
13841 		return (ire);
13842 	}
13843 
13844 	ire_refrele(ire);
13845 	return (NULL);
13846 }
13847 
13848 /*
13849  *
13850  * This is the fast forward path. If we are here, we dont need to
13851  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13852  * needed to find the nexthop in this case is much simpler
13853  */
13854 ire_t *
13855 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13856 {
13857 	ipha_t	*ipha;
13858 	ire_t	*src_ire;
13859 	ill_t	*stq_ill;
13860 	uint_t	hlen;
13861 	uint_t	pkt_len;
13862 	uint32_t sum;
13863 	queue_t	*dev_q;
13864 	ip_stack_t *ipst = ill->ill_ipst;
13865 	mblk_t *fpmp;
13866 	enum	ire_forward_action ret_action;
13867 
13868 	ipha = (ipha_t *)mp->b_rptr;
13869 
13870 	if (ire != NULL &&
13871 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13872 	    ire->ire_zoneid != ALL_ZONES) {
13873 		/*
13874 		 * Should only use IREs that are visible to the global
13875 		 * zone for forwarding.
13876 		 */
13877 		ire_refrele(ire);
13878 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13879 		/*
13880 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13881 		 * transient cases. In such case, just drop the packet
13882 		 */
13883 		if (ire->ire_type != IRE_CACHE)
13884 			goto drop;
13885 	}
13886 
13887 	/*
13888 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13889 	 * The loopback address check for both src and dst has already
13890 	 * been checked in ip_input
13891 	 */
13892 
13893 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13894 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13895 		goto drop;
13896 	}
13897 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13898 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13899 
13900 	if (src_ire != NULL) {
13901 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13902 		ire_refrele(src_ire);
13903 		goto drop;
13904 	}
13905 
13906 	/* No ire cache of nexthop. So first create one  */
13907 	if (ire == NULL) {
13908 
13909 		ire = ire_forward_simple(dst, &ret_action, ipst);
13910 
13911 		/*
13912 		 * We only come to ip_fast_forward if ip_cgtp_filter
13913 		 * is not set. So ire_forward() should not return with
13914 		 * Forward_check_multirt as the next action.
13915 		 */
13916 		ASSERT(ret_action != Forward_check_multirt);
13917 		if (ire == NULL) {
13918 			/* An attempt was made to forward the packet */
13919 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13920 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13921 			mp->b_prev = mp->b_next = 0;
13922 			/* send icmp unreachable */
13923 			/* Sent by forwarding path, and router is global zone */
13924 			if (ret_action == Forward_ret_icmp_err) {
13925 				if (ip_source_routed(ipha, ipst)) {
13926 					icmp_unreachable(ill->ill_wq, mp,
13927 					    ICMP_SOURCE_ROUTE_FAILED,
13928 					    GLOBAL_ZONEID, ipst);
13929 				} else {
13930 					icmp_unreachable(ill->ill_wq, mp,
13931 					    ICMP_HOST_UNREACHABLE,
13932 					    GLOBAL_ZONEID, ipst);
13933 				}
13934 			} else {
13935 				freemsg(mp);
13936 			}
13937 			return (NULL);
13938 		}
13939 	}
13940 
13941 	/*
13942 	 * Forwarding fastpath exception case:
13943 	 * If any of the following are true, we take the slowpath:
13944 	 *	o forwarding is not enabled
13945 	 *	o incoming and outgoing interface are the same, or in the same
13946 	 *	  IPMP group.
13947 	 *	o corresponding ire is in incomplete state
13948 	 *	o packet needs fragmentation
13949 	 *	o ARP cache is not resolved
13950 	 *
13951 	 * The codeflow from here on is thus:
13952 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13953 	 */
13954 	pkt_len = ntohs(ipha->ipha_length);
13955 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13956 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13957 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13958 	    (ire->ire_nce == NULL) ||
13959 	    (pkt_len > ire->ire_max_frag) ||
13960 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13961 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13962 	    ipha->ipha_ttl <= 1) {
13963 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13964 		    ipha, ill, B_FALSE, B_TRUE);
13965 		return (ire);
13966 	}
13967 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13968 
13969 	DTRACE_PROBE4(ip4__forwarding__start,
13970 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13971 
13972 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13973 	    ipst->ips_ipv4firewall_forwarding,
13974 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13975 
13976 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13977 
13978 	if (mp == NULL)
13979 		goto drop;
13980 
13981 	mp->b_datap->db_struioun.cksum.flags = 0;
13982 	/* Adjust the checksum to reflect the ttl decrement. */
13983 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13984 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13985 	ipha->ipha_ttl--;
13986 
13987 	/*
13988 	 * Write the link layer header.  We can do this safely here,
13989 	 * because we have already tested to make sure that the IP
13990 	 * policy is not set, and that we have a fast path destination
13991 	 * header.
13992 	 */
13993 	mp->b_rptr -= hlen;
13994 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13995 
13996 	UPDATE_IB_PKT_COUNT(ire);
13997 	ire->ire_last_used_time = lbolt;
13998 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13999 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14000 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14001 
14002 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14003 		dev_q = ire->ire_stq->q_next;
14004 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14005 			goto indiscard;
14006 	}
14007 
14008 	DTRACE_PROBE4(ip4__physical__out__start,
14009 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14010 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14011 	    ipst->ips_ipv4firewall_physical_out,
14012 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14013 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14014 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14015 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14016 	    ip6_t *, NULL, int, 0);
14017 
14018 	if (mp != NULL) {
14019 		if (ipst->ips_ipobs_enabled) {
14020 			zoneid_t szone;
14021 
14022 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14023 			    ipst, ALL_ZONES);
14024 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14025 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14026 		}
14027 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
14028 	}
14029 	return (ire);
14030 
14031 indiscard:
14032 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14033 drop:
14034 	if (mp != NULL)
14035 		freemsg(mp);
14036 	return (ire);
14037 
14038 }
14039 
14040 /*
14041  * This function is called in the forwarding slowpath, when
14042  * either the ire lacks the link-layer address, or the packet needs
14043  * further processing(eg. fragmentation), before transmission.
14044  */
14045 
14046 static void
14047 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14048     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14049 {
14050 	queue_t		*dev_q;
14051 	ire_t		*src_ire;
14052 	ip_stack_t	*ipst = ill->ill_ipst;
14053 	boolean_t	same_illgrp = B_FALSE;
14054 
14055 	ASSERT(ire->ire_stq != NULL);
14056 
14057 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14058 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14059 
14060 	/*
14061 	 * If the caller of this function is ip_fast_forward() skip the
14062 	 * next three checks as it does not apply.
14063 	 */
14064 	if (from_ip_fast_forward)
14065 		goto skip;
14066 
14067 	if (ll_multicast != 0) {
14068 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14069 		goto drop_pkt;
14070 	}
14071 
14072 	/*
14073 	 * check if ipha_src is a broadcast address. Note that this
14074 	 * check is redundant when we get here from ip_fast_forward()
14075 	 * which has already done this check. However, since we can
14076 	 * also get here from ip_rput_process_broadcast() or, for
14077 	 * for the slow path through ip_fast_forward(), we perform
14078 	 * the check again for code-reusability
14079 	 */
14080 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14081 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14082 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14083 		if (src_ire != NULL)
14084 			ire_refrele(src_ire);
14085 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14086 		ip2dbg(("ip_rput_process_forward: Received packet with"
14087 		    " bad src/dst address on %s\n", ill->ill_name));
14088 		goto drop_pkt;
14089 	}
14090 
14091 	/*
14092 	 * Check if we want to forward this one at this time.
14093 	 * We allow source routed packets on a host provided that
14094 	 * they go out the same ill or illgrp as they came in on.
14095 	 *
14096 	 * XXX To be quicker, we may wish to not chase pointers to
14097 	 * get the ILLF_ROUTER flag and instead store the
14098 	 * forwarding policy in the ire.  An unfortunate
14099 	 * side-effect of that would be requiring an ire flush
14100 	 * whenever the ILLF_ROUTER flag changes.
14101 	 */
14102 skip:
14103 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14104 
14105 	if (((ill->ill_flags &
14106 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14107 	    !(ip_source_routed(ipha, ipst) &&
14108 	    (ire->ire_rfq == q || same_illgrp))) {
14109 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14110 		if (ip_source_routed(ipha, ipst)) {
14111 			q = WR(q);
14112 			/*
14113 			 * Clear the indication that this may have
14114 			 * hardware checksum as we are not using it.
14115 			 */
14116 			DB_CKSUMFLAGS(mp) = 0;
14117 			/* Sent by forwarding path, and router is global zone */
14118 			icmp_unreachable(q, mp,
14119 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14120 			return;
14121 		}
14122 		goto drop_pkt;
14123 	}
14124 
14125 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14126 
14127 	/* Packet is being forwarded. Turning off hwcksum flag. */
14128 	DB_CKSUMFLAGS(mp) = 0;
14129 	if (ipst->ips_ip_g_send_redirects) {
14130 		/*
14131 		 * Check whether the incoming interface and outgoing
14132 		 * interface is part of the same group. If so,
14133 		 * send redirects.
14134 		 *
14135 		 * Check the source address to see if it originated
14136 		 * on the same logical subnet it is going back out on.
14137 		 * If so, we should be able to send it a redirect.
14138 		 * Avoid sending a redirect if the destination
14139 		 * is directly connected (i.e., ipha_dst is the same
14140 		 * as ire_gateway_addr or the ire_addr of the
14141 		 * nexthop IRE_CACHE ), or if the packet was source
14142 		 * routed out this interface.
14143 		 */
14144 		ipaddr_t src, nhop;
14145 		mblk_t	*mp1;
14146 		ire_t	*nhop_ire = NULL;
14147 
14148 		/*
14149 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14150 		 * If so, send redirects.
14151 		 */
14152 		if ((ire->ire_rfq == q || same_illgrp) &&
14153 		    !ip_source_routed(ipha, ipst)) {
14154 
14155 			nhop = (ire->ire_gateway_addr != 0 ?
14156 			    ire->ire_gateway_addr : ire->ire_addr);
14157 
14158 			if (ipha->ipha_dst == nhop) {
14159 				/*
14160 				 * We avoid sending a redirect if the
14161 				 * destination is directly connected
14162 				 * because it is possible that multiple
14163 				 * IP subnets may have been configured on
14164 				 * the link, and the source may not
14165 				 * be on the same subnet as ip destination,
14166 				 * even though they are on the same
14167 				 * physical link.
14168 				 */
14169 				goto sendit;
14170 			}
14171 
14172 			src = ipha->ipha_src;
14173 
14174 			/*
14175 			 * We look up the interface ire for the nexthop,
14176 			 * to see if ipha_src is in the same subnet
14177 			 * as the nexthop.
14178 			 *
14179 			 * Note that, if, in the future, IRE_CACHE entries
14180 			 * are obsoleted,  this lookup will not be needed,
14181 			 * as the ire passed to this function will be the
14182 			 * same as the nhop_ire computed below.
14183 			 */
14184 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14185 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14186 			    0, NULL, MATCH_IRE_TYPE, ipst);
14187 
14188 			if (nhop_ire != NULL) {
14189 				if ((src & nhop_ire->ire_mask) ==
14190 				    (nhop & nhop_ire->ire_mask)) {
14191 					/*
14192 					 * The source is directly connected.
14193 					 * Just copy the ip header (which is
14194 					 * in the first mblk)
14195 					 */
14196 					mp1 = copyb(mp);
14197 					if (mp1 != NULL) {
14198 						icmp_send_redirect(WR(q), mp1,
14199 						    nhop, ipst);
14200 					}
14201 				}
14202 				ire_refrele(nhop_ire);
14203 			}
14204 		}
14205 	}
14206 sendit:
14207 	dev_q = ire->ire_stq->q_next;
14208 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14209 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14210 		freemsg(mp);
14211 		return;
14212 	}
14213 
14214 	ip_rput_forward(ire, ipha, mp, ill);
14215 	return;
14216 
14217 drop_pkt:
14218 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14219 	freemsg(mp);
14220 }
14221 
14222 ire_t *
14223 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14224     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14225 {
14226 	queue_t		*q;
14227 	uint16_t	hcksumflags;
14228 	ip_stack_t	*ipst = ill->ill_ipst;
14229 
14230 	q = *qp;
14231 
14232 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14233 
14234 	/*
14235 	 * Clear the indication that this may have hardware
14236 	 * checksum as we are not using it for forwarding.
14237 	 */
14238 	hcksumflags = DB_CKSUMFLAGS(mp);
14239 	DB_CKSUMFLAGS(mp) = 0;
14240 
14241 	/*
14242 	 * Directed broadcast forwarding: if the packet came in over a
14243 	 * different interface then it is routed out over we can forward it.
14244 	 */
14245 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14246 		ire_refrele(ire);
14247 		freemsg(mp);
14248 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14249 		return (NULL);
14250 	}
14251 	/*
14252 	 * For multicast we have set dst to be INADDR_BROADCAST
14253 	 * for delivering to all STREAMS.
14254 	 */
14255 	if (!CLASSD(ipha->ipha_dst)) {
14256 		ire_t *new_ire;
14257 		ipif_t *ipif;
14258 
14259 		ipif = ipif_get_next_ipif(NULL, ill);
14260 		if (ipif == NULL) {
14261 discard:		ire_refrele(ire);
14262 			freemsg(mp);
14263 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14264 			return (NULL);
14265 		}
14266 		new_ire = ire_ctable_lookup(dst, 0, 0,
14267 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14268 		ipif_refrele(ipif);
14269 
14270 		if (new_ire != NULL) {
14271 			/*
14272 			 * If the matching IRE_BROADCAST is part of an IPMP
14273 			 * group, then drop the packet unless our ill has been
14274 			 * nominated to receive for the group.
14275 			 */
14276 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14277 			    new_ire->ire_rfq != q) {
14278 				ire_refrele(new_ire);
14279 				goto discard;
14280 			}
14281 
14282 			/*
14283 			 * In the special case of multirouted broadcast
14284 			 * packets, we unconditionally need to "gateway"
14285 			 * them to the appropriate interface here.
14286 			 * In the normal case, this cannot happen, because
14287 			 * there is no broadcast IRE tagged with the
14288 			 * RTF_MULTIRT flag.
14289 			 */
14290 			if (new_ire->ire_flags & RTF_MULTIRT) {
14291 				ire_refrele(new_ire);
14292 				if (ire->ire_rfq != NULL) {
14293 					q = ire->ire_rfq;
14294 					*qp = q;
14295 				}
14296 			} else {
14297 				ire_refrele(ire);
14298 				ire = new_ire;
14299 			}
14300 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14301 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14302 				/*
14303 				 * Free the message if
14304 				 * ip_g_forward_directed_bcast is turned
14305 				 * off for non-local broadcast.
14306 				 */
14307 				ire_refrele(ire);
14308 				freemsg(mp);
14309 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14310 				return (NULL);
14311 			}
14312 		} else {
14313 			/*
14314 			 * This CGTP packet successfully passed the
14315 			 * CGTP filter, but the related CGTP
14316 			 * broadcast IRE has not been found,
14317 			 * meaning that the redundant ipif is
14318 			 * probably down. However, if we discarded
14319 			 * this packet, its duplicate would be
14320 			 * filtered out by the CGTP filter so none
14321 			 * of them would get through. So we keep
14322 			 * going with this one.
14323 			 */
14324 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14325 			if (ire->ire_rfq != NULL) {
14326 				q = ire->ire_rfq;
14327 				*qp = q;
14328 			}
14329 		}
14330 	}
14331 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14332 		/*
14333 		 * Verify that there are not more then one
14334 		 * IRE_BROADCAST with this broadcast address which
14335 		 * has ire_stq set.
14336 		 * TODO: simplify, loop over all IRE's
14337 		 */
14338 		ire_t	*ire1;
14339 		int	num_stq = 0;
14340 		mblk_t	*mp1;
14341 
14342 		/* Find the first one with ire_stq set */
14343 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14344 		for (ire1 = ire; ire1 &&
14345 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14346 		    ire1 = ire1->ire_next)
14347 			;
14348 		if (ire1) {
14349 			ire_refrele(ire);
14350 			ire = ire1;
14351 			IRE_REFHOLD(ire);
14352 		}
14353 
14354 		/* Check if there are additional ones with stq set */
14355 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14356 			if (ire->ire_addr != ire1->ire_addr)
14357 				break;
14358 			if (ire1->ire_stq) {
14359 				num_stq++;
14360 				break;
14361 			}
14362 		}
14363 		rw_exit(&ire->ire_bucket->irb_lock);
14364 		if (num_stq == 1 && ire->ire_stq != NULL) {
14365 			ip1dbg(("ip_rput_process_broadcast: directed "
14366 			    "broadcast to 0x%x\n",
14367 			    ntohl(ire->ire_addr)));
14368 			mp1 = copymsg(mp);
14369 			if (mp1) {
14370 				switch (ipha->ipha_protocol) {
14371 				case IPPROTO_UDP:
14372 					ip_udp_input(q, mp1, ipha, ire, ill);
14373 					break;
14374 				default:
14375 					ip_proto_input(q, mp1, ipha, ire, ill,
14376 					    0);
14377 					break;
14378 				}
14379 			}
14380 			/*
14381 			 * Adjust ttl to 2 (1+1 - the forward engine
14382 			 * will decrement it by one.
14383 			 */
14384 			if (ip_csum_hdr(ipha)) {
14385 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14386 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14387 				freemsg(mp);
14388 				ire_refrele(ire);
14389 				return (NULL);
14390 			}
14391 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14392 			ipha->ipha_hdr_checksum = 0;
14393 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14394 			ip_rput_process_forward(q, mp, ire, ipha,
14395 			    ill, ll_multicast, B_FALSE);
14396 			ire_refrele(ire);
14397 			return (NULL);
14398 		}
14399 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14400 		    ntohl(ire->ire_addr)));
14401 	}
14402 
14403 	/* Restore any hardware checksum flags */
14404 	DB_CKSUMFLAGS(mp) = hcksumflags;
14405 	return (ire);
14406 }
14407 
14408 /* ARGSUSED */
14409 static boolean_t
14410 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14411     int *ll_multicast, ipaddr_t *dstp)
14412 {
14413 	ip_stack_t	*ipst = ill->ill_ipst;
14414 
14415 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14416 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14417 	    ntohs(ipha->ipha_length));
14418 
14419 	/*
14420 	 * So that we don't end up with dups, only one ill in an IPMP group is
14421 	 * nominated to receive multicast traffic.
14422 	 */
14423 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14424 		goto drop_pkt;
14425 
14426 	/*
14427 	 * Forward packets only if we have joined the allmulti
14428 	 * group on this interface.
14429 	 */
14430 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14431 		int retval;
14432 
14433 		/*
14434 		 * Clear the indication that this may have hardware
14435 		 * checksum as we are not using it.
14436 		 */
14437 		DB_CKSUMFLAGS(mp) = 0;
14438 		retval = ip_mforward(ill, ipha, mp);
14439 		/* ip_mforward updates mib variables if needed */
14440 		/* clear b_prev - used by ip_mroute_decap */
14441 		mp->b_prev = NULL;
14442 
14443 		switch (retval) {
14444 		case 0:
14445 			/*
14446 			 * pkt is okay and arrived on phyint.
14447 			 *
14448 			 * If we are running as a multicast router
14449 			 * we need to see all IGMP and/or PIM packets.
14450 			 */
14451 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14452 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14453 				goto done;
14454 			}
14455 			break;
14456 		case -1:
14457 			/* pkt is mal-formed, toss it */
14458 			goto drop_pkt;
14459 		case 1:
14460 			/* pkt is okay and arrived on a tunnel */
14461 			/*
14462 			 * If we are running a multicast router
14463 			 *  we need to see all igmp packets.
14464 			 */
14465 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14466 				*dstp = INADDR_BROADCAST;
14467 				*ll_multicast = 1;
14468 				return (B_FALSE);
14469 			}
14470 
14471 			goto drop_pkt;
14472 		}
14473 	}
14474 
14475 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14476 		/*
14477 		 * This might just be caused by the fact that
14478 		 * multiple IP Multicast addresses map to the same
14479 		 * link layer multicast - no need to increment counter!
14480 		 */
14481 		freemsg(mp);
14482 		return (B_TRUE);
14483 	}
14484 done:
14485 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14486 	/*
14487 	 * This assumes the we deliver to all streams for multicast
14488 	 * and broadcast packets.
14489 	 */
14490 	*dstp = INADDR_BROADCAST;
14491 	*ll_multicast = 1;
14492 	return (B_FALSE);
14493 drop_pkt:
14494 	ip2dbg(("ip_rput: drop pkt\n"));
14495 	freemsg(mp);
14496 	return (B_TRUE);
14497 }
14498 
14499 /*
14500  * This function is used to both return an indication of whether or not
14501  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14502  * and in doing so, determine whether or not it is broadcast vs multicast.
14503  * For it to be a broadcast packet, we must have the appropriate mblk_t
14504  * hanging off the ill_t.  If this is either not present or doesn't match
14505  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14506  * to be multicast.  Thus NICs that have no broadcast address (or no
14507  * capability for one, such as point to point links) cannot return as
14508  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14509  * the return values simplifies the current use of the return value of this
14510  * function, which is to pass through the multicast/broadcast characteristic
14511  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14512  * changing the return value to some other symbol demands the appropriate
14513  * "translation" when hpe_flags is set prior to calling hook_run() for
14514  * packet events.
14515  */
14516 int
14517 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14518 {
14519 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14520 	mblk_t *bmp;
14521 
14522 	if (ind->dl_group_address) {
14523 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14524 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14525 		    MBLKL(mb) &&
14526 		    (bmp = ill->ill_bcast_mp) != NULL) {
14527 			dl_unitdata_req_t *dlur;
14528 			uint8_t *bphys_addr;
14529 
14530 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14531 			if (ill->ill_sap_length < 0)
14532 				bphys_addr = (uchar_t *)dlur +
14533 				    dlur->dl_dest_addr_offset;
14534 			else
14535 				bphys_addr = (uchar_t *)dlur +
14536 				    dlur->dl_dest_addr_offset +
14537 				    ill->ill_sap_length;
14538 
14539 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14540 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14541 				return (HPE_BROADCAST);
14542 			}
14543 			return (HPE_MULTICAST);
14544 		}
14545 		return (HPE_MULTICAST);
14546 	}
14547 	return (0);
14548 }
14549 
14550 static boolean_t
14551 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14552     int *ll_multicast, mblk_t **mpp)
14553 {
14554 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14555 	boolean_t must_copy = B_FALSE;
14556 	struct iocblk   *iocp;
14557 	ipha_t		*ipha;
14558 	ip_stack_t	*ipst = ill->ill_ipst;
14559 
14560 #define	rptr    ((uchar_t *)ipha)
14561 
14562 	first_mp = *first_mpp;
14563 	mp = *mpp;
14564 
14565 	ASSERT(first_mp == mp);
14566 
14567 	/*
14568 	 * if db_ref > 1 then copymsg and free original. Packet may be
14569 	 * changed and do not want other entity who has a reference to this
14570 	 * message to trip over the changes. This is a blind change because
14571 	 * trying to catch all places that might change packet is too
14572 	 * difficult (since it may be a module above this one)
14573 	 *
14574 	 * This corresponds to the non-fast path case. We walk down the full
14575 	 * chain in this case, and check the db_ref count of all the dblks,
14576 	 * and do a copymsg if required. It is possible that the db_ref counts
14577 	 * of the data blocks in the mblk chain can be different.
14578 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14579 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14580 	 * 'snoop' is running.
14581 	 */
14582 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14583 		if (mp1->b_datap->db_ref > 1) {
14584 			must_copy = B_TRUE;
14585 			break;
14586 		}
14587 	}
14588 
14589 	if (must_copy) {
14590 		mp1 = copymsg(mp);
14591 		if (mp1 == NULL) {
14592 			for (mp1 = mp; mp1 != NULL;
14593 			    mp1 = mp1->b_cont) {
14594 				mp1->b_next = NULL;
14595 				mp1->b_prev = NULL;
14596 			}
14597 			freemsg(mp);
14598 			if (ill != NULL) {
14599 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14600 			} else {
14601 				BUMP_MIB(&ipst->ips_ip_mib,
14602 				    ipIfStatsInDiscards);
14603 			}
14604 			return (B_TRUE);
14605 		}
14606 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14607 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14608 			/* Copy b_prev - used by ip_mroute_decap */
14609 			to_mp->b_prev = from_mp->b_prev;
14610 			from_mp->b_prev = NULL;
14611 		}
14612 		*first_mpp = first_mp = mp1;
14613 		freemsg(mp);
14614 		mp = mp1;
14615 		*mpp = mp1;
14616 	}
14617 
14618 	ipha = (ipha_t *)mp->b_rptr;
14619 
14620 	/*
14621 	 * previous code has a case for M_DATA.
14622 	 * We want to check how that happens.
14623 	 */
14624 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14625 	switch (first_mp->b_datap->db_type) {
14626 	case M_PROTO:
14627 	case M_PCPROTO:
14628 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14629 		    DL_UNITDATA_IND) {
14630 			/* Go handle anything other than data elsewhere. */
14631 			ip_rput_dlpi(q, mp);
14632 			return (B_TRUE);
14633 		}
14634 
14635 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14636 		/* Ditch the DLPI header. */
14637 		mp1 = mp->b_cont;
14638 		ASSERT(first_mp == mp);
14639 		*first_mpp = mp1;
14640 		freeb(mp);
14641 		*mpp = mp1;
14642 		return (B_FALSE);
14643 	case M_IOCACK:
14644 		ip1dbg(("got iocack "));
14645 		iocp = (struct iocblk *)mp->b_rptr;
14646 		switch (iocp->ioc_cmd) {
14647 		case DL_IOC_HDR_INFO:
14648 			ill = (ill_t *)q->q_ptr;
14649 			ill_fastpath_ack(ill, mp);
14650 			return (B_TRUE);
14651 		case SIOCSTUNPARAM:
14652 		case OSIOCSTUNPARAM:
14653 			/* Go through qwriter_ip */
14654 			break;
14655 		case SIOCGTUNPARAM:
14656 		case OSIOCGTUNPARAM:
14657 			ip_rput_other(NULL, q, mp, NULL);
14658 			return (B_TRUE);
14659 		default:
14660 			putnext(q, mp);
14661 			return (B_TRUE);
14662 		}
14663 		/* FALLTHRU */
14664 	case M_ERROR:
14665 	case M_HANGUP:
14666 		/*
14667 		 * Since this is on the ill stream we unconditionally
14668 		 * bump up the refcount
14669 		 */
14670 		ill_refhold(ill);
14671 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14672 		return (B_TRUE);
14673 	case M_CTL:
14674 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14675 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14676 		    IPHADA_M_CTL)) {
14677 			/*
14678 			 * It's an IPsec accelerated packet.
14679 			 * Make sure that the ill from which we received the
14680 			 * packet has enabled IPsec hardware acceleration.
14681 			 */
14682 			if (!(ill->ill_capabilities &
14683 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14684 				/* IPsec kstats: bean counter */
14685 				freemsg(mp);
14686 				return (B_TRUE);
14687 			}
14688 
14689 			/*
14690 			 * Make mp point to the mblk following the M_CTL,
14691 			 * then process according to type of mp.
14692 			 * After this processing, first_mp will point to
14693 			 * the data-attributes and mp to the pkt following
14694 			 * the M_CTL.
14695 			 */
14696 			mp = first_mp->b_cont;
14697 			if (mp == NULL) {
14698 				freemsg(first_mp);
14699 				return (B_TRUE);
14700 			}
14701 			/*
14702 			 * A Hardware Accelerated packet can only be M_DATA
14703 			 * ESP or AH packet.
14704 			 */
14705 			if (mp->b_datap->db_type != M_DATA) {
14706 				/* non-M_DATA IPsec accelerated packet */
14707 				IPSECHW_DEBUG(IPSECHW_PKT,
14708 				    ("non-M_DATA IPsec accelerated pkt\n"));
14709 				freemsg(first_mp);
14710 				return (B_TRUE);
14711 			}
14712 			ipha = (ipha_t *)mp->b_rptr;
14713 			if (ipha->ipha_protocol != IPPROTO_AH &&
14714 			    ipha->ipha_protocol != IPPROTO_ESP) {
14715 				IPSECHW_DEBUG(IPSECHW_PKT,
14716 				    ("non-M_DATA IPsec accelerated pkt\n"));
14717 				freemsg(first_mp);
14718 				return (B_TRUE);
14719 			}
14720 			*mpp = mp;
14721 			return (B_FALSE);
14722 		}
14723 		putnext(q, mp);
14724 		return (B_TRUE);
14725 	case M_IOCNAK:
14726 		ip1dbg(("got iocnak "));
14727 		iocp = (struct iocblk *)mp->b_rptr;
14728 		switch (iocp->ioc_cmd) {
14729 		case SIOCSTUNPARAM:
14730 		case OSIOCSTUNPARAM:
14731 			/*
14732 			 * Since this is on the ill stream we unconditionally
14733 			 * bump up the refcount
14734 			 */
14735 			ill_refhold(ill);
14736 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14737 			return (B_TRUE);
14738 		case DL_IOC_HDR_INFO:
14739 		case SIOCGTUNPARAM:
14740 		case OSIOCGTUNPARAM:
14741 			ip_rput_other(NULL, q, mp, NULL);
14742 			return (B_TRUE);
14743 		default:
14744 			break;
14745 		}
14746 		/* FALLTHRU */
14747 	default:
14748 		putnext(q, mp);
14749 		return (B_TRUE);
14750 	}
14751 }
14752 
14753 /* Read side put procedure.  Packets coming from the wire arrive here. */
14754 void
14755 ip_rput(queue_t *q, mblk_t *mp)
14756 {
14757 	ill_t	*ill;
14758 	union DL_primitives *dl;
14759 
14760 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14761 
14762 	ill = (ill_t *)q->q_ptr;
14763 
14764 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14765 		/*
14766 		 * If things are opening or closing, only accept high-priority
14767 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14768 		 * created; on close, things hanging off the ill may have been
14769 		 * freed already.)
14770 		 */
14771 		dl = (union DL_primitives *)mp->b_rptr;
14772 		if (DB_TYPE(mp) != M_PCPROTO ||
14773 		    dl->dl_primitive == DL_UNITDATA_IND) {
14774 			/*
14775 			 * SIOC[GS]TUNPARAM ioctls can come here.
14776 			 */
14777 			inet_freemsg(mp);
14778 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14779 			    "ip_rput_end: q %p (%S)", q, "uninit");
14780 			return;
14781 		}
14782 	}
14783 
14784 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14785 	    "ip_rput_end: q %p (%S)", q, "end");
14786 
14787 	ip_input(ill, NULL, mp, NULL);
14788 }
14789 
14790 static mblk_t *
14791 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14792 {
14793 	mblk_t *mp1;
14794 	boolean_t adjusted = B_FALSE;
14795 	ip_stack_t *ipst = ill->ill_ipst;
14796 
14797 	IP_STAT(ipst, ip_db_ref);
14798 	/*
14799 	 * The IP_RECVSLLA option depends on having the
14800 	 * link layer header. First check that:
14801 	 * a> the underlying device is of type ether,
14802 	 * since this option is currently supported only
14803 	 * over ethernet.
14804 	 * b> there is enough room to copy over the link
14805 	 * layer header.
14806 	 *
14807 	 * Once the checks are done, adjust rptr so that
14808 	 * the link layer header will be copied via
14809 	 * copymsg. Note that, IFT_ETHER may be returned
14810 	 * by some non-ethernet drivers but in this case
14811 	 * the second check will fail.
14812 	 */
14813 	if (ill->ill_type == IFT_ETHER &&
14814 	    (mp->b_rptr - mp->b_datap->db_base) >=
14815 	    sizeof (struct ether_header)) {
14816 		mp->b_rptr -= sizeof (struct ether_header);
14817 		adjusted = B_TRUE;
14818 	}
14819 	mp1 = copymsg(mp);
14820 
14821 	if (mp1 == NULL) {
14822 		mp->b_next = NULL;
14823 		/* clear b_prev - used by ip_mroute_decap */
14824 		mp->b_prev = NULL;
14825 		freemsg(mp);
14826 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14827 		return (NULL);
14828 	}
14829 
14830 	if (adjusted) {
14831 		/*
14832 		 * Copy is done. Restore the pointer in
14833 		 * the _new_ mblk
14834 		 */
14835 		mp1->b_rptr += sizeof (struct ether_header);
14836 	}
14837 
14838 	/* Copy b_prev - used by ip_mroute_decap */
14839 	mp1->b_prev = mp->b_prev;
14840 	mp->b_prev = NULL;
14841 
14842 	/* preserve the hardware checksum flags and data, if present */
14843 	if (DB_CKSUMFLAGS(mp) != 0) {
14844 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14845 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14846 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14847 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14848 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14849 	}
14850 
14851 	freemsg(mp);
14852 	return (mp1);
14853 }
14854 
14855 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14856 	if (tail != NULL)					\
14857 		tail->b_next = mp;				\
14858 	else							\
14859 		head = mp;					\
14860 	tail = mp;						\
14861 	cnt++;							\
14862 }
14863 
14864 /*
14865  * Direct read side procedure capable of dealing with chains. GLDv3 based
14866  * drivers call this function directly with mblk chains while STREAMS
14867  * read side procedure ip_rput() calls this for single packet with ip_ring
14868  * set to NULL to process one packet at a time.
14869  *
14870  * The ill will always be valid if this function is called directly from
14871  * the driver.
14872  *
14873  * If ip_input() is called from GLDv3:
14874  *
14875  *   - This must be a non-VLAN IP stream.
14876  *   - 'mp' is either an untagged or a special priority-tagged packet.
14877  *   - Any VLAN tag that was in the MAC header has been stripped.
14878  *
14879  * If the IP header in packet is not 32-bit aligned, every message in the
14880  * chain will be aligned before further operations. This is required on SPARC
14881  * platform.
14882  */
14883 /* ARGSUSED */
14884 void
14885 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14886     struct mac_header_info_s *mhip)
14887 {
14888 	ipaddr_t		dst = NULL;
14889 	ipaddr_t		prev_dst;
14890 	ire_t			*ire = NULL;
14891 	ipha_t			*ipha;
14892 	uint_t			pkt_len;
14893 	ssize_t			len;
14894 	uint_t			opt_len;
14895 	int			ll_multicast;
14896 	int			cgtp_flt_pkt;
14897 	queue_t			*q = ill->ill_rq;
14898 	squeue_t		*curr_sqp = NULL;
14899 	mblk_t 			*head = NULL;
14900 	mblk_t			*tail = NULL;
14901 	mblk_t			*first_mp;
14902 	int			cnt = 0;
14903 	ip_stack_t		*ipst = ill->ill_ipst;
14904 	mblk_t			*mp;
14905 	mblk_t			*dmp;
14906 	uint8_t			tag;
14907 
14908 	ASSERT(mp_chain != NULL);
14909 	ASSERT(ill != NULL);
14910 
14911 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14912 
14913 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14914 
14915 #define	rptr	((uchar_t *)ipha)
14916 
14917 	while (mp_chain != NULL) {
14918 		mp = mp_chain;
14919 		mp_chain = mp_chain->b_next;
14920 		mp->b_next = NULL;
14921 		ll_multicast = 0;
14922 
14923 		/*
14924 		 * We do ire caching from one iteration to
14925 		 * another. In the event the packet chain contains
14926 		 * all packets from the same dst, this caching saves
14927 		 * an ire_cache_lookup for each of the succeeding
14928 		 * packets in a packet chain.
14929 		 */
14930 		prev_dst = dst;
14931 
14932 		/*
14933 		 * if db_ref > 1 then copymsg and free original. Packet
14934 		 * may be changed and we do not want the other entity
14935 		 * who has a reference to this message to trip over the
14936 		 * changes. This is a blind change because trying to
14937 		 * catch all places that might change the packet is too
14938 		 * difficult.
14939 		 *
14940 		 * This corresponds to the fast path case, where we have
14941 		 * a chain of M_DATA mblks.  We check the db_ref count
14942 		 * of only the 1st data block in the mblk chain. There
14943 		 * doesn't seem to be a reason why a device driver would
14944 		 * send up data with varying db_ref counts in the mblk
14945 		 * chain. In any case the Fast path is a private
14946 		 * interface, and our drivers don't do such a thing.
14947 		 * Given the above assumption, there is no need to walk
14948 		 * down the entire mblk chain (which could have a
14949 		 * potential performance problem)
14950 		 *
14951 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14952 		 * to here because of exclusive ip stacks and vnics.
14953 		 * Packets transmitted from exclusive stack over vnic
14954 		 * can have db_ref > 1 and when it gets looped back to
14955 		 * another vnic in a different zone, you have ip_input()
14956 		 * getting dblks with db_ref > 1. So if someone
14957 		 * complains of TCP performance under this scenario,
14958 		 * take a serious look here on the impact of copymsg().
14959 		 */
14960 
14961 		if (DB_REF(mp) > 1) {
14962 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14963 				continue;
14964 		}
14965 
14966 		/*
14967 		 * Check and align the IP header.
14968 		 */
14969 		first_mp = mp;
14970 		if (DB_TYPE(mp) == M_DATA) {
14971 			dmp = mp;
14972 		} else if (DB_TYPE(mp) == M_PROTO &&
14973 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14974 			dmp = mp->b_cont;
14975 		} else {
14976 			dmp = NULL;
14977 		}
14978 		if (dmp != NULL) {
14979 			/*
14980 			 * IP header ptr not aligned?
14981 			 * OR IP header not complete in first mblk
14982 			 */
14983 			if (!OK_32PTR(dmp->b_rptr) ||
14984 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14985 				if (!ip_check_and_align_header(q, dmp, ipst))
14986 					continue;
14987 			}
14988 		}
14989 
14990 		/*
14991 		 * ip_input fast path
14992 		 */
14993 
14994 		/* mblk type is not M_DATA */
14995 		if (DB_TYPE(mp) != M_DATA) {
14996 			if (ip_rput_process_notdata(q, &first_mp, ill,
14997 			    &ll_multicast, &mp))
14998 				continue;
14999 
15000 			/*
15001 			 * The only way we can get here is if we had a
15002 			 * packet that was either a DL_UNITDATA_IND or
15003 			 * an M_CTL for an IPsec accelerated packet.
15004 			 *
15005 			 * In either case, the first_mp will point to
15006 			 * the leading M_PROTO or M_CTL.
15007 			 */
15008 			ASSERT(first_mp != NULL);
15009 		} else if (mhip != NULL) {
15010 			/*
15011 			 * ll_multicast is set here so that it is ready
15012 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15013 			 * manipulates ll_multicast in the same fashion when
15014 			 * called from ip_rput_process_notdata.
15015 			 */
15016 			switch (mhip->mhi_dsttype) {
15017 			case MAC_ADDRTYPE_MULTICAST :
15018 				ll_multicast = HPE_MULTICAST;
15019 				break;
15020 			case MAC_ADDRTYPE_BROADCAST :
15021 				ll_multicast = HPE_BROADCAST;
15022 				break;
15023 			default :
15024 				break;
15025 			}
15026 		}
15027 
15028 		/* Only M_DATA can come here and it is always aligned */
15029 		ASSERT(DB_TYPE(mp) == M_DATA);
15030 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15031 
15032 		ipha = (ipha_t *)mp->b_rptr;
15033 		len = mp->b_wptr - rptr;
15034 		pkt_len = ntohs(ipha->ipha_length);
15035 
15036 		/*
15037 		 * We must count all incoming packets, even if they end
15038 		 * up being dropped later on.
15039 		 */
15040 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15041 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15042 
15043 		/* multiple mblk or too short */
15044 		len -= pkt_len;
15045 		if (len != 0) {
15046 			/*
15047 			 * Make sure we have data length consistent
15048 			 * with the IP header.
15049 			 */
15050 			if (mp->b_cont == NULL) {
15051 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15052 					BUMP_MIB(ill->ill_ip_mib,
15053 					    ipIfStatsInHdrErrors);
15054 					ip2dbg(("ip_input: drop pkt\n"));
15055 					freemsg(mp);
15056 					continue;
15057 				}
15058 				mp->b_wptr = rptr + pkt_len;
15059 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15060 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15061 					BUMP_MIB(ill->ill_ip_mib,
15062 					    ipIfStatsInHdrErrors);
15063 					ip2dbg(("ip_input: drop pkt\n"));
15064 					freemsg(mp);
15065 					continue;
15066 				}
15067 				(void) adjmsg(mp, -len);
15068 				IP_STAT(ipst, ip_multimblk3);
15069 			}
15070 		}
15071 
15072 		/* Obtain the dst of the current packet */
15073 		dst = ipha->ipha_dst;
15074 
15075 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15076 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15077 		    ipha, ip6_t *, NULL, int, 0);
15078 
15079 		/*
15080 		 * The following test for loopback is faster than
15081 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15082 		 * operations.
15083 		 * Note that these addresses are always in network byte order
15084 		 */
15085 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15086 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15087 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15088 			freemsg(mp);
15089 			continue;
15090 		}
15091 
15092 		/*
15093 		 * The event for packets being received from a 'physical'
15094 		 * interface is placed after validation of the source and/or
15095 		 * destination address as being local so that packets can be
15096 		 * redirected to loopback addresses using ipnat.
15097 		 */
15098 		DTRACE_PROBE4(ip4__physical__in__start,
15099 		    ill_t *, ill, ill_t *, NULL,
15100 		    ipha_t *, ipha, mblk_t *, first_mp);
15101 
15102 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15103 		    ipst->ips_ipv4firewall_physical_in,
15104 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15105 
15106 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15107 
15108 		if (first_mp == NULL) {
15109 			continue;
15110 		}
15111 		dst = ipha->ipha_dst;
15112 		/*
15113 		 * Attach any necessary label information to
15114 		 * this packet
15115 		 */
15116 		if (is_system_labeled() &&
15117 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15118 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15119 			freemsg(mp);
15120 			continue;
15121 		}
15122 
15123 		if (ipst->ips_ipobs_enabled) {
15124 			zoneid_t dzone;
15125 
15126 			/*
15127 			 * On the inbound path the src zone will be unknown as
15128 			 * this packet has come from the wire.
15129 			 */
15130 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15131 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15132 			    ill, IPV4_VERSION, 0, ipst);
15133 		}
15134 
15135 		/*
15136 		 * Reuse the cached ire only if the ipha_dst of the previous
15137 		 * packet is the same as the current packet AND it is not
15138 		 * INADDR_ANY.
15139 		 */
15140 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15141 		    (ire != NULL)) {
15142 			ire_refrele(ire);
15143 			ire = NULL;
15144 		}
15145 
15146 		opt_len = ipha->ipha_version_and_hdr_length -
15147 		    IP_SIMPLE_HDR_VERSION;
15148 
15149 		/*
15150 		 * Check to see if we can take the fastpath.
15151 		 * That is possible if the following conditions are met
15152 		 *	o Tsol disabled
15153 		 *	o CGTP disabled
15154 		 *	o ipp_action_count is 0
15155 		 *	o no options in the packet
15156 		 *	o not a RSVP packet
15157 		 * 	o not a multicast packet
15158 		 *	o ill not in IP_DHCPINIT_IF mode
15159 		 */
15160 		if (!is_system_labeled() &&
15161 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15162 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15163 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15164 			if (ire == NULL)
15165 				ire = ire_cache_lookup_simple(dst, ipst);
15166 			/*
15167 			 * Unless forwarding is enabled, dont call
15168 			 * ip_fast_forward(). Incoming packet is for forwarding
15169 			 */
15170 			if ((ill->ill_flags & ILLF_ROUTER) &&
15171 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15172 				ire = ip_fast_forward(ire, dst, ill, mp);
15173 				continue;
15174 			}
15175 			/* incoming packet is for local consumption */
15176 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15177 				goto local;
15178 		}
15179 
15180 		/*
15181 		 * Disable ire caching for anything more complex
15182 		 * than the simple fast path case we checked for above.
15183 		 */
15184 		if (ire != NULL) {
15185 			ire_refrele(ire);
15186 			ire = NULL;
15187 		}
15188 
15189 		/*
15190 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15191 		 * server to unicast DHCP packets to a DHCP client using the
15192 		 * IP address it is offering to the client.  This can be
15193 		 * disabled through the "broadcast bit", but not all DHCP
15194 		 * servers honor that bit.  Therefore, to interoperate with as
15195 		 * many DHCP servers as possible, the DHCP client allows the
15196 		 * server to unicast, but we treat those packets as broadcast
15197 		 * here.  Note that we don't rewrite the packet itself since
15198 		 * (a) that would mess up the checksums and (b) the DHCP
15199 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15200 		 * hand it the packet regardless.
15201 		 */
15202 		if (ill->ill_dhcpinit != 0 &&
15203 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15204 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15205 			udpha_t *udpha;
15206 
15207 			/*
15208 			 * Reload ipha since pullupmsg() can change b_rptr.
15209 			 */
15210 			ipha = (ipha_t *)mp->b_rptr;
15211 			udpha = (udpha_t *)&ipha[1];
15212 
15213 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15214 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15215 				    mblk_t *, mp);
15216 				dst = INADDR_BROADCAST;
15217 			}
15218 		}
15219 
15220 		/* Full-blown slow path */
15221 		if (opt_len != 0) {
15222 			if (len != 0)
15223 				IP_STAT(ipst, ip_multimblk4);
15224 			else
15225 				IP_STAT(ipst, ip_ipoptions);
15226 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15227 			    &dst, ipst))
15228 				continue;
15229 		}
15230 
15231 		/*
15232 		 * Invoke the CGTP (multirouting) filtering module to process
15233 		 * the incoming packet. Packets identified as duplicates
15234 		 * must be discarded. Filtering is active only if the
15235 		 * the ip_cgtp_filter ndd variable is non-zero.
15236 		 */
15237 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15238 		if (ipst->ips_ip_cgtp_filter &&
15239 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15240 			netstackid_t stackid;
15241 
15242 			stackid = ipst->ips_netstack->netstack_stackid;
15243 			cgtp_flt_pkt =
15244 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15245 			    ill->ill_phyint->phyint_ifindex, mp);
15246 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15247 				freemsg(first_mp);
15248 				continue;
15249 			}
15250 		}
15251 
15252 		/*
15253 		 * If rsvpd is running, let RSVP daemon handle its processing
15254 		 * and forwarding of RSVP multicast/unicast packets.
15255 		 * If rsvpd is not running but mrouted is running, RSVP
15256 		 * multicast packets are forwarded as multicast traffic
15257 		 * and RSVP unicast packets are forwarded by unicast router.
15258 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15259 		 * packets are not forwarded, but the unicast packets are
15260 		 * forwarded like unicast traffic.
15261 		 */
15262 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15263 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15264 		    NULL) {
15265 			/* RSVP packet and rsvpd running. Treat as ours */
15266 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15267 			/*
15268 			 * This assumes that we deliver to all streams for
15269 			 * multicast and broadcast packets.
15270 			 * We have to force ll_multicast to 1 to handle the
15271 			 * M_DATA messages passed in from ip_mroute_decap.
15272 			 */
15273 			dst = INADDR_BROADCAST;
15274 			ll_multicast = 1;
15275 		} else if (CLASSD(dst)) {
15276 			/* packet is multicast */
15277 			mp->b_next = NULL;
15278 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15279 			    &ll_multicast, &dst))
15280 				continue;
15281 		}
15282 
15283 		if (ire == NULL) {
15284 			ire = ire_cache_lookup(dst, ALL_ZONES,
15285 			    msg_getlabel(mp), ipst);
15286 		}
15287 
15288 		if (ire != NULL && ire->ire_stq != NULL &&
15289 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15290 		    ire->ire_zoneid != ALL_ZONES) {
15291 			/*
15292 			 * Should only use IREs that are visible from the
15293 			 * global zone for forwarding.
15294 			 */
15295 			ire_refrele(ire);
15296 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15297 			    msg_getlabel(mp), ipst);
15298 		}
15299 
15300 		if (ire == NULL) {
15301 			/*
15302 			 * No IRE for this destination, so it can't be for us.
15303 			 * Unless we are forwarding, drop the packet.
15304 			 * We have to let source routed packets through
15305 			 * since we don't yet know if they are 'ping -l'
15306 			 * packets i.e. if they will go out over the
15307 			 * same interface as they came in on.
15308 			 */
15309 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15310 			if (ire == NULL)
15311 				continue;
15312 		}
15313 
15314 		/*
15315 		 * Broadcast IRE may indicate either broadcast or
15316 		 * multicast packet
15317 		 */
15318 		if (ire->ire_type == IRE_BROADCAST) {
15319 			/*
15320 			 * Skip broadcast checks if packet is UDP multicast;
15321 			 * we'd rather not enter ip_rput_process_broadcast()
15322 			 * unless the packet is broadcast for real, since
15323 			 * that routine is a no-op for multicast.
15324 			 */
15325 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15326 			    !CLASSD(ipha->ipha_dst)) {
15327 				ire = ip_rput_process_broadcast(&q, mp,
15328 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15329 				    ll_multicast);
15330 				if (ire == NULL)
15331 					continue;
15332 			}
15333 		} else if (ire->ire_stq != NULL) {
15334 			/* fowarding? */
15335 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15336 			    ll_multicast, B_FALSE);
15337 			/* ip_rput_process_forward consumed the packet */
15338 			continue;
15339 		}
15340 
15341 local:
15342 		/*
15343 		 * If the queue in the ire is different to the ingress queue
15344 		 * then we need to check to see if we can accept the packet.
15345 		 * Note that for multicast packets and broadcast packets sent
15346 		 * to a broadcast address which is shared between multiple
15347 		 * interfaces we should not do this since we just got a random
15348 		 * broadcast ire.
15349 		 */
15350 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15351 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15352 			if (ire == NULL) {
15353 				/* Drop packet */
15354 				BUMP_MIB(ill->ill_ip_mib,
15355 				    ipIfStatsForwProhibits);
15356 				freemsg(mp);
15357 				continue;
15358 			}
15359 			if (ire->ire_rfq != NULL)
15360 				q = ire->ire_rfq;
15361 		}
15362 
15363 		switch (ipha->ipha_protocol) {
15364 		case IPPROTO_TCP:
15365 			ASSERT(first_mp == mp);
15366 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15367 			    mp, 0, q, ip_ring)) != NULL) {
15368 				if (curr_sqp == NULL) {
15369 					curr_sqp = GET_SQUEUE(mp);
15370 					ASSERT(cnt == 0);
15371 					cnt++;
15372 					head = tail = mp;
15373 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15374 					ASSERT(tail != NULL);
15375 					cnt++;
15376 					tail->b_next = mp;
15377 					tail = mp;
15378 				} else {
15379 					/*
15380 					 * A different squeue. Send the
15381 					 * chain for the previous squeue on
15382 					 * its way. This shouldn't happen
15383 					 * often unless interrupt binding
15384 					 * changes.
15385 					 */
15386 					IP_STAT(ipst, ip_input_multi_squeue);
15387 					SQUEUE_ENTER(curr_sqp, head,
15388 					    tail, cnt, SQ_PROCESS, tag);
15389 					curr_sqp = GET_SQUEUE(mp);
15390 					head = mp;
15391 					tail = mp;
15392 					cnt = 1;
15393 				}
15394 			}
15395 			continue;
15396 		case IPPROTO_UDP:
15397 			ASSERT(first_mp == mp);
15398 			ip_udp_input(q, mp, ipha, ire, ill);
15399 			continue;
15400 		case IPPROTO_SCTP:
15401 			ASSERT(first_mp == mp);
15402 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15403 			    q, dst);
15404 			/* ire has been released by ip_sctp_input */
15405 			ire = NULL;
15406 			continue;
15407 		default:
15408 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15409 			continue;
15410 		}
15411 	}
15412 
15413 	if (ire != NULL)
15414 		ire_refrele(ire);
15415 
15416 	if (head != NULL)
15417 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15418 
15419 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15420 	    "ip_input_end: q %p (%S)", q, "end");
15421 #undef  rptr
15422 }
15423 
15424 /*
15425  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15426  * a chain of packets in the poll mode. The packets have gone through the
15427  * data link processing but not IP processing. For performance and latency
15428  * reasons, the squeue wants to process the chain in line instead of feeding
15429  * it back via ip_input path.
15430  *
15431  * So this is a light weight function which checks to see if the packets
15432  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15433  * but we still do the paranoid check) meant for local machine and we don't
15434  * have labels etc enabled. Packets that meet the criterion are returned to
15435  * the squeue and processed inline while the rest go via ip_input path.
15436  */
15437 /*ARGSUSED*/
15438 mblk_t *
15439 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15440     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15441 {
15442 	mblk_t 		*mp;
15443 	ipaddr_t	dst = NULL;
15444 	ipaddr_t	prev_dst;
15445 	ire_t		*ire = NULL;
15446 	ipha_t		*ipha;
15447 	uint_t		pkt_len;
15448 	ssize_t		len;
15449 	uint_t		opt_len;
15450 	queue_t		*q = ill->ill_rq;
15451 	squeue_t	*curr_sqp;
15452 	mblk_t 		*ahead = NULL;	/* Accepted head */
15453 	mblk_t		*atail = NULL;	/* Accepted tail */
15454 	uint_t		acnt = 0;	/* Accepted count */
15455 	mblk_t		*utail = NULL;	/* Unaccepted head */
15456 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15457 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15458 	ip_stack_t	*ipst = ill->ill_ipst;
15459 
15460 	*cnt = 0;
15461 
15462 	ASSERT(ill != NULL);
15463 	ASSERT(ip_ring != NULL);
15464 
15465 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15466 
15467 #define	rptr	((uchar_t *)ipha)
15468 
15469 	while (mp_chain != NULL) {
15470 		mp = mp_chain;
15471 		mp_chain = mp_chain->b_next;
15472 		mp->b_next = NULL;
15473 
15474 		/*
15475 		 * We do ire caching from one iteration to
15476 		 * another. In the event the packet chain contains
15477 		 * all packets from the same dst, this caching saves
15478 		 * an ire_cache_lookup for each of the succeeding
15479 		 * packets in a packet chain.
15480 		 */
15481 		prev_dst = dst;
15482 
15483 		ipha = (ipha_t *)mp->b_rptr;
15484 		len = mp->b_wptr - rptr;
15485 
15486 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15487 
15488 		/*
15489 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15490 		 * or doesn't have min len, reject.
15491 		 */
15492 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15493 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15494 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15495 			continue;
15496 		}
15497 
15498 		pkt_len = ntohs(ipha->ipha_length);
15499 		if (len != pkt_len) {
15500 			if (len > pkt_len) {
15501 				mp->b_wptr = rptr + pkt_len;
15502 			} else {
15503 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15504 				continue;
15505 			}
15506 		}
15507 
15508 		opt_len = ipha->ipha_version_and_hdr_length -
15509 		    IP_SIMPLE_HDR_VERSION;
15510 		dst = ipha->ipha_dst;
15511 
15512 		/* IP version bad or there are IP options */
15513 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15514 		    mp, &ipha, &dst, ipst)))
15515 			continue;
15516 
15517 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15518 		    (ipst->ips_ip_cgtp_filter &&
15519 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15520 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15521 			continue;
15522 		}
15523 
15524 		/*
15525 		 * Reuse the cached ire only if the ipha_dst of the previous
15526 		 * packet is the same as the current packet AND it is not
15527 		 * INADDR_ANY.
15528 		 */
15529 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15530 		    (ire != NULL)) {
15531 			ire_refrele(ire);
15532 			ire = NULL;
15533 		}
15534 
15535 		if (ire == NULL)
15536 			ire = ire_cache_lookup_simple(dst, ipst);
15537 
15538 		/*
15539 		 * Unless forwarding is enabled, dont call
15540 		 * ip_fast_forward(). Incoming packet is for forwarding
15541 		 */
15542 		if ((ill->ill_flags & ILLF_ROUTER) &&
15543 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15544 
15545 			DTRACE_PROBE4(ip4__physical__in__start,
15546 			    ill_t *, ill, ill_t *, NULL,
15547 			    ipha_t *, ipha, mblk_t *, mp);
15548 
15549 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15550 			    ipst->ips_ipv4firewall_physical_in,
15551 			    ill, NULL, ipha, mp, mp, 0, ipst);
15552 
15553 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15554 
15555 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15556 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15557 			    pkt_len);
15558 
15559 			if (mp != NULL)
15560 				ire = ip_fast_forward(ire, dst, ill, mp);
15561 			continue;
15562 		}
15563 
15564 		/* incoming packet is for local consumption */
15565 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15566 			goto local_accept;
15567 
15568 		/*
15569 		 * Disable ire caching for anything more complex
15570 		 * than the simple fast path case we checked for above.
15571 		 */
15572 		if (ire != NULL) {
15573 			ire_refrele(ire);
15574 			ire = NULL;
15575 		}
15576 
15577 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15578 		    ipst);
15579 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15580 		    ire->ire_stq != NULL) {
15581 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15582 			if (ire != NULL) {
15583 				ire_refrele(ire);
15584 				ire = NULL;
15585 			}
15586 			continue;
15587 		}
15588 
15589 local_accept:
15590 
15591 		if (ire->ire_rfq != q) {
15592 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15593 			if (ire != NULL) {
15594 				ire_refrele(ire);
15595 				ire = NULL;
15596 			}
15597 			continue;
15598 		}
15599 
15600 		/*
15601 		 * The event for packets being received from a 'physical'
15602 		 * interface is placed after validation of the source and/or
15603 		 * destination address as being local so that packets can be
15604 		 * redirected to loopback addresses using ipnat.
15605 		 */
15606 		DTRACE_PROBE4(ip4__physical__in__start,
15607 		    ill_t *, ill, ill_t *, NULL,
15608 		    ipha_t *, ipha, mblk_t *, mp);
15609 
15610 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15611 		    ipst->ips_ipv4firewall_physical_in,
15612 		    ill, NULL, ipha, mp, mp, 0, ipst);
15613 
15614 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15615 
15616 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15617 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15618 
15619 		if (mp != NULL &&
15620 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15621 		    0, q, ip_ring)) != NULL) {
15622 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15623 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15624 			} else {
15625 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15626 				    SQ_FILL, SQTAG_IP_INPUT);
15627 			}
15628 		}
15629 	}
15630 
15631 	if (ire != NULL)
15632 		ire_refrele(ire);
15633 
15634 	if (uhead != NULL)
15635 		ip_input(ill, ip_ring, uhead, NULL);
15636 
15637 	if (ahead != NULL) {
15638 		*last = atail;
15639 		*cnt = acnt;
15640 		return (ahead);
15641 	}
15642 
15643 	return (NULL);
15644 #undef  rptr
15645 }
15646 
15647 static void
15648 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15649     t_uscalar_t err)
15650 {
15651 	if (dl_err == DL_SYSERR) {
15652 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15653 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15654 		    ill->ill_name, dl_primstr(prim), err);
15655 		return;
15656 	}
15657 
15658 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15659 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15660 	    dl_errstr(dl_err));
15661 }
15662 
15663 /*
15664  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15665  * than DL_UNITDATA_IND messages. If we need to process this message
15666  * exclusively, we call qwriter_ip, in which case we also need to call
15667  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15668  */
15669 void
15670 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15671 {
15672 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15673 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15674 	ill_t		*ill = q->q_ptr;
15675 	t_uscalar_t	prim = dloa->dl_primitive;
15676 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15677 
15678 	ip1dbg(("ip_rput_dlpi"));
15679 
15680 	/*
15681 	 * If we received an ACK but didn't send a request for it, then it
15682 	 * can't be part of any pending operation; discard up-front.
15683 	 */
15684 	switch (prim) {
15685 	case DL_ERROR_ACK:
15686 		reqprim = dlea->dl_error_primitive;
15687 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15688 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15689 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15690 		    dlea->dl_unix_errno));
15691 		break;
15692 	case DL_OK_ACK:
15693 		reqprim = dloa->dl_correct_primitive;
15694 		break;
15695 	case DL_INFO_ACK:
15696 		reqprim = DL_INFO_REQ;
15697 		break;
15698 	case DL_BIND_ACK:
15699 		reqprim = DL_BIND_REQ;
15700 		break;
15701 	case DL_PHYS_ADDR_ACK:
15702 		reqprim = DL_PHYS_ADDR_REQ;
15703 		break;
15704 	case DL_NOTIFY_ACK:
15705 		reqprim = DL_NOTIFY_REQ;
15706 		break;
15707 	case DL_CONTROL_ACK:
15708 		reqprim = DL_CONTROL_REQ;
15709 		break;
15710 	case DL_CAPABILITY_ACK:
15711 		reqprim = DL_CAPABILITY_REQ;
15712 		break;
15713 	}
15714 
15715 	if (prim != DL_NOTIFY_IND) {
15716 		if (reqprim == DL_PRIM_INVAL ||
15717 		    !ill_dlpi_pending(ill, reqprim)) {
15718 			/* Not a DLPI message we support or expected */
15719 			freemsg(mp);
15720 			return;
15721 		}
15722 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15723 		    dl_primstr(reqprim)));
15724 	}
15725 
15726 	switch (reqprim) {
15727 	case DL_UNBIND_REQ:
15728 		/*
15729 		 * NOTE: we mark the unbind as complete even if we got a
15730 		 * DL_ERROR_ACK, since there's not much else we can do.
15731 		 */
15732 		mutex_enter(&ill->ill_lock);
15733 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15734 		cv_signal(&ill->ill_cv);
15735 		mutex_exit(&ill->ill_lock);
15736 		break;
15737 
15738 	case DL_ENABMULTI_REQ:
15739 		if (prim == DL_OK_ACK) {
15740 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15741 				ill->ill_dlpi_multicast_state = IDS_OK;
15742 		}
15743 		break;
15744 	}
15745 
15746 	/*
15747 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15748 	 * need to become writer to continue to process it.  Because an
15749 	 * exclusive operation doesn't complete until replies to all queued
15750 	 * DLPI messages have been received, we know we're in the middle of an
15751 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15752 	 *
15753 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15754 	 * Since this is on the ill stream we unconditionally bump up the
15755 	 * refcount without doing ILL_CAN_LOOKUP().
15756 	 */
15757 	ill_refhold(ill);
15758 	if (prim == DL_NOTIFY_IND)
15759 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15760 	else
15761 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15762 }
15763 
15764 /*
15765  * Handling of DLPI messages that require exclusive access to the ipsq.
15766  *
15767  * Need to do ill_pending_mp_release on ioctl completion, which could
15768  * happen here. (along with mi_copy_done)
15769  */
15770 /* ARGSUSED */
15771 static void
15772 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15773 {
15774 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15775 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15776 	int		err = 0;
15777 	ill_t		*ill;
15778 	ipif_t		*ipif = NULL;
15779 	mblk_t		*mp1 = NULL;
15780 	conn_t		*connp = NULL;
15781 	t_uscalar_t	paddrreq;
15782 	mblk_t		*mp_hw;
15783 	boolean_t	success;
15784 	boolean_t	ioctl_aborted = B_FALSE;
15785 	boolean_t	log = B_TRUE;
15786 	ip_stack_t		*ipst;
15787 
15788 	ip1dbg(("ip_rput_dlpi_writer .."));
15789 	ill = (ill_t *)q->q_ptr;
15790 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15791 	ASSERT(IAM_WRITER_ILL(ill));
15792 
15793 	ipst = ill->ill_ipst;
15794 
15795 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15796 	/*
15797 	 * The current ioctl could have been aborted by the user and a new
15798 	 * ioctl to bring up another ill could have started. We could still
15799 	 * get a response from the driver later.
15800 	 */
15801 	if (ipif != NULL && ipif->ipif_ill != ill)
15802 		ioctl_aborted = B_TRUE;
15803 
15804 	switch (dloa->dl_primitive) {
15805 	case DL_ERROR_ACK:
15806 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15807 		    dl_primstr(dlea->dl_error_primitive)));
15808 
15809 		switch (dlea->dl_error_primitive) {
15810 		case DL_DISABMULTI_REQ:
15811 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15812 			break;
15813 		case DL_PROMISCON_REQ:
15814 		case DL_PROMISCOFF_REQ:
15815 		case DL_UNBIND_REQ:
15816 		case DL_ATTACH_REQ:
15817 		case DL_INFO_REQ:
15818 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15819 			break;
15820 		case DL_NOTIFY_REQ:
15821 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15822 			log = B_FALSE;
15823 			break;
15824 		case DL_PHYS_ADDR_REQ:
15825 			/*
15826 			 * For IPv6 only, there are two additional
15827 			 * phys_addr_req's sent to the driver to get the
15828 			 * IPv6 token and lla. This allows IP to acquire
15829 			 * the hardware address format for a given interface
15830 			 * without having built in knowledge of the hardware
15831 			 * address. ill_phys_addr_pend keeps track of the last
15832 			 * DL_PAR sent so we know which response we are
15833 			 * dealing with. ill_dlpi_done will update
15834 			 * ill_phys_addr_pend when it sends the next req.
15835 			 * We don't complete the IOCTL until all three DL_PARs
15836 			 * have been attempted, so set *_len to 0 and break.
15837 			 */
15838 			paddrreq = ill->ill_phys_addr_pend;
15839 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15840 			if (paddrreq == DL_IPV6_TOKEN) {
15841 				ill->ill_token_length = 0;
15842 				log = B_FALSE;
15843 				break;
15844 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15845 				ill->ill_nd_lla_len = 0;
15846 				log = B_FALSE;
15847 				break;
15848 			}
15849 			/*
15850 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15851 			 * We presumably have an IOCTL hanging out waiting
15852 			 * for completion. Find it and complete the IOCTL
15853 			 * with the error noted.
15854 			 * However, ill_dl_phys was called on an ill queue
15855 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15856 			 * set. But the ioctl is known to be pending on ill_wq.
15857 			 */
15858 			if (!ill->ill_ifname_pending)
15859 				break;
15860 			ill->ill_ifname_pending = 0;
15861 			if (!ioctl_aborted)
15862 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15863 			if (mp1 != NULL) {
15864 				/*
15865 				 * This operation (SIOCSLIFNAME) must have
15866 				 * happened on the ill. Assert there is no conn
15867 				 */
15868 				ASSERT(connp == NULL);
15869 				q = ill->ill_wq;
15870 			}
15871 			break;
15872 		case DL_BIND_REQ:
15873 			ill_dlpi_done(ill, DL_BIND_REQ);
15874 			if (ill->ill_ifname_pending)
15875 				break;
15876 			/*
15877 			 * Something went wrong with the bind.  We presumably
15878 			 * have an IOCTL hanging out waiting for completion.
15879 			 * Find it, take down the interface that was coming
15880 			 * up, and complete the IOCTL with the error noted.
15881 			 */
15882 			if (!ioctl_aborted)
15883 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15884 			if (mp1 != NULL) {
15885 				/*
15886 				 * This might be a result of a DL_NOTE_REPLUMB
15887 				 * notification. In that case, connp is NULL.
15888 				 */
15889 				if (connp != NULL)
15890 					q = CONNP_TO_WQ(connp);
15891 
15892 				(void) ipif_down(ipif, NULL, NULL);
15893 				/* error is set below the switch */
15894 			}
15895 			break;
15896 		case DL_ENABMULTI_REQ:
15897 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15898 
15899 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15900 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15901 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15902 				ipif_t *ipif;
15903 
15904 				printf("ip: joining multicasts failed (%d)"
15905 				    " on %s - will use link layer "
15906 				    "broadcasts for multicast\n",
15907 				    dlea->dl_errno, ill->ill_name);
15908 
15909 				/*
15910 				 * Set up the multicast mapping alone.
15911 				 * writer, so ok to access ill->ill_ipif
15912 				 * without any lock.
15913 				 */
15914 				ipif = ill->ill_ipif;
15915 				mutex_enter(&ill->ill_phyint->phyint_lock);
15916 				ill->ill_phyint->phyint_flags |=
15917 				    PHYI_MULTI_BCAST;
15918 				mutex_exit(&ill->ill_phyint->phyint_lock);
15919 
15920 				if (!ill->ill_isv6) {
15921 					(void) ipif_arp_setup_multicast(ipif,
15922 					    NULL);
15923 				} else {
15924 					(void) ipif_ndp_setup_multicast(ipif,
15925 					    NULL);
15926 				}
15927 			}
15928 			freemsg(mp);	/* Don't want to pass this up */
15929 			return;
15930 		case DL_CONTROL_REQ:
15931 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15932 			    "DL_CONTROL_REQ\n"));
15933 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15934 			freemsg(mp);
15935 			return;
15936 		case DL_CAPABILITY_REQ:
15937 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15938 			    "DL_CAPABILITY REQ\n"));
15939 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15940 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15941 			ill_capability_done(ill);
15942 			freemsg(mp);
15943 			return;
15944 		}
15945 		/*
15946 		 * Note the error for IOCTL completion (mp1 is set when
15947 		 * ready to complete ioctl). If ill_ifname_pending_err is
15948 		 * set, an error occured during plumbing (ill_ifname_pending),
15949 		 * so we want to report that error.
15950 		 *
15951 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15952 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15953 		 * expected to get errack'd if the driver doesn't support
15954 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15955 		 * if these error conditions are encountered.
15956 		 */
15957 		if (mp1 != NULL) {
15958 			if (ill->ill_ifname_pending_err != 0)  {
15959 				err = ill->ill_ifname_pending_err;
15960 				ill->ill_ifname_pending_err = 0;
15961 			} else {
15962 				err = dlea->dl_unix_errno ?
15963 				    dlea->dl_unix_errno : ENXIO;
15964 			}
15965 		/*
15966 		 * If we're plumbing an interface and an error hasn't already
15967 		 * been saved, set ill_ifname_pending_err to the error passed
15968 		 * up. Ignore the error if log is B_FALSE (see comment above).
15969 		 */
15970 		} else if (log && ill->ill_ifname_pending &&
15971 		    ill->ill_ifname_pending_err == 0) {
15972 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15973 			    dlea->dl_unix_errno : ENXIO;
15974 		}
15975 
15976 		if (log)
15977 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15978 			    dlea->dl_errno, dlea->dl_unix_errno);
15979 		break;
15980 	case DL_CAPABILITY_ACK:
15981 		ill_capability_ack(ill, mp);
15982 		/*
15983 		 * The message has been handed off to ill_capability_ack
15984 		 * and must not be freed below
15985 		 */
15986 		mp = NULL;
15987 		break;
15988 
15989 	case DL_CONTROL_ACK:
15990 		/* We treat all of these as "fire and forget" */
15991 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15992 		break;
15993 	case DL_INFO_ACK:
15994 		/* Call a routine to handle this one. */
15995 		ill_dlpi_done(ill, DL_INFO_REQ);
15996 		ip_ll_subnet_defaults(ill, mp);
15997 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15998 		return;
15999 	case DL_BIND_ACK:
16000 		/*
16001 		 * We should have an IOCTL waiting on this unless
16002 		 * sent by ill_dl_phys, in which case just return
16003 		 */
16004 		ill_dlpi_done(ill, DL_BIND_REQ);
16005 		if (ill->ill_ifname_pending)
16006 			break;
16007 
16008 		if (!ioctl_aborted)
16009 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16010 		if (mp1 == NULL)
16011 			break;
16012 		/*
16013 		 * mp1 was added by ill_dl_up(). if that is a result of
16014 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
16015 		 */
16016 		if (connp != NULL)
16017 			q = CONNP_TO_WQ(connp);
16018 
16019 		/*
16020 		 * We are exclusive. So nothing can change even after
16021 		 * we get the pending mp. If need be we can put it back
16022 		 * and restart, as in calling ipif_arp_up()  below.
16023 		 */
16024 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16025 
16026 		mutex_enter(&ill->ill_lock);
16027 		ill->ill_dl_up = 1;
16028 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16029 		mutex_exit(&ill->ill_lock);
16030 
16031 		/*
16032 		 * Now bring up the resolver; when that is complete, we'll
16033 		 * create IREs.  Note that we intentionally mirror what
16034 		 * ipif_up() would have done, because we got here by way of
16035 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16036 		 */
16037 		if (ill->ill_isv6) {
16038 			if (ill->ill_flags & ILLF_XRESOLV) {
16039 				if (connp != NULL)
16040 					mutex_enter(&connp->conn_lock);
16041 				mutex_enter(&ill->ill_lock);
16042 				success = ipsq_pending_mp_add(connp, ipif, q,
16043 				    mp1, 0);
16044 				mutex_exit(&ill->ill_lock);
16045 				if (connp != NULL)
16046 					mutex_exit(&connp->conn_lock);
16047 				if (success) {
16048 					err = ipif_resolver_up(ipif,
16049 					    Res_act_initial);
16050 					if (err == EINPROGRESS) {
16051 						freemsg(mp);
16052 						return;
16053 					}
16054 					ASSERT(err != 0);
16055 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16056 					ASSERT(mp1 != NULL);
16057 				} else {
16058 					/* conn has started closing */
16059 					err = EINTR;
16060 				}
16061 			} else { /* Non XRESOLV interface */
16062 				(void) ipif_resolver_up(ipif, Res_act_initial);
16063 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16064 					err = ipif_up_done_v6(ipif);
16065 			}
16066 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16067 			/*
16068 			 * ARP and other v4 external resolvers.
16069 			 * Leave the pending mblk intact so that
16070 			 * the ioctl completes in ip_rput().
16071 			 */
16072 			if (connp != NULL)
16073 				mutex_enter(&connp->conn_lock);
16074 			mutex_enter(&ill->ill_lock);
16075 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16076 			mutex_exit(&ill->ill_lock);
16077 			if (connp != NULL)
16078 				mutex_exit(&connp->conn_lock);
16079 			if (success) {
16080 				err = ipif_resolver_up(ipif, Res_act_initial);
16081 				if (err == EINPROGRESS) {
16082 					freemsg(mp);
16083 					return;
16084 				}
16085 				ASSERT(err != 0);
16086 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16087 			} else {
16088 				/* The conn has started closing */
16089 				err = EINTR;
16090 			}
16091 		} else {
16092 			/*
16093 			 * This one is complete. Reply to pending ioctl.
16094 			 */
16095 			(void) ipif_resolver_up(ipif, Res_act_initial);
16096 			err = ipif_up_done(ipif);
16097 		}
16098 
16099 		if ((err == 0) && (ill->ill_up_ipifs)) {
16100 			err = ill_up_ipifs(ill, q, mp1);
16101 			if (err == EINPROGRESS) {
16102 				freemsg(mp);
16103 				return;
16104 			}
16105 		}
16106 
16107 		/*
16108 		 * If we have a moved ipif to bring up, and everything has
16109 		 * succeeded to this point, bring it up on the IPMP ill.
16110 		 * Otherwise, leave it down -- the admin can try to bring it
16111 		 * up by hand if need be.
16112 		 */
16113 		if (ill->ill_move_ipif != NULL) {
16114 			if (err != 0) {
16115 				ill->ill_move_ipif = NULL;
16116 			} else {
16117 				ipif = ill->ill_move_ipif;
16118 				ill->ill_move_ipif = NULL;
16119 				err = ipif_up(ipif, q, mp1);
16120 				if (err == EINPROGRESS) {
16121 					freemsg(mp);
16122 					return;
16123 				}
16124 			}
16125 		}
16126 		break;
16127 
16128 	case DL_NOTIFY_IND: {
16129 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16130 		ire_t *ire;
16131 		uint_t orig_mtu;
16132 		boolean_t need_ire_walk_v4 = B_FALSE;
16133 		boolean_t need_ire_walk_v6 = B_FALSE;
16134 
16135 		switch (notify->dl_notification) {
16136 		case DL_NOTE_PHYS_ADDR:
16137 			err = ill_set_phys_addr(ill, mp);
16138 			break;
16139 
16140 		case DL_NOTE_REPLUMB:
16141 			/*
16142 			 * Directly return after calling ill_replumb().
16143 			 * Note that we should not free mp as it is reused
16144 			 * in the ill_replumb() function.
16145 			 */
16146 			err = ill_replumb(ill, mp);
16147 			return;
16148 
16149 		case DL_NOTE_FASTPATH_FLUSH:
16150 			ill_fastpath_flush(ill);
16151 			break;
16152 
16153 		case DL_NOTE_SDU_SIZE:
16154 			/*
16155 			 * Change the MTU size of the interface, of all
16156 			 * attached ipif's, and of all relevant ire's.  The
16157 			 * new value's a uint32_t at notify->dl_data.
16158 			 * Mtu change Vs. new ire creation - protocol below.
16159 			 *
16160 			 * a Mark the ipif as IPIF_CHANGING.
16161 			 * b Set the new mtu in the ipif.
16162 			 * c Change the ire_max_frag on all affected ires
16163 			 * d Unmark the IPIF_CHANGING
16164 			 *
16165 			 * To see how the protocol works, assume an interface
16166 			 * route is also being added simultaneously by
16167 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16168 			 * the ire. If the ire is created before step a,
16169 			 * it will be cleaned up by step c. If the ire is
16170 			 * created after step d, it will see the new value of
16171 			 * ipif_mtu. Any attempt to create the ire between
16172 			 * steps a to d will fail because of the IPIF_CHANGING
16173 			 * flag. Note that ire_create() is passed a pointer to
16174 			 * the ipif_mtu, and not the value. During ire_add
16175 			 * under the bucket lock, the ire_max_frag of the
16176 			 * new ire being created is set from the ipif/ire from
16177 			 * which it is being derived.
16178 			 */
16179 			mutex_enter(&ill->ill_lock);
16180 
16181 			orig_mtu = ill->ill_max_mtu;
16182 			ill->ill_max_frag = (uint_t)notify->dl_data;
16183 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16184 
16185 			/*
16186 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16187 			 * clamp ill_max_mtu at it.
16188 			 */
16189 			if (ill->ill_user_mtu != 0 &&
16190 			    ill->ill_user_mtu < ill->ill_max_mtu)
16191 				ill->ill_max_mtu = ill->ill_user_mtu;
16192 
16193 			/*
16194 			 * If the MTU is unchanged, we're done.
16195 			 */
16196 			if (orig_mtu == ill->ill_max_mtu) {
16197 				mutex_exit(&ill->ill_lock);
16198 				break;
16199 			}
16200 
16201 			if (ill->ill_isv6) {
16202 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16203 					ill->ill_max_mtu = IPV6_MIN_MTU;
16204 			} else {
16205 				if (ill->ill_max_mtu < IP_MIN_MTU)
16206 					ill->ill_max_mtu = IP_MIN_MTU;
16207 			}
16208 			for (ipif = ill->ill_ipif; ipif != NULL;
16209 			    ipif = ipif->ipif_next) {
16210 				/*
16211 				 * Don't override the mtu if the user
16212 				 * has explicitly set it.
16213 				 */
16214 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16215 					continue;
16216 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16217 				if (ipif->ipif_isv6)
16218 					ire = ipif_to_ire_v6(ipif);
16219 				else
16220 					ire = ipif_to_ire(ipif);
16221 				if (ire != NULL) {
16222 					ire->ire_max_frag = ipif->ipif_mtu;
16223 					ire_refrele(ire);
16224 				}
16225 				if (ipif->ipif_flags & IPIF_UP) {
16226 					if (ill->ill_isv6)
16227 						need_ire_walk_v6 = B_TRUE;
16228 					else
16229 						need_ire_walk_v4 = B_TRUE;
16230 				}
16231 			}
16232 			mutex_exit(&ill->ill_lock);
16233 			if (need_ire_walk_v4)
16234 				ire_walk_v4(ill_mtu_change, (char *)ill,
16235 				    ALL_ZONES, ipst);
16236 			if (need_ire_walk_v6)
16237 				ire_walk_v6(ill_mtu_change, (char *)ill,
16238 				    ALL_ZONES, ipst);
16239 
16240 			/*
16241 			 * Refresh IPMP meta-interface MTU if necessary.
16242 			 */
16243 			if (IS_UNDER_IPMP(ill))
16244 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16245 			break;
16246 
16247 		case DL_NOTE_LINK_UP:
16248 		case DL_NOTE_LINK_DOWN: {
16249 			/*
16250 			 * We are writer. ill / phyint / ipsq assocs stable.
16251 			 * The RUNNING flag reflects the state of the link.
16252 			 */
16253 			phyint_t *phyint = ill->ill_phyint;
16254 			uint64_t new_phyint_flags;
16255 			boolean_t changed = B_FALSE;
16256 			boolean_t went_up;
16257 
16258 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16259 			mutex_enter(&phyint->phyint_lock);
16260 
16261 			new_phyint_flags = went_up ?
16262 			    phyint->phyint_flags | PHYI_RUNNING :
16263 			    phyint->phyint_flags & ~PHYI_RUNNING;
16264 
16265 			if (IS_IPMP(ill)) {
16266 				new_phyint_flags = went_up ?
16267 				    new_phyint_flags & ~PHYI_FAILED :
16268 				    new_phyint_flags | PHYI_FAILED;
16269 			}
16270 
16271 			if (new_phyint_flags != phyint->phyint_flags) {
16272 				phyint->phyint_flags = new_phyint_flags;
16273 				changed = B_TRUE;
16274 			}
16275 			mutex_exit(&phyint->phyint_lock);
16276 			/*
16277 			 * ill_restart_dad handles the DAD restart and routing
16278 			 * socket notification logic.
16279 			 */
16280 			if (changed) {
16281 				ill_restart_dad(phyint->phyint_illv4, went_up);
16282 				ill_restart_dad(phyint->phyint_illv6, went_up);
16283 			}
16284 			break;
16285 		}
16286 		case DL_NOTE_PROMISC_ON_PHYS:
16287 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16288 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16289 			mutex_enter(&ill->ill_lock);
16290 			ill->ill_promisc_on_phys = B_TRUE;
16291 			mutex_exit(&ill->ill_lock);
16292 			break;
16293 		case DL_NOTE_PROMISC_OFF_PHYS:
16294 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16295 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16296 			mutex_enter(&ill->ill_lock);
16297 			ill->ill_promisc_on_phys = B_FALSE;
16298 			mutex_exit(&ill->ill_lock);
16299 			break;
16300 		case DL_NOTE_CAPAB_RENEG:
16301 			/*
16302 			 * Something changed on the driver side.
16303 			 * It wants us to renegotiate the capabilities
16304 			 * on this ill. One possible cause is the aggregation
16305 			 * interface under us where a port got added or
16306 			 * went away.
16307 			 *
16308 			 * If the capability negotiation is already done
16309 			 * or is in progress, reset the capabilities and
16310 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16311 			 * so that when the ack comes back, we can start
16312 			 * the renegotiation process.
16313 			 *
16314 			 * Note that if ill_capab_reneg is already B_TRUE
16315 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16316 			 * the capability resetting request has been sent
16317 			 * and the renegotiation has not been started yet;
16318 			 * nothing needs to be done in this case.
16319 			 */
16320 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16321 			ill_capability_reset(ill, B_TRUE);
16322 			ipsq_current_finish(ipsq);
16323 			break;
16324 		default:
16325 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16326 			    "type 0x%x for DL_NOTIFY_IND\n",
16327 			    notify->dl_notification));
16328 			break;
16329 		}
16330 
16331 		/*
16332 		 * As this is an asynchronous operation, we
16333 		 * should not call ill_dlpi_done
16334 		 */
16335 		break;
16336 	}
16337 	case DL_NOTIFY_ACK: {
16338 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16339 
16340 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16341 			ill->ill_note_link = 1;
16342 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16343 		break;
16344 	}
16345 	case DL_PHYS_ADDR_ACK: {
16346 		/*
16347 		 * As part of plumbing the interface via SIOCSLIFNAME,
16348 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16349 		 * whose answers we receive here.  As each answer is received,
16350 		 * we call ill_dlpi_done() to dispatch the next request as
16351 		 * we're processing the current one.  Once all answers have
16352 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16353 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16354 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16355 		 * available, but we know the ioctl is pending on ill_wq.)
16356 		 */
16357 		uint_t	paddrlen, paddroff;
16358 
16359 		paddrreq = ill->ill_phys_addr_pend;
16360 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16361 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16362 
16363 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16364 		if (paddrreq == DL_IPV6_TOKEN) {
16365 			/*
16366 			 * bcopy to low-order bits of ill_token
16367 			 *
16368 			 * XXX Temporary hack - currently, all known tokens
16369 			 * are 64 bits, so I'll cheat for the moment.
16370 			 */
16371 			bcopy(mp->b_rptr + paddroff,
16372 			    &ill->ill_token.s6_addr32[2], paddrlen);
16373 			ill->ill_token_length = paddrlen;
16374 			break;
16375 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16376 			ASSERT(ill->ill_nd_lla_mp == NULL);
16377 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16378 			mp = NULL;
16379 			break;
16380 		}
16381 
16382 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16383 		ASSERT(ill->ill_phys_addr_mp == NULL);
16384 		if (!ill->ill_ifname_pending)
16385 			break;
16386 		ill->ill_ifname_pending = 0;
16387 		if (!ioctl_aborted)
16388 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16389 		if (mp1 != NULL) {
16390 			ASSERT(connp == NULL);
16391 			q = ill->ill_wq;
16392 		}
16393 		/*
16394 		 * If any error acks received during the plumbing sequence,
16395 		 * ill_ifname_pending_err will be set. Break out and send up
16396 		 * the error to the pending ioctl.
16397 		 */
16398 		if (ill->ill_ifname_pending_err != 0) {
16399 			err = ill->ill_ifname_pending_err;
16400 			ill->ill_ifname_pending_err = 0;
16401 			break;
16402 		}
16403 
16404 		ill->ill_phys_addr_mp = mp;
16405 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16406 		mp = NULL;
16407 
16408 		/*
16409 		 * If paddrlen is zero, the DLPI provider doesn't support
16410 		 * physical addresses.  The other two tests were historical
16411 		 * workarounds for bugs in our former PPP implementation, but
16412 		 * now other things have grown dependencies on them -- e.g.,
16413 		 * the tun module specifies a dl_addr_length of zero in its
16414 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16415 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16416 		 * but only after careful testing ensures that all dependent
16417 		 * broken DLPI providers have been fixed.
16418 		 */
16419 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16420 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16421 			ill->ill_phys_addr = NULL;
16422 		} else if (paddrlen != ill->ill_phys_addr_length) {
16423 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16424 			    paddrlen, ill->ill_phys_addr_length));
16425 			err = EINVAL;
16426 			break;
16427 		}
16428 
16429 		if (ill->ill_nd_lla_mp == NULL) {
16430 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16431 				err = ENOMEM;
16432 				break;
16433 			}
16434 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16435 		}
16436 
16437 		/*
16438 		 * Set the interface token.  If the zeroth interface address
16439 		 * is unspecified, then set it to the link local address.
16440 		 */
16441 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16442 			(void) ill_setdefaulttoken(ill);
16443 
16444 		ASSERT(ill->ill_ipif->ipif_id == 0);
16445 		if (ipif != NULL &&
16446 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16447 			(void) ipif_setlinklocal(ipif);
16448 		}
16449 		break;
16450 	}
16451 	case DL_OK_ACK:
16452 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16453 		    dl_primstr((int)dloa->dl_correct_primitive),
16454 		    dloa->dl_correct_primitive));
16455 		switch (dloa->dl_correct_primitive) {
16456 		case DL_ENABMULTI_REQ:
16457 		case DL_DISABMULTI_REQ:
16458 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16459 			break;
16460 		case DL_PROMISCON_REQ:
16461 		case DL_PROMISCOFF_REQ:
16462 		case DL_UNBIND_REQ:
16463 		case DL_ATTACH_REQ:
16464 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16465 			break;
16466 		}
16467 		break;
16468 	default:
16469 		break;
16470 	}
16471 
16472 	freemsg(mp);
16473 	if (mp1 == NULL)
16474 		return;
16475 
16476 	/*
16477 	 * The operation must complete without EINPROGRESS since
16478 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16479 	 * the operation will be stuck forever inside the IPSQ.
16480 	 */
16481 	ASSERT(err != EINPROGRESS);
16482 
16483 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16484 	case 0:
16485 		ipsq_current_finish(ipsq);
16486 		break;
16487 
16488 	case SIOCSLIFNAME:
16489 	case IF_UNITSEL: {
16490 		ill_t *ill_other = ILL_OTHER(ill);
16491 
16492 		/*
16493 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16494 		 * ill has a peer which is in an IPMP group, then place ill
16495 		 * into the same group.  One catch: although ifconfig plumbs
16496 		 * the appropriate IPMP meta-interface prior to plumbing this
16497 		 * ill, it is possible for multiple ifconfig applications to
16498 		 * race (or for another application to adjust plumbing), in
16499 		 * which case the IPMP meta-interface we need will be missing.
16500 		 * If so, kick the phyint out of the group.
16501 		 */
16502 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16503 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16504 			ipmp_illgrp_t	*illg;
16505 
16506 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16507 			if (illg == NULL)
16508 				ipmp_phyint_leave_grp(ill->ill_phyint);
16509 			else
16510 				ipmp_ill_join_illgrp(ill, illg);
16511 		}
16512 
16513 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16514 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16515 		else
16516 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16517 		break;
16518 	}
16519 	case SIOCLIFADDIF:
16520 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16521 		break;
16522 
16523 	default:
16524 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16525 		break;
16526 	}
16527 }
16528 
16529 /*
16530  * ip_rput_other is called by ip_rput to handle messages modifying the global
16531  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16532  */
16533 /* ARGSUSED */
16534 void
16535 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16536 {
16537 	ill_t		*ill = q->q_ptr;
16538 	struct iocblk	*iocp;
16539 	mblk_t		*mp1;
16540 	conn_t		*connp = NULL;
16541 
16542 	ip1dbg(("ip_rput_other "));
16543 	if (ipsq != NULL) {
16544 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16545 		ASSERT(ipsq->ipsq_xop ==
16546 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16547 	}
16548 
16549 	switch (mp->b_datap->db_type) {
16550 	case M_ERROR:
16551 	case M_HANGUP:
16552 		/*
16553 		 * The device has a problem.  We force the ILL down.  It can
16554 		 * be brought up again manually using SIOCSIFFLAGS (via
16555 		 * ifconfig or equivalent).
16556 		 */
16557 		ASSERT(ipsq != NULL);
16558 		if (mp->b_rptr < mp->b_wptr)
16559 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16560 		if (ill->ill_error == 0)
16561 			ill->ill_error = ENXIO;
16562 		if (!ill_down_start(q, mp))
16563 			return;
16564 		ipif_all_down_tail(ipsq, q, mp, NULL);
16565 		break;
16566 	case M_IOCACK:
16567 		iocp = (struct iocblk *)mp->b_rptr;
16568 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16569 		switch (iocp->ioc_cmd) {
16570 		case SIOCSTUNPARAM:
16571 		case OSIOCSTUNPARAM:
16572 			ASSERT(ipsq != NULL);
16573 			/*
16574 			 * Finish socket ioctl passed through to tun.
16575 			 * We should have an IOCTL waiting on this.
16576 			 */
16577 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16578 			if (ill->ill_isv6) {
16579 				struct iftun_req *ta;
16580 
16581 				/*
16582 				 * if a source or destination is
16583 				 * being set, try and set the link
16584 				 * local address for the tunnel
16585 				 */
16586 				ta = (struct iftun_req *)mp->b_cont->
16587 				    b_cont->b_rptr;
16588 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16589 					ipif_set_tun_llink(ill, ta);
16590 				}
16591 
16592 			}
16593 			if (mp1 != NULL) {
16594 				/*
16595 				 * Now copy back the b_next/b_prev used by
16596 				 * mi code for the mi_copy* functions.
16597 				 * See ip_sioctl_tunparam() for the reason.
16598 				 * Also protect against missing b_cont.
16599 				 */
16600 				if (mp->b_cont != NULL) {
16601 					mp->b_cont->b_next =
16602 					    mp1->b_cont->b_next;
16603 					mp->b_cont->b_prev =
16604 					    mp1->b_cont->b_prev;
16605 				}
16606 				inet_freemsg(mp1);
16607 				ASSERT(connp != NULL);
16608 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16609 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16610 			} else {
16611 				ASSERT(connp == NULL);
16612 				putnext(q, mp);
16613 			}
16614 			break;
16615 		case SIOCGTUNPARAM:
16616 		case OSIOCGTUNPARAM:
16617 			/*
16618 			 * This is really M_IOCDATA from the tunnel driver.
16619 			 * convert back and complete the ioctl.
16620 			 * We should have an IOCTL waiting on this.
16621 			 */
16622 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16623 			if (mp1) {
16624 				/*
16625 				 * Now copy back the b_next/b_prev used by
16626 				 * mi code for the mi_copy* functions.
16627 				 * See ip_sioctl_tunparam() for the reason.
16628 				 * Also protect against missing b_cont.
16629 				 */
16630 				if (mp->b_cont != NULL) {
16631 					mp->b_cont->b_next =
16632 					    mp1->b_cont->b_next;
16633 					mp->b_cont->b_prev =
16634 					    mp1->b_cont->b_prev;
16635 				}
16636 				inet_freemsg(mp1);
16637 				if (iocp->ioc_error == 0)
16638 					mp->b_datap->db_type = M_IOCDATA;
16639 				ASSERT(connp != NULL);
16640 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16641 				    iocp->ioc_error, COPYOUT, NULL);
16642 			} else {
16643 				ASSERT(connp == NULL);
16644 				putnext(q, mp);
16645 			}
16646 			break;
16647 		default:
16648 			break;
16649 		}
16650 		break;
16651 	case M_IOCNAK:
16652 		iocp = (struct iocblk *)mp->b_rptr;
16653 
16654 		switch (iocp->ioc_cmd) {
16655 			int mode;
16656 
16657 		case DL_IOC_HDR_INFO:
16658 			/*
16659 			 * If this was the first attempt, turn off the
16660 			 * fastpath probing.
16661 			 */
16662 			mutex_enter(&ill->ill_lock);
16663 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16664 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16665 				mutex_exit(&ill->ill_lock);
16666 				ill_fastpath_nack(ill);
16667 				ip1dbg(("ip_rput: DLPI fastpath off on "
16668 				    "interface %s\n",
16669 				    ill->ill_name));
16670 			} else {
16671 				mutex_exit(&ill->ill_lock);
16672 			}
16673 			freemsg(mp);
16674 			break;
16675 			case SIOCSTUNPARAM:
16676 		case OSIOCSTUNPARAM:
16677 			ASSERT(ipsq != NULL);
16678 			/*
16679 			 * Finish socket ioctl passed through to tun
16680 			 * We should have an IOCTL waiting on this.
16681 			 */
16682 			/* FALLTHRU */
16683 		case SIOCGTUNPARAM:
16684 		case OSIOCGTUNPARAM:
16685 			/*
16686 			 * This is really M_IOCDATA from the tunnel driver.
16687 			 * convert back and complete the ioctl.
16688 			 * We should have an IOCTL waiting on this.
16689 			 */
16690 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16691 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16692 				mp1 = ill_pending_mp_get(ill, &connp,
16693 				    iocp->ioc_id);
16694 				mode = COPYOUT;
16695 				ipsq = NULL;
16696 			} else {
16697 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16698 				mode = NO_COPYOUT;
16699 			}
16700 			if (mp1 != NULL) {
16701 				/*
16702 				 * Now copy back the b_next/b_prev used by
16703 				 * mi code for the mi_copy* functions.
16704 				 * See ip_sioctl_tunparam() for the reason.
16705 				 * Also protect against missing b_cont.
16706 				 */
16707 				if (mp->b_cont != NULL) {
16708 					mp->b_cont->b_next =
16709 					    mp1->b_cont->b_next;
16710 					mp->b_cont->b_prev =
16711 					    mp1->b_cont->b_prev;
16712 				}
16713 				inet_freemsg(mp1);
16714 				if (iocp->ioc_error == 0)
16715 					iocp->ioc_error = EINVAL;
16716 				ASSERT(connp != NULL);
16717 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16718 				    iocp->ioc_error, mode, ipsq);
16719 			} else {
16720 				ASSERT(connp == NULL);
16721 				putnext(q, mp);
16722 			}
16723 			break;
16724 		default:
16725 			break;
16726 		}
16727 	default:
16728 		break;
16729 	}
16730 }
16731 
16732 /*
16733  * NOTE : This function does not ire_refrele the ire argument passed in.
16734  *
16735  * IPQoS notes
16736  * IP policy is invoked twice for a forwarded packet, once on the read side
16737  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16738  * enabled. An additional parameter, in_ill, has been added for this purpose.
16739  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16740  * because ip_mroute drops this information.
16741  *
16742  */
16743 void
16744 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16745 {
16746 	uint32_t	old_pkt_len;
16747 	uint32_t	pkt_len;
16748 	queue_t	*q;
16749 	uint32_t	sum;
16750 #define	rptr	((uchar_t *)ipha)
16751 	uint32_t	max_frag;
16752 	uint32_t	ill_index;
16753 	ill_t		*out_ill;
16754 	mib2_ipIfStatsEntry_t *mibptr;
16755 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16756 
16757 	/* Get the ill_index of the incoming ILL */
16758 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16759 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16760 
16761 	/* Initiate Read side IPPF processing */
16762 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16763 		ip_process(IPP_FWD_IN, &mp, ill_index);
16764 		if (mp == NULL) {
16765 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16766 			    "during IPPF processing\n"));
16767 			return;
16768 		}
16769 	}
16770 
16771 	/* Adjust the checksum to reflect the ttl decrement. */
16772 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16773 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16774 
16775 	if (ipha->ipha_ttl-- <= 1) {
16776 		if (ip_csum_hdr(ipha)) {
16777 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16778 			goto drop_pkt;
16779 		}
16780 		/*
16781 		 * Note: ire_stq this will be NULL for multicast
16782 		 * datagrams using the long path through arp (the IRE
16783 		 * is not an IRE_CACHE). This should not cause
16784 		 * problems since we don't generate ICMP errors for
16785 		 * multicast packets.
16786 		 */
16787 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16788 		q = ire->ire_stq;
16789 		if (q != NULL) {
16790 			/* Sent by forwarding path, and router is global zone */
16791 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16792 			    GLOBAL_ZONEID, ipst);
16793 		} else
16794 			freemsg(mp);
16795 		return;
16796 	}
16797 
16798 	/*
16799 	 * Don't forward if the interface is down
16800 	 */
16801 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16802 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16803 		ip2dbg(("ip_rput_forward:interface is down\n"));
16804 		goto drop_pkt;
16805 	}
16806 
16807 	/* Get the ill_index of the outgoing ILL */
16808 	out_ill = ire_to_ill(ire);
16809 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16810 
16811 	DTRACE_PROBE4(ip4__forwarding__start,
16812 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16813 
16814 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16815 	    ipst->ips_ipv4firewall_forwarding,
16816 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16817 
16818 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16819 
16820 	if (mp == NULL)
16821 		return;
16822 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16823 
16824 	if (is_system_labeled()) {
16825 		mblk_t *mp1;
16826 
16827 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16828 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16829 			goto drop_pkt;
16830 		}
16831 		/* Size may have changed */
16832 		mp = mp1;
16833 		ipha = (ipha_t *)mp->b_rptr;
16834 		pkt_len = ntohs(ipha->ipha_length);
16835 	}
16836 
16837 	/* Check if there are options to update */
16838 	if (!IS_SIMPLE_IPH(ipha)) {
16839 		if (ip_csum_hdr(ipha)) {
16840 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16841 			goto drop_pkt;
16842 		}
16843 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16844 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16845 			return;
16846 		}
16847 
16848 		ipha->ipha_hdr_checksum = 0;
16849 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16850 	}
16851 	max_frag = ire->ire_max_frag;
16852 	if (pkt_len > max_frag) {
16853 		/*
16854 		 * It needs fragging on its way out.  We haven't
16855 		 * verified the header checksum yet.  Since we
16856 		 * are going to put a surely good checksum in the
16857 		 * outgoing header, we have to make sure that it
16858 		 * was good coming in.
16859 		 */
16860 		if (ip_csum_hdr(ipha)) {
16861 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16862 			goto drop_pkt;
16863 		}
16864 		/* Initiate Write side IPPF processing */
16865 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16866 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16867 			if (mp == NULL) {
16868 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16869 				    " during IPPF processing\n"));
16870 				return;
16871 			}
16872 		}
16873 		/*
16874 		 * Handle labeled packet resizing.
16875 		 *
16876 		 * If we have added a label, inform ip_wput_frag() of its
16877 		 * effect on the MTU for ICMP messages.
16878 		 */
16879 		if (pkt_len > old_pkt_len) {
16880 			uint32_t secopt_size;
16881 
16882 			secopt_size = pkt_len - old_pkt_len;
16883 			if (secopt_size < max_frag)
16884 				max_frag -= secopt_size;
16885 		}
16886 
16887 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16888 		    GLOBAL_ZONEID, ipst, NULL);
16889 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16890 		return;
16891 	}
16892 
16893 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16894 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16895 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16896 	    ipst->ips_ipv4firewall_physical_out,
16897 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16898 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16899 	if (mp == NULL)
16900 		return;
16901 
16902 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16903 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16904 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16905 	/* ip_xmit_v4 always consumes the packet */
16906 	return;
16907 
16908 drop_pkt:;
16909 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16910 	freemsg(mp);
16911 #undef	rptr
16912 }
16913 
16914 void
16915 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16916 {
16917 	ire_t	*ire;
16918 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16919 
16920 	ASSERT(!ipif->ipif_isv6);
16921 	/*
16922 	 * Find an IRE which matches the destination and the outgoing
16923 	 * queue in the cache table. All we need is an IRE_CACHE which
16924 	 * is pointing at ipif->ipif_ill.
16925 	 */
16926 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16927 		dst = ipif->ipif_pp_dst_addr;
16928 
16929 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16930 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16931 	if (ire == NULL) {
16932 		/*
16933 		 * Mark this packet to make it be delivered to
16934 		 * ip_rput_forward after the new ire has been
16935 		 * created.
16936 		 */
16937 		mp->b_prev = NULL;
16938 		mp->b_next = mp;
16939 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16940 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16941 	} else {
16942 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16943 		IRE_REFRELE(ire);
16944 	}
16945 }
16946 
16947 /* Update any source route, record route or timestamp options */
16948 static int
16949 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16950 {
16951 	ipoptp_t	opts;
16952 	uchar_t		*opt;
16953 	uint8_t		optval;
16954 	uint8_t		optlen;
16955 	ipaddr_t	dst;
16956 	uint32_t	ts;
16957 	ire_t		*dst_ire = NULL;
16958 	ire_t		*tmp_ire = NULL;
16959 	timestruc_t	now;
16960 
16961 	ip2dbg(("ip_rput_forward_options\n"));
16962 	dst = ipha->ipha_dst;
16963 	for (optval = ipoptp_first(&opts, ipha);
16964 	    optval != IPOPT_EOL;
16965 	    optval = ipoptp_next(&opts)) {
16966 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16967 		opt = opts.ipoptp_cur;
16968 		optlen = opts.ipoptp_len;
16969 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16970 		    optval, opts.ipoptp_len));
16971 		switch (optval) {
16972 			uint32_t off;
16973 		case IPOPT_SSRR:
16974 		case IPOPT_LSRR:
16975 			/* Check if adminstratively disabled */
16976 			if (!ipst->ips_ip_forward_src_routed) {
16977 				if (ire->ire_stq != NULL) {
16978 					/*
16979 					 * Sent by forwarding path, and router
16980 					 * is global zone
16981 					 */
16982 					icmp_unreachable(ire->ire_stq, mp,
16983 					    ICMP_SOURCE_ROUTE_FAILED,
16984 					    GLOBAL_ZONEID, ipst);
16985 				} else {
16986 					ip0dbg(("ip_rput_forward_options: "
16987 					    "unable to send unreach\n"));
16988 					freemsg(mp);
16989 				}
16990 				return (-1);
16991 			}
16992 
16993 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16994 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16995 			if (dst_ire == NULL) {
16996 				/*
16997 				 * Must be partial since ip_rput_options
16998 				 * checked for strict.
16999 				 */
17000 				break;
17001 			}
17002 			off = opt[IPOPT_OFFSET];
17003 			off--;
17004 		redo_srr:
17005 			if (optlen < IP_ADDR_LEN ||
17006 			    off > optlen - IP_ADDR_LEN) {
17007 				/* End of source route */
17008 				ip1dbg((
17009 				    "ip_rput_forward_options: end of SR\n"));
17010 				ire_refrele(dst_ire);
17011 				break;
17012 			}
17013 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17014 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17015 			    IP_ADDR_LEN);
17016 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17017 			    ntohl(dst)));
17018 
17019 			/*
17020 			 * Check if our address is present more than
17021 			 * once as consecutive hops in source route.
17022 			 */
17023 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17024 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17025 			if (tmp_ire != NULL) {
17026 				ire_refrele(tmp_ire);
17027 				off += IP_ADDR_LEN;
17028 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17029 				goto redo_srr;
17030 			}
17031 			ipha->ipha_dst = dst;
17032 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17033 			ire_refrele(dst_ire);
17034 			break;
17035 		case IPOPT_RR:
17036 			off = opt[IPOPT_OFFSET];
17037 			off--;
17038 			if (optlen < IP_ADDR_LEN ||
17039 			    off > optlen - IP_ADDR_LEN) {
17040 				/* No more room - ignore */
17041 				ip1dbg((
17042 				    "ip_rput_forward_options: end of RR\n"));
17043 				break;
17044 			}
17045 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17046 			    IP_ADDR_LEN);
17047 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17048 			break;
17049 		case IPOPT_TS:
17050 			/* Insert timestamp if there is room */
17051 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17052 			case IPOPT_TS_TSONLY:
17053 				off = IPOPT_TS_TIMELEN;
17054 				break;
17055 			case IPOPT_TS_PRESPEC:
17056 			case IPOPT_TS_PRESPEC_RFC791:
17057 				/* Verify that the address matched */
17058 				off = opt[IPOPT_OFFSET] - 1;
17059 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17060 				dst_ire = ire_ctable_lookup(dst, 0,
17061 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17062 				    MATCH_IRE_TYPE, ipst);
17063 				if (dst_ire == NULL) {
17064 					/* Not for us */
17065 					break;
17066 				}
17067 				ire_refrele(dst_ire);
17068 				/* FALLTHRU */
17069 			case IPOPT_TS_TSANDADDR:
17070 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17071 				break;
17072 			default:
17073 				/*
17074 				 * ip_*put_options should have already
17075 				 * dropped this packet.
17076 				 */
17077 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17078 				    "unknown IT - bug in ip_rput_options?\n");
17079 				return (0);	/* Keep "lint" happy */
17080 			}
17081 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17082 				/* Increase overflow counter */
17083 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17084 				opt[IPOPT_POS_OV_FLG] =
17085 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17086 				    (off << 4));
17087 				break;
17088 			}
17089 			off = opt[IPOPT_OFFSET] - 1;
17090 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17091 			case IPOPT_TS_PRESPEC:
17092 			case IPOPT_TS_PRESPEC_RFC791:
17093 			case IPOPT_TS_TSANDADDR:
17094 				bcopy(&ire->ire_src_addr,
17095 				    (char *)opt + off, IP_ADDR_LEN);
17096 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17097 				/* FALLTHRU */
17098 			case IPOPT_TS_TSONLY:
17099 				off = opt[IPOPT_OFFSET] - 1;
17100 				/* Compute # of milliseconds since midnight */
17101 				gethrestime(&now);
17102 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17103 				    now.tv_nsec / (NANOSEC / MILLISEC);
17104 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17105 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17106 				break;
17107 			}
17108 			break;
17109 		}
17110 	}
17111 	return (0);
17112 }
17113 
17114 /*
17115  * This is called after processing at least one of AH/ESP headers.
17116  *
17117  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17118  * the actual, physical interface on which the packet was received,
17119  * but, when ip_strict_dst_multihoming is set to 1, could be the
17120  * interface which had the ipha_dst configured when the packet went
17121  * through ip_rput. The ill_index corresponding to the recv_ill
17122  * is saved in ipsec_in_rill_index
17123  *
17124  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17125  * cannot assume "ire" points to valid data for any IPv6 cases.
17126  */
17127 void
17128 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17129 {
17130 	mblk_t *mp;
17131 	ipaddr_t dst;
17132 	in6_addr_t *v6dstp;
17133 	ipha_t *ipha;
17134 	ip6_t *ip6h;
17135 	ipsec_in_t *ii;
17136 	boolean_t ill_need_rele = B_FALSE;
17137 	boolean_t rill_need_rele = B_FALSE;
17138 	boolean_t ire_need_rele = B_FALSE;
17139 	netstack_t	*ns;
17140 	ip_stack_t	*ipst;
17141 
17142 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17143 	ASSERT(ii->ipsec_in_ill_index != 0);
17144 	ns = ii->ipsec_in_ns;
17145 	ASSERT(ii->ipsec_in_ns != NULL);
17146 	ipst = ns->netstack_ip;
17147 
17148 	mp = ipsec_mp->b_cont;
17149 	ASSERT(mp != NULL);
17150 
17151 	if (ill == NULL) {
17152 		ASSERT(recv_ill == NULL);
17153 		/*
17154 		 * We need to get the original queue on which ip_rput_local
17155 		 * or ip_rput_data_v6 was called.
17156 		 */
17157 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17158 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17159 		ill_need_rele = B_TRUE;
17160 
17161 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17162 			recv_ill = ill_lookup_on_ifindex(
17163 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17164 			    NULL, NULL, NULL, NULL, ipst);
17165 			rill_need_rele = B_TRUE;
17166 		} else {
17167 			recv_ill = ill;
17168 		}
17169 
17170 		if ((ill == NULL) || (recv_ill == NULL)) {
17171 			ip0dbg(("ip_fanout_proto_again: interface "
17172 			    "disappeared\n"));
17173 			if (ill != NULL)
17174 				ill_refrele(ill);
17175 			if (recv_ill != NULL)
17176 				ill_refrele(recv_ill);
17177 			freemsg(ipsec_mp);
17178 			return;
17179 		}
17180 	}
17181 
17182 	ASSERT(ill != NULL && recv_ill != NULL);
17183 
17184 	if (mp->b_datap->db_type == M_CTL) {
17185 		/*
17186 		 * AH/ESP is returning the ICMP message after
17187 		 * removing their headers. Fanout again till
17188 		 * it gets to the right protocol.
17189 		 */
17190 		if (ii->ipsec_in_v4) {
17191 			icmph_t *icmph;
17192 			int iph_hdr_length;
17193 			int hdr_length;
17194 
17195 			ipha = (ipha_t *)mp->b_rptr;
17196 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17197 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17198 			ipha = (ipha_t *)&icmph[1];
17199 			hdr_length = IPH_HDR_LENGTH(ipha);
17200 			/*
17201 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17202 			 * Reset the type to M_DATA.
17203 			 */
17204 			mp->b_datap->db_type = M_DATA;
17205 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17206 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17207 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17208 		} else {
17209 			icmp6_t *icmp6;
17210 			int hdr_length;
17211 
17212 			ip6h = (ip6_t *)mp->b_rptr;
17213 			/* Don't call hdr_length_v6() unless you have to. */
17214 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17215 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17216 			else
17217 				hdr_length = IPV6_HDR_LEN;
17218 
17219 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17220 			/*
17221 			 * icmp_inbound_error_fanout_v6 may need to do
17222 			 * pullupmsg.  Reset the type to M_DATA.
17223 			 */
17224 			mp->b_datap->db_type = M_DATA;
17225 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17226 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17227 			    ii->ipsec_in_zoneid);
17228 		}
17229 		if (ill_need_rele)
17230 			ill_refrele(ill);
17231 		if (rill_need_rele)
17232 			ill_refrele(recv_ill);
17233 		return;
17234 	}
17235 
17236 	if (ii->ipsec_in_v4) {
17237 		ipha = (ipha_t *)mp->b_rptr;
17238 		dst = ipha->ipha_dst;
17239 		if (CLASSD(dst)) {
17240 			/*
17241 			 * Multicast has to be delivered to all streams.
17242 			 */
17243 			dst = INADDR_BROADCAST;
17244 		}
17245 
17246 		if (ire == NULL) {
17247 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17248 			    msg_getlabel(mp), ipst);
17249 			if (ire == NULL) {
17250 				if (ill_need_rele)
17251 					ill_refrele(ill);
17252 				if (rill_need_rele)
17253 					ill_refrele(recv_ill);
17254 				ip1dbg(("ip_fanout_proto_again: "
17255 				    "IRE not found"));
17256 				freemsg(ipsec_mp);
17257 				return;
17258 			}
17259 			ire_need_rele = B_TRUE;
17260 		}
17261 
17262 		switch (ipha->ipha_protocol) {
17263 		case IPPROTO_UDP:
17264 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17265 			    recv_ill);
17266 			if (ire_need_rele)
17267 				ire_refrele(ire);
17268 			break;
17269 		case IPPROTO_TCP:
17270 			if (!ire_need_rele)
17271 				IRE_REFHOLD(ire);
17272 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17273 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17274 			IRE_REFRELE(ire);
17275 			if (mp != NULL) {
17276 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17277 				    mp, 1, SQ_PROCESS,
17278 				    SQTAG_IP_PROTO_AGAIN);
17279 			}
17280 			break;
17281 		case IPPROTO_SCTP:
17282 			if (!ire_need_rele)
17283 				IRE_REFHOLD(ire);
17284 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17285 			    ipsec_mp, 0, ill->ill_rq, dst);
17286 			break;
17287 		default:
17288 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17289 			    recv_ill, 0);
17290 			if (ire_need_rele)
17291 				ire_refrele(ire);
17292 			break;
17293 		}
17294 	} else {
17295 		uint32_t rput_flags = 0;
17296 
17297 		ip6h = (ip6_t *)mp->b_rptr;
17298 		v6dstp = &ip6h->ip6_dst;
17299 		/*
17300 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17301 		 * address.
17302 		 *
17303 		 * Currently, we don't store that state in the IPSEC_IN
17304 		 * message, and we may need to.
17305 		 */
17306 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17307 		    IP6_IN_LLMCAST : 0);
17308 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17309 		    NULL, NULL);
17310 	}
17311 	if (ill_need_rele)
17312 		ill_refrele(ill);
17313 	if (rill_need_rele)
17314 		ill_refrele(recv_ill);
17315 }
17316 
17317 /*
17318  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17319  * returns 'true' if there are still fragments left on the queue, in
17320  * which case we restart the timer.
17321  */
17322 void
17323 ill_frag_timer(void *arg)
17324 {
17325 	ill_t	*ill = (ill_t *)arg;
17326 	boolean_t frag_pending;
17327 	ip_stack_t	*ipst = ill->ill_ipst;
17328 	time_t	timeout;
17329 
17330 	mutex_enter(&ill->ill_lock);
17331 	ASSERT(!ill->ill_fragtimer_executing);
17332 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17333 		ill->ill_frag_timer_id = 0;
17334 		mutex_exit(&ill->ill_lock);
17335 		return;
17336 	}
17337 	ill->ill_fragtimer_executing = 1;
17338 	mutex_exit(&ill->ill_lock);
17339 
17340 	if (ill->ill_isv6)
17341 		timeout = ipst->ips_ipv6_frag_timeout;
17342 	else
17343 		timeout = ipst->ips_ip_g_frag_timeout;
17344 
17345 	frag_pending = ill_frag_timeout(ill, timeout);
17346 
17347 	/*
17348 	 * Restart the timer, if we have fragments pending or if someone
17349 	 * wanted us to be scheduled again.
17350 	 */
17351 	mutex_enter(&ill->ill_lock);
17352 	ill->ill_fragtimer_executing = 0;
17353 	ill->ill_frag_timer_id = 0;
17354 	if (frag_pending || ill->ill_fragtimer_needrestart)
17355 		ill_frag_timer_start(ill);
17356 	mutex_exit(&ill->ill_lock);
17357 }
17358 
17359 void
17360 ill_frag_timer_start(ill_t *ill)
17361 {
17362 	ip_stack_t	*ipst = ill->ill_ipst;
17363 	clock_t	timeo_ms;
17364 
17365 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17366 
17367 	/* If the ill is closing or opening don't proceed */
17368 	if (ill->ill_state_flags & ILL_CONDEMNED)
17369 		return;
17370 
17371 	if (ill->ill_fragtimer_executing) {
17372 		/*
17373 		 * ill_frag_timer is currently executing. Just record the
17374 		 * the fact that we want the timer to be restarted.
17375 		 * ill_frag_timer will post a timeout before it returns,
17376 		 * ensuring it will be called again.
17377 		 */
17378 		ill->ill_fragtimer_needrestart = 1;
17379 		return;
17380 	}
17381 
17382 	if (ill->ill_frag_timer_id == 0) {
17383 		if (ill->ill_isv6)
17384 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
17385 		else
17386 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
17387 		/*
17388 		 * The timer is neither running nor is the timeout handler
17389 		 * executing. Post a timeout so that ill_frag_timer will be
17390 		 * called
17391 		 */
17392 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17393 		    MSEC_TO_TICK(timeo_ms >> 1));
17394 		ill->ill_fragtimer_needrestart = 0;
17395 	}
17396 }
17397 
17398 /*
17399  * This routine is needed for loopback when forwarding multicasts.
17400  *
17401  * IPQoS Notes:
17402  * IPPF processing is done in fanout routines.
17403  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17404  * processing for IPsec packets is done when it comes back in clear.
17405  * NOTE : The callers of this function need to do the ire_refrele for the
17406  *	  ire that is being passed in.
17407  */
17408 void
17409 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17410     ill_t *recv_ill, uint32_t esp_udp_ports)
17411 {
17412 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17413 	ill_t	*ill = (ill_t *)q->q_ptr;
17414 	uint32_t	sum;
17415 	uint32_t	u1;
17416 	uint32_t	u2;
17417 	int		hdr_length;
17418 	boolean_t	mctl_present;
17419 	mblk_t		*first_mp = mp;
17420 	mblk_t		*hada_mp = NULL;
17421 	ipha_t		*inner_ipha;
17422 	ip_stack_t	*ipst;
17423 
17424 	ASSERT(recv_ill != NULL);
17425 	ipst = recv_ill->ill_ipst;
17426 
17427 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17428 	    "ip_rput_locl_start: q %p", q);
17429 
17430 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17431 	ASSERT(ill != NULL);
17432 
17433 #define	rptr	((uchar_t *)ipha)
17434 #define	iphs	((uint16_t *)ipha)
17435 
17436 	/*
17437 	 * no UDP or TCP packet should come here anymore.
17438 	 */
17439 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17440 	    ipha->ipha_protocol != IPPROTO_UDP);
17441 
17442 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17443 	if (mctl_present &&
17444 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17445 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17446 
17447 		/*
17448 		 * It's an IPsec accelerated packet.
17449 		 * Keep a pointer to the data attributes around until
17450 		 * we allocate the ipsec_info_t.
17451 		 */
17452 		IPSECHW_DEBUG(IPSECHW_PKT,
17453 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17454 		hada_mp = first_mp;
17455 		hada_mp->b_cont = NULL;
17456 		/*
17457 		 * Since it is accelerated, it comes directly from
17458 		 * the ill and the data attributes is followed by
17459 		 * the packet data.
17460 		 */
17461 		ASSERT(mp->b_datap->db_type != M_CTL);
17462 		first_mp = mp;
17463 		mctl_present = B_FALSE;
17464 	}
17465 
17466 	/*
17467 	 * IF M_CTL is not present, then ipsec_in_is_secure
17468 	 * should return B_TRUE. There is a case where loopback
17469 	 * packets has an M_CTL in the front with all the
17470 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17471 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17472 	 * packets never comes here, it is safe to ASSERT the
17473 	 * following.
17474 	 */
17475 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17476 
17477 	/*
17478 	 * Also, we should never have an mctl_present if this is an
17479 	 * ESP-in-UDP packet.
17480 	 */
17481 	ASSERT(!mctl_present || !esp_in_udp_packet);
17482 
17483 	/* u1 is # words of IP options */
17484 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17485 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17486 
17487 	/*
17488 	 * Don't verify header checksum if we just removed UDP header or
17489 	 * packet is coming back from AH/ESP.
17490 	 */
17491 	if (!esp_in_udp_packet && !mctl_present) {
17492 		if (u1) {
17493 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17494 				if (hada_mp != NULL)
17495 					freemsg(hada_mp);
17496 				return;
17497 			}
17498 		} else {
17499 			/* Check the IP header checksum.  */
17500 #define	uph	((uint16_t *)ipha)
17501 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17502 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17503 #undef  uph
17504 			/* finish doing IP checksum */
17505 			sum = (sum & 0xFFFF) + (sum >> 16);
17506 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17507 			if (sum && sum != 0xFFFF) {
17508 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17509 				goto drop_pkt;
17510 			}
17511 		}
17512 	}
17513 
17514 	/*
17515 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17516 	 * might be called more than once for secure packets, count only
17517 	 * the first time.
17518 	 */
17519 	if (!mctl_present) {
17520 		UPDATE_IB_PKT_COUNT(ire);
17521 		ire->ire_last_used_time = lbolt;
17522 	}
17523 
17524 	/* Check for fragmentation offset. */
17525 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17526 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17527 	if (u1) {
17528 		/*
17529 		 * We re-assemble fragments before we do the AH/ESP
17530 		 * processing. Thus, M_CTL should not be present
17531 		 * while we are re-assembling.
17532 		 */
17533 		ASSERT(!mctl_present);
17534 		ASSERT(first_mp == mp);
17535 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17536 			return;
17537 
17538 		/*
17539 		 * Make sure that first_mp points back to mp as
17540 		 * the mp we came in with could have changed in
17541 		 * ip_rput_fragment().
17542 		 */
17543 		ipha = (ipha_t *)mp->b_rptr;
17544 		first_mp = mp;
17545 	}
17546 
17547 	/*
17548 	 * Clear hardware checksumming flag as it is currently only
17549 	 * used by TCP and UDP.
17550 	 */
17551 	DB_CKSUMFLAGS(mp) = 0;
17552 
17553 	/* Now we have a complete datagram, destined for this machine. */
17554 	u1 = IPH_HDR_LENGTH(ipha);
17555 	switch (ipha->ipha_protocol) {
17556 	case IPPROTO_ICMP: {
17557 		ire_t		*ire_zone;
17558 		ilm_t		*ilm;
17559 		mblk_t		*mp1;
17560 		zoneid_t	last_zoneid;
17561 		ilm_walker_t	ilw;
17562 
17563 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17564 			ASSERT(ire->ire_type == IRE_BROADCAST);
17565 
17566 			/*
17567 			 * In the multicast case, applications may have joined
17568 			 * the group from different zones, so we need to deliver
17569 			 * the packet to each of them. Loop through the
17570 			 * multicast memberships structures (ilm) on the receive
17571 			 * ill and send a copy of the packet up each matching
17572 			 * one. However, we don't do this for multicasts sent on
17573 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17574 			 * they must stay in the sender's zone.
17575 			 *
17576 			 * ilm_add_v6() ensures that ilms in the same zone are
17577 			 * contiguous in the ill_ilm list. We use this property
17578 			 * to avoid sending duplicates needed when two
17579 			 * applications in the same zone join the same group on
17580 			 * different logical interfaces: we ignore the ilm if
17581 			 * its zoneid is the same as the last matching one.
17582 			 * In addition, the sending of the packet for
17583 			 * ire_zoneid is delayed until all of the other ilms
17584 			 * have been exhausted.
17585 			 */
17586 			last_zoneid = -1;
17587 			ilm = ilm_walker_start(&ilw, recv_ill);
17588 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17589 				if (ipha->ipha_dst != ilm->ilm_addr ||
17590 				    ilm->ilm_zoneid == last_zoneid ||
17591 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17592 				    ilm->ilm_zoneid == ALL_ZONES ||
17593 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17594 					continue;
17595 				mp1 = ip_copymsg(first_mp);
17596 				if (mp1 == NULL)
17597 					continue;
17598 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17599 				    0, sum, mctl_present, B_TRUE,
17600 				    recv_ill, ilm->ilm_zoneid);
17601 				last_zoneid = ilm->ilm_zoneid;
17602 			}
17603 			ilm_walker_finish(&ilw);
17604 		} else if (ire->ire_type == IRE_BROADCAST) {
17605 			/*
17606 			 * In the broadcast case, there may be many zones
17607 			 * which need a copy of the packet delivered to them.
17608 			 * There is one IRE_BROADCAST per broadcast address
17609 			 * and per zone; we walk those using a helper function.
17610 			 * In addition, the sending of the packet for ire is
17611 			 * delayed until all of the other ires have been
17612 			 * processed.
17613 			 */
17614 			IRB_REFHOLD(ire->ire_bucket);
17615 			ire_zone = NULL;
17616 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17617 			    ire)) != NULL) {
17618 				mp1 = ip_copymsg(first_mp);
17619 				if (mp1 == NULL)
17620 					continue;
17621 
17622 				UPDATE_IB_PKT_COUNT(ire_zone);
17623 				ire_zone->ire_last_used_time = lbolt;
17624 				icmp_inbound(q, mp1, B_TRUE, ill,
17625 				    0, sum, mctl_present, B_TRUE,
17626 				    recv_ill, ire_zone->ire_zoneid);
17627 			}
17628 			IRB_REFRELE(ire->ire_bucket);
17629 		}
17630 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17631 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17632 		    ire->ire_zoneid);
17633 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17634 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17635 		return;
17636 	}
17637 	case IPPROTO_IGMP:
17638 		/*
17639 		 * If we are not willing to accept IGMP packets in clear,
17640 		 * then check with global policy.
17641 		 */
17642 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17643 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17644 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17645 			if (first_mp == NULL)
17646 				return;
17647 		}
17648 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17649 			freemsg(first_mp);
17650 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17651 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17652 			return;
17653 		}
17654 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17655 			/* Bad packet - discarded by igmp_input */
17656 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17657 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17658 			if (mctl_present)
17659 				freeb(first_mp);
17660 			return;
17661 		}
17662 		/*
17663 		 * igmp_input() may have returned the pulled up message.
17664 		 * So first_mp and ipha need to be reinitialized.
17665 		 */
17666 		ipha = (ipha_t *)mp->b_rptr;
17667 		if (mctl_present)
17668 			first_mp->b_cont = mp;
17669 		else
17670 			first_mp = mp;
17671 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17672 		    connf_head != NULL) {
17673 			/* No user-level listener for IGMP packets */
17674 			goto drop_pkt;
17675 		}
17676 		/* deliver to local raw users */
17677 		break;
17678 	case IPPROTO_PIM:
17679 		/*
17680 		 * If we are not willing to accept PIM packets in clear,
17681 		 * then check with global policy.
17682 		 */
17683 		if (ipst->ips_pim_accept_clear_messages == 0) {
17684 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17685 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17686 			if (first_mp == NULL)
17687 				return;
17688 		}
17689 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17690 			freemsg(first_mp);
17691 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17692 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17693 			return;
17694 		}
17695 		if (pim_input(q, mp, ill) != 0) {
17696 			/* Bad packet - discarded by pim_input */
17697 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17698 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17699 			if (mctl_present)
17700 				freeb(first_mp);
17701 			return;
17702 		}
17703 
17704 		/*
17705 		 * pim_input() may have pulled up the message so ipha needs to
17706 		 * be reinitialized.
17707 		 */
17708 		ipha = (ipha_t *)mp->b_rptr;
17709 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17710 		    connf_head != NULL) {
17711 			/* No user-level listener for PIM packets */
17712 			goto drop_pkt;
17713 		}
17714 		/* deliver to local raw users */
17715 		break;
17716 	case IPPROTO_ENCAP:
17717 		/*
17718 		 * Handle self-encapsulated packets (IP-in-IP where
17719 		 * the inner addresses == the outer addresses).
17720 		 */
17721 		hdr_length = IPH_HDR_LENGTH(ipha);
17722 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17723 		    mp->b_wptr) {
17724 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17725 			    sizeof (ipha_t) - mp->b_rptr)) {
17726 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17727 				freemsg(first_mp);
17728 				return;
17729 			}
17730 			ipha = (ipha_t *)mp->b_rptr;
17731 		}
17732 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17733 		/*
17734 		 * Check the sanity of the inner IP header.
17735 		 */
17736 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17737 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17738 			freemsg(first_mp);
17739 			return;
17740 		}
17741 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17742 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17743 			freemsg(first_mp);
17744 			return;
17745 		}
17746 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17747 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17748 			ipsec_in_t *ii;
17749 
17750 			/*
17751 			 * Self-encapsulated tunnel packet. Remove
17752 			 * the outer IP header and fanout again.
17753 			 * We also need to make sure that the inner
17754 			 * header is pulled up until options.
17755 			 */
17756 			mp->b_rptr = (uchar_t *)inner_ipha;
17757 			ipha = inner_ipha;
17758 			hdr_length = IPH_HDR_LENGTH(ipha);
17759 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17760 				if (!pullupmsg(mp, (uchar_t *)ipha +
17761 				    + hdr_length - mp->b_rptr)) {
17762 					freemsg(first_mp);
17763 					return;
17764 				}
17765 				ipha = (ipha_t *)mp->b_rptr;
17766 			}
17767 			if (hdr_length > sizeof (ipha_t)) {
17768 				/* We got options on the inner packet. */
17769 				ipaddr_t dst = ipha->ipha_dst;
17770 
17771 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17772 				    -1) {
17773 					/* Bad options! */
17774 					return;
17775 				}
17776 				if (dst != ipha->ipha_dst) {
17777 					/*
17778 					 * Someone put a source-route in
17779 					 * the inside header of a self-
17780 					 * encapsulated packet.  Drop it
17781 					 * with extreme prejudice and let
17782 					 * the sender know.
17783 					 */
17784 					icmp_unreachable(q, first_mp,
17785 					    ICMP_SOURCE_ROUTE_FAILED,
17786 					    recv_ill->ill_zoneid, ipst);
17787 					return;
17788 				}
17789 			}
17790 			if (!mctl_present) {
17791 				ASSERT(first_mp == mp);
17792 				/*
17793 				 * This means that somebody is sending
17794 				 * Self-encapsualted packets without AH/ESP.
17795 				 * If AH/ESP was present, we would have already
17796 				 * allocated the first_mp.
17797 				 *
17798 				 * Send this packet to find a tunnel endpoint.
17799 				 * if I can't find one, an ICMP
17800 				 * PROTOCOL_UNREACHABLE will get sent.
17801 				 */
17802 				goto fanout;
17803 			}
17804 			/*
17805 			 * We generally store the ill_index if we need to
17806 			 * do IPsec processing as we lose the ill queue when
17807 			 * we come back. But in this case, we never should
17808 			 * have to store the ill_index here as it should have
17809 			 * been stored previously when we processed the
17810 			 * AH/ESP header in this routine or for non-ipsec
17811 			 * cases, we still have the queue. But for some bad
17812 			 * packets from the wire, we can get to IPsec after
17813 			 * this and we better store the index for that case.
17814 			 */
17815 			ill = (ill_t *)q->q_ptr;
17816 			ii = (ipsec_in_t *)first_mp->b_rptr;
17817 			ii->ipsec_in_ill_index =
17818 			    ill->ill_phyint->phyint_ifindex;
17819 			ii->ipsec_in_rill_index =
17820 			    recv_ill->ill_phyint->phyint_ifindex;
17821 			if (ii->ipsec_in_decaps) {
17822 				/*
17823 				 * This packet is self-encapsulated multiple
17824 				 * times. We don't want to recurse infinitely.
17825 				 * To keep it simple, drop the packet.
17826 				 */
17827 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17828 				freemsg(first_mp);
17829 				return;
17830 			}
17831 			ii->ipsec_in_decaps = B_TRUE;
17832 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17833 			    ire);
17834 			return;
17835 		}
17836 		break;
17837 	case IPPROTO_AH:
17838 	case IPPROTO_ESP: {
17839 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17840 
17841 		/*
17842 		 * Fast path for AH/ESP. If this is the first time
17843 		 * we are sending a datagram to AH/ESP, allocate
17844 		 * a IPSEC_IN message and prepend it. Otherwise,
17845 		 * just fanout.
17846 		 */
17847 
17848 		int ipsec_rc;
17849 		ipsec_in_t *ii;
17850 		netstack_t *ns = ipst->ips_netstack;
17851 
17852 		IP_STAT(ipst, ipsec_proto_ahesp);
17853 		if (!mctl_present) {
17854 			ASSERT(first_mp == mp);
17855 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17856 			if (first_mp == NULL) {
17857 				ip1dbg(("ip_proto_input: IPSEC_IN "
17858 				    "allocation failure.\n"));
17859 				freemsg(hada_mp); /* okay ifnull */
17860 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17861 				freemsg(mp);
17862 				return;
17863 			}
17864 			/*
17865 			 * Store the ill_index so that when we come back
17866 			 * from IPsec we ride on the same queue.
17867 			 */
17868 			ill = (ill_t *)q->q_ptr;
17869 			ii = (ipsec_in_t *)first_mp->b_rptr;
17870 			ii->ipsec_in_ill_index =
17871 			    ill->ill_phyint->phyint_ifindex;
17872 			ii->ipsec_in_rill_index =
17873 			    recv_ill->ill_phyint->phyint_ifindex;
17874 			first_mp->b_cont = mp;
17875 			/*
17876 			 * Cache hardware acceleration info.
17877 			 */
17878 			if (hada_mp != NULL) {
17879 				IPSECHW_DEBUG(IPSECHW_PKT,
17880 				    ("ip_rput_local: caching data attr.\n"));
17881 				ii->ipsec_in_accelerated = B_TRUE;
17882 				ii->ipsec_in_da = hada_mp;
17883 				hada_mp = NULL;
17884 			}
17885 		} else {
17886 			ii = (ipsec_in_t *)first_mp->b_rptr;
17887 		}
17888 
17889 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17890 
17891 		if (!ipsec_loaded(ipss)) {
17892 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17893 			    ire->ire_zoneid, ipst);
17894 			return;
17895 		}
17896 
17897 		ns = ipst->ips_netstack;
17898 		/* select inbound SA and have IPsec process the pkt */
17899 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17900 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17901 			boolean_t esp_in_udp_sa;
17902 			if (esph == NULL)
17903 				return;
17904 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17905 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17906 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17907 			    IPSA_F_NATT) != 0);
17908 			/*
17909 			 * The following is a fancy, but quick, way of saying:
17910 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17911 			 *    OR
17912 			 * ESP SA and ESP-in-UDP packet --> drop
17913 			 */
17914 			if (esp_in_udp_sa != esp_in_udp_packet) {
17915 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17916 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17917 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17918 				    &ns->netstack_ipsec->ipsec_dropper);
17919 				return;
17920 			}
17921 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17922 			    first_mp, esph);
17923 		} else {
17924 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17925 			if (ah == NULL)
17926 				return;
17927 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17928 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17929 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17930 			    first_mp, ah);
17931 		}
17932 
17933 		switch (ipsec_rc) {
17934 		case IPSEC_STATUS_SUCCESS:
17935 			break;
17936 		case IPSEC_STATUS_FAILED:
17937 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17938 			/* FALLTHRU */
17939 		case IPSEC_STATUS_PENDING:
17940 			return;
17941 		}
17942 		/* we're done with IPsec processing, send it up */
17943 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17944 		return;
17945 	}
17946 	default:
17947 		break;
17948 	}
17949 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17950 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17951 		    ire->ire_zoneid));
17952 		goto drop_pkt;
17953 	}
17954 	/*
17955 	 * Handle protocols with which IP is less intimate.  There
17956 	 * can be more than one stream bound to a particular
17957 	 * protocol.  When this is the case, each one gets a copy
17958 	 * of any incoming packets.
17959 	 */
17960 fanout:
17961 	ip_fanout_proto(q, first_mp, ill, ipha,
17962 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17963 	    B_TRUE, recv_ill, ire->ire_zoneid);
17964 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17965 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17966 	return;
17967 
17968 drop_pkt:
17969 	freemsg(first_mp);
17970 	if (hada_mp != NULL)
17971 		freeb(hada_mp);
17972 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17973 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17974 #undef	rptr
17975 #undef  iphs
17976 
17977 }
17978 
17979 /*
17980  * Update any source route, record route or timestamp options.
17981  * Check that we are at end of strict source route.
17982  * The options have already been checked for sanity in ip_rput_options().
17983  */
17984 static boolean_t
17985 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17986     ip_stack_t *ipst)
17987 {
17988 	ipoptp_t	opts;
17989 	uchar_t		*opt;
17990 	uint8_t		optval;
17991 	uint8_t		optlen;
17992 	ipaddr_t	dst;
17993 	uint32_t	ts;
17994 	ire_t		*dst_ire;
17995 	timestruc_t	now;
17996 	zoneid_t	zoneid;
17997 	ill_t		*ill;
17998 
17999 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18000 
18001 	ip2dbg(("ip_rput_local_options\n"));
18002 
18003 	for (optval = ipoptp_first(&opts, ipha);
18004 	    optval != IPOPT_EOL;
18005 	    optval = ipoptp_next(&opts)) {
18006 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18007 		opt = opts.ipoptp_cur;
18008 		optlen = opts.ipoptp_len;
18009 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18010 		    optval, optlen));
18011 		switch (optval) {
18012 			uint32_t off;
18013 		case IPOPT_SSRR:
18014 		case IPOPT_LSRR:
18015 			off = opt[IPOPT_OFFSET];
18016 			off--;
18017 			if (optlen < IP_ADDR_LEN ||
18018 			    off > optlen - IP_ADDR_LEN) {
18019 				/* End of source route */
18020 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18021 				break;
18022 			}
18023 			/*
18024 			 * This will only happen if two consecutive entries
18025 			 * in the source route contains our address or if
18026 			 * it is a packet with a loose source route which
18027 			 * reaches us before consuming the whole source route
18028 			 */
18029 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18030 			if (optval == IPOPT_SSRR) {
18031 				goto bad_src_route;
18032 			}
18033 			/*
18034 			 * Hack: instead of dropping the packet truncate the
18035 			 * source route to what has been used by filling the
18036 			 * rest with IPOPT_NOP.
18037 			 */
18038 			opt[IPOPT_OLEN] = (uint8_t)off;
18039 			while (off < optlen) {
18040 				opt[off++] = IPOPT_NOP;
18041 			}
18042 			break;
18043 		case IPOPT_RR:
18044 			off = opt[IPOPT_OFFSET];
18045 			off--;
18046 			if (optlen < IP_ADDR_LEN ||
18047 			    off > optlen - IP_ADDR_LEN) {
18048 				/* No more room - ignore */
18049 				ip1dbg((
18050 				    "ip_rput_local_options: end of RR\n"));
18051 				break;
18052 			}
18053 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18054 			    IP_ADDR_LEN);
18055 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18056 			break;
18057 		case IPOPT_TS:
18058 			/* Insert timestamp if there is romm */
18059 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18060 			case IPOPT_TS_TSONLY:
18061 				off = IPOPT_TS_TIMELEN;
18062 				break;
18063 			case IPOPT_TS_PRESPEC:
18064 			case IPOPT_TS_PRESPEC_RFC791:
18065 				/* Verify that the address matched */
18066 				off = opt[IPOPT_OFFSET] - 1;
18067 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18068 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18069 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18070 				    ipst);
18071 				if (dst_ire == NULL) {
18072 					/* Not for us */
18073 					break;
18074 				}
18075 				ire_refrele(dst_ire);
18076 				/* FALLTHRU */
18077 			case IPOPT_TS_TSANDADDR:
18078 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18079 				break;
18080 			default:
18081 				/*
18082 				 * ip_*put_options should have already
18083 				 * dropped this packet.
18084 				 */
18085 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18086 				    "unknown IT - bug in ip_rput_options?\n");
18087 				return (B_TRUE);	/* Keep "lint" happy */
18088 			}
18089 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18090 				/* Increase overflow counter */
18091 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18092 				opt[IPOPT_POS_OV_FLG] =
18093 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18094 				    (off << 4));
18095 				break;
18096 			}
18097 			off = opt[IPOPT_OFFSET] - 1;
18098 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18099 			case IPOPT_TS_PRESPEC:
18100 			case IPOPT_TS_PRESPEC_RFC791:
18101 			case IPOPT_TS_TSANDADDR:
18102 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18103 				    IP_ADDR_LEN);
18104 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18105 				/* FALLTHRU */
18106 			case IPOPT_TS_TSONLY:
18107 				off = opt[IPOPT_OFFSET] - 1;
18108 				/* Compute # of milliseconds since midnight */
18109 				gethrestime(&now);
18110 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18111 				    now.tv_nsec / (NANOSEC / MILLISEC);
18112 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18113 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18114 				break;
18115 			}
18116 			break;
18117 		}
18118 	}
18119 	return (B_TRUE);
18120 
18121 bad_src_route:
18122 	q = WR(q);
18123 	if (q->q_next != NULL)
18124 		ill = q->q_ptr;
18125 	else
18126 		ill = NULL;
18127 
18128 	/* make sure we clear any indication of a hardware checksum */
18129 	DB_CKSUMFLAGS(mp) = 0;
18130 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18131 	if (zoneid == ALL_ZONES)
18132 		freemsg(mp);
18133 	else
18134 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18135 	return (B_FALSE);
18136 
18137 }
18138 
18139 /*
18140  * Process IP options in an inbound packet.  If an option affects the
18141  * effective destination address, return the next hop address via dstp.
18142  * Returns -1 if something fails in which case an ICMP error has been sent
18143  * and mp freed.
18144  */
18145 static int
18146 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18147     ip_stack_t *ipst)
18148 {
18149 	ipoptp_t	opts;
18150 	uchar_t		*opt;
18151 	uint8_t		optval;
18152 	uint8_t		optlen;
18153 	ipaddr_t	dst;
18154 	intptr_t	code = 0;
18155 	ire_t		*ire = NULL;
18156 	zoneid_t	zoneid;
18157 	ill_t		*ill;
18158 
18159 	ip2dbg(("ip_rput_options\n"));
18160 	dst = ipha->ipha_dst;
18161 	for (optval = ipoptp_first(&opts, ipha);
18162 	    optval != IPOPT_EOL;
18163 	    optval = ipoptp_next(&opts)) {
18164 		opt = opts.ipoptp_cur;
18165 		optlen = opts.ipoptp_len;
18166 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18167 		    optval, optlen));
18168 		/*
18169 		 * Note: we need to verify the checksum before we
18170 		 * modify anything thus this routine only extracts the next
18171 		 * hop dst from any source route.
18172 		 */
18173 		switch (optval) {
18174 			uint32_t off;
18175 		case IPOPT_SSRR:
18176 		case IPOPT_LSRR:
18177 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18178 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18179 			if (ire == NULL) {
18180 				if (optval == IPOPT_SSRR) {
18181 					ip1dbg(("ip_rput_options: not next"
18182 					    " strict source route 0x%x\n",
18183 					    ntohl(dst)));
18184 					code = (char *)&ipha->ipha_dst -
18185 					    (char *)ipha;
18186 					goto param_prob; /* RouterReq's */
18187 				}
18188 				ip2dbg(("ip_rput_options: "
18189 				    "not next source route 0x%x\n",
18190 				    ntohl(dst)));
18191 				break;
18192 			}
18193 			ire_refrele(ire);
18194 
18195 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18196 				ip1dbg((
18197 				    "ip_rput_options: bad option offset\n"));
18198 				code = (char *)&opt[IPOPT_OLEN] -
18199 				    (char *)ipha;
18200 				goto param_prob;
18201 			}
18202 			off = opt[IPOPT_OFFSET];
18203 			off--;
18204 		redo_srr:
18205 			if (optlen < IP_ADDR_LEN ||
18206 			    off > optlen - IP_ADDR_LEN) {
18207 				/* End of source route */
18208 				ip1dbg(("ip_rput_options: end of SR\n"));
18209 				break;
18210 			}
18211 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18212 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18213 			    ntohl(dst)));
18214 
18215 			/*
18216 			 * Check if our address is present more than
18217 			 * once as consecutive hops in source route.
18218 			 * XXX verify per-interface ip_forwarding
18219 			 * for source route?
18220 			 */
18221 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18222 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18223 
18224 			if (ire != NULL) {
18225 				ire_refrele(ire);
18226 				off += IP_ADDR_LEN;
18227 				goto redo_srr;
18228 			}
18229 
18230 			if (dst == htonl(INADDR_LOOPBACK)) {
18231 				ip1dbg(("ip_rput_options: loopback addr in "
18232 				    "source route!\n"));
18233 				goto bad_src_route;
18234 			}
18235 			/*
18236 			 * For strict: verify that dst is directly
18237 			 * reachable.
18238 			 */
18239 			if (optval == IPOPT_SSRR) {
18240 				ire = ire_ftable_lookup(dst, 0, 0,
18241 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18242 				    msg_getlabel(mp),
18243 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18244 				if (ire == NULL) {
18245 					ip1dbg(("ip_rput_options: SSRR not "
18246 					    "directly reachable: 0x%x\n",
18247 					    ntohl(dst)));
18248 					goto bad_src_route;
18249 				}
18250 				ire_refrele(ire);
18251 			}
18252 			/*
18253 			 * Defer update of the offset and the record route
18254 			 * until the packet is forwarded.
18255 			 */
18256 			break;
18257 		case IPOPT_RR:
18258 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18259 				ip1dbg((
18260 				    "ip_rput_options: bad option offset\n"));
18261 				code = (char *)&opt[IPOPT_OLEN] -
18262 				    (char *)ipha;
18263 				goto param_prob;
18264 			}
18265 			break;
18266 		case IPOPT_TS:
18267 			/*
18268 			 * Verify that length >= 5 and that there is either
18269 			 * room for another timestamp or that the overflow
18270 			 * counter is not maxed out.
18271 			 */
18272 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18273 			if (optlen < IPOPT_MINLEN_IT) {
18274 				goto param_prob;
18275 			}
18276 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18277 				ip1dbg((
18278 				    "ip_rput_options: bad option offset\n"));
18279 				code = (char *)&opt[IPOPT_OFFSET] -
18280 				    (char *)ipha;
18281 				goto param_prob;
18282 			}
18283 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18284 			case IPOPT_TS_TSONLY:
18285 				off = IPOPT_TS_TIMELEN;
18286 				break;
18287 			case IPOPT_TS_TSANDADDR:
18288 			case IPOPT_TS_PRESPEC:
18289 			case IPOPT_TS_PRESPEC_RFC791:
18290 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18291 				break;
18292 			default:
18293 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18294 				    (char *)ipha;
18295 				goto param_prob;
18296 			}
18297 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18298 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18299 				/*
18300 				 * No room and the overflow counter is 15
18301 				 * already.
18302 				 */
18303 				goto param_prob;
18304 			}
18305 			break;
18306 		}
18307 	}
18308 
18309 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18310 		*dstp = dst;
18311 		return (0);
18312 	}
18313 
18314 	ip1dbg(("ip_rput_options: error processing IP options."));
18315 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18316 
18317 param_prob:
18318 	q = WR(q);
18319 	if (q->q_next != NULL)
18320 		ill = q->q_ptr;
18321 	else
18322 		ill = NULL;
18323 
18324 	/* make sure we clear any indication of a hardware checksum */
18325 	DB_CKSUMFLAGS(mp) = 0;
18326 	/* Don't know whether this is for non-global or global/forwarding */
18327 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18328 	if (zoneid == ALL_ZONES)
18329 		freemsg(mp);
18330 	else
18331 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18332 	return (-1);
18333 
18334 bad_src_route:
18335 	q = WR(q);
18336 	if (q->q_next != NULL)
18337 		ill = q->q_ptr;
18338 	else
18339 		ill = NULL;
18340 
18341 	/* make sure we clear any indication of a hardware checksum */
18342 	DB_CKSUMFLAGS(mp) = 0;
18343 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18344 	if (zoneid == ALL_ZONES)
18345 		freemsg(mp);
18346 	else
18347 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18348 	return (-1);
18349 }
18350 
18351 /*
18352  * IP & ICMP info in >=14 msg's ...
18353  *  - ip fixed part (mib2_ip_t)
18354  *  - icmp fixed part (mib2_icmp_t)
18355  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18356  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18357  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18358  *  - ipRouteAttributeTable (ip 102)	labeled routes
18359  *  - ip multicast membership (ip_member_t)
18360  *  - ip multicast source filtering (ip_grpsrc_t)
18361  *  - igmp fixed part (struct igmpstat)
18362  *  - multicast routing stats (struct mrtstat)
18363  *  - multicast routing vifs (array of struct vifctl)
18364  *  - multicast routing routes (array of struct mfcctl)
18365  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18366  *					One per ill plus one generic
18367  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18368  *					One per ill plus one generic
18369  *  - ipv6RouteEntry			all IPv6 IREs
18370  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18371  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18372  *  - ipv6AddrEntry			all IPv6 ipifs
18373  *  - ipv6 multicast membership (ipv6_member_t)
18374  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18375  *
18376  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18377  *
18378  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18379  * already filled in by the caller.
18380  * Return value of 0 indicates that no messages were sent and caller
18381  * should free mpctl.
18382  */
18383 int
18384 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18385 {
18386 	ip_stack_t *ipst;
18387 	sctp_stack_t *sctps;
18388 
18389 	if (q->q_next != NULL) {
18390 		ipst = ILLQ_TO_IPST(q);
18391 	} else {
18392 		ipst = CONNQ_TO_IPST(q);
18393 	}
18394 	ASSERT(ipst != NULL);
18395 	sctps = ipst->ips_netstack->netstack_sctp;
18396 
18397 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18398 		return (0);
18399 	}
18400 
18401 	/*
18402 	 * For the purposes of the (broken) packet shell use
18403 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18404 	 * to make TCP and UDP appear first in the list of mib items.
18405 	 * TBD: We could expand this and use it in netstat so that
18406 	 * the kernel doesn't have to produce large tables (connections,
18407 	 * routes, etc) when netstat only wants the statistics or a particular
18408 	 * table.
18409 	 */
18410 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18411 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18412 			return (1);
18413 		}
18414 	}
18415 
18416 	if (level != MIB2_TCP) {
18417 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18418 			return (1);
18419 		}
18420 	}
18421 
18422 	if (level != MIB2_UDP) {
18423 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18424 			return (1);
18425 		}
18426 	}
18427 
18428 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18429 	    ipst)) == NULL) {
18430 		return (1);
18431 	}
18432 
18433 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18434 		return (1);
18435 	}
18436 
18437 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18438 		return (1);
18439 	}
18440 
18441 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18442 		return (1);
18443 	}
18444 
18445 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18446 		return (1);
18447 	}
18448 
18449 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18450 		return (1);
18451 	}
18452 
18453 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18454 		return (1);
18455 	}
18456 
18457 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18458 		return (1);
18459 	}
18460 
18461 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18462 		return (1);
18463 	}
18464 
18465 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18466 		return (1);
18467 	}
18468 
18469 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18470 		return (1);
18471 	}
18472 
18473 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18474 		return (1);
18475 	}
18476 
18477 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18478 		return (1);
18479 	}
18480 
18481 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18482 		return (1);
18483 	}
18484 
18485 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18486 	if (mpctl == NULL)
18487 		return (1);
18488 
18489 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18490 	if (mpctl == NULL)
18491 		return (1);
18492 
18493 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18494 		return (1);
18495 	}
18496 	freemsg(mpctl);
18497 	return (1);
18498 }
18499 
18500 /* Get global (legacy) IPv4 statistics */
18501 static mblk_t *
18502 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18503     ip_stack_t *ipst)
18504 {
18505 	mib2_ip_t		old_ip_mib;
18506 	struct opthdr		*optp;
18507 	mblk_t			*mp2ctl;
18508 
18509 	/*
18510 	 * make a copy of the original message
18511 	 */
18512 	mp2ctl = copymsg(mpctl);
18513 
18514 	/* fixed length IP structure... */
18515 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18516 	optp->level = MIB2_IP;
18517 	optp->name = 0;
18518 	SET_MIB(old_ip_mib.ipForwarding,
18519 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18520 	SET_MIB(old_ip_mib.ipDefaultTTL,
18521 	    (uint32_t)ipst->ips_ip_def_ttl);
18522 	SET_MIB(old_ip_mib.ipReasmTimeout,
18523 	    ipst->ips_ip_g_frag_timeout);
18524 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18525 	    sizeof (mib2_ipAddrEntry_t));
18526 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18527 	    sizeof (mib2_ipRouteEntry_t));
18528 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18529 	    sizeof (mib2_ipNetToMediaEntry_t));
18530 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18531 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18532 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18533 	    sizeof (mib2_ipAttributeEntry_t));
18534 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18535 
18536 	/*
18537 	 * Grab the statistics from the new IP MIB
18538 	 */
18539 	SET_MIB(old_ip_mib.ipInReceives,
18540 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18541 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18542 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18543 	SET_MIB(old_ip_mib.ipForwDatagrams,
18544 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18545 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18546 	    ipmib->ipIfStatsInUnknownProtos);
18547 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18548 	SET_MIB(old_ip_mib.ipInDelivers,
18549 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18550 	SET_MIB(old_ip_mib.ipOutRequests,
18551 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18552 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18553 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18554 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18555 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18556 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18557 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18558 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18559 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18560 
18561 	/* ipRoutingDiscards is not being used */
18562 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18563 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18564 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18565 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18566 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18567 	    ipmib->ipIfStatsReasmDuplicates);
18568 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18569 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18570 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18571 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18572 	SET_MIB(old_ip_mib.rawipInOverflows,
18573 	    ipmib->rawipIfStatsInOverflows);
18574 
18575 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18576 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18577 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18578 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18579 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18580 	    ipmib->ipIfStatsOutSwitchIPVersion);
18581 
18582 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18583 	    (int)sizeof (old_ip_mib))) {
18584 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18585 		    (uint_t)sizeof (old_ip_mib)));
18586 	}
18587 
18588 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18589 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18590 	    (int)optp->level, (int)optp->name, (int)optp->len));
18591 	qreply(q, mpctl);
18592 	return (mp2ctl);
18593 }
18594 
18595 /* Per interface IPv4 statistics */
18596 static mblk_t *
18597 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18598 {
18599 	struct opthdr		*optp;
18600 	mblk_t			*mp2ctl;
18601 	ill_t			*ill;
18602 	ill_walk_context_t	ctx;
18603 	mblk_t			*mp_tail = NULL;
18604 	mib2_ipIfStatsEntry_t	global_ip_mib;
18605 
18606 	/*
18607 	 * Make a copy of the original message
18608 	 */
18609 	mp2ctl = copymsg(mpctl);
18610 
18611 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18612 	optp->level = MIB2_IP;
18613 	optp->name = MIB2_IP_TRAFFIC_STATS;
18614 	/* Include "unknown interface" ip_mib */
18615 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18616 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18617 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18618 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18619 	    (ipst->ips_ip_g_forward ? 1 : 2));
18620 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18621 	    (uint32_t)ipst->ips_ip_def_ttl);
18622 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18623 	    sizeof (mib2_ipIfStatsEntry_t));
18624 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18625 	    sizeof (mib2_ipAddrEntry_t));
18626 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18627 	    sizeof (mib2_ipRouteEntry_t));
18628 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18629 	    sizeof (mib2_ipNetToMediaEntry_t));
18630 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18631 	    sizeof (ip_member_t));
18632 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18633 	    sizeof (ip_grpsrc_t));
18634 
18635 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18636 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18637 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18638 		    "failed to allocate %u bytes\n",
18639 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18640 	}
18641 
18642 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18643 
18644 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18645 	ill = ILL_START_WALK_V4(&ctx, ipst);
18646 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18647 		ill->ill_ip_mib->ipIfStatsIfIndex =
18648 		    ill->ill_phyint->phyint_ifindex;
18649 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18650 		    (ipst->ips_ip_g_forward ? 1 : 2));
18651 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18652 		    (uint32_t)ipst->ips_ip_def_ttl);
18653 
18654 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18655 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18656 		    (char *)ill->ill_ip_mib,
18657 		    (int)sizeof (*ill->ill_ip_mib))) {
18658 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18659 			    "failed to allocate %u bytes\n",
18660 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18661 		}
18662 	}
18663 	rw_exit(&ipst->ips_ill_g_lock);
18664 
18665 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18666 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18667 	    "level %d, name %d, len %d\n",
18668 	    (int)optp->level, (int)optp->name, (int)optp->len));
18669 	qreply(q, mpctl);
18670 
18671 	if (mp2ctl == NULL)
18672 		return (NULL);
18673 
18674 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18675 }
18676 
18677 /* Global IPv4 ICMP statistics */
18678 static mblk_t *
18679 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18680 {
18681 	struct opthdr		*optp;
18682 	mblk_t			*mp2ctl;
18683 
18684 	/*
18685 	 * Make a copy of the original message
18686 	 */
18687 	mp2ctl = copymsg(mpctl);
18688 
18689 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18690 	optp->level = MIB2_ICMP;
18691 	optp->name = 0;
18692 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18693 	    (int)sizeof (ipst->ips_icmp_mib))) {
18694 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18695 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18696 	}
18697 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18698 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18699 	    (int)optp->level, (int)optp->name, (int)optp->len));
18700 	qreply(q, mpctl);
18701 	return (mp2ctl);
18702 }
18703 
18704 /* Global IPv4 IGMP statistics */
18705 static mblk_t *
18706 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18707 {
18708 	struct opthdr		*optp;
18709 	mblk_t			*mp2ctl;
18710 
18711 	/*
18712 	 * make a copy of the original message
18713 	 */
18714 	mp2ctl = copymsg(mpctl);
18715 
18716 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18717 	optp->level = EXPER_IGMP;
18718 	optp->name = 0;
18719 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18720 	    (int)sizeof (ipst->ips_igmpstat))) {
18721 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18722 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18723 	}
18724 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18725 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18726 	    (int)optp->level, (int)optp->name, (int)optp->len));
18727 	qreply(q, mpctl);
18728 	return (mp2ctl);
18729 }
18730 
18731 /* Global IPv4 Multicast Routing statistics */
18732 static mblk_t *
18733 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18734 {
18735 	struct opthdr		*optp;
18736 	mblk_t			*mp2ctl;
18737 
18738 	/*
18739 	 * make a copy of the original message
18740 	 */
18741 	mp2ctl = copymsg(mpctl);
18742 
18743 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18744 	optp->level = EXPER_DVMRP;
18745 	optp->name = 0;
18746 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18747 		ip0dbg(("ip_mroute_stats: failed\n"));
18748 	}
18749 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18750 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18751 	    (int)optp->level, (int)optp->name, (int)optp->len));
18752 	qreply(q, mpctl);
18753 	return (mp2ctl);
18754 }
18755 
18756 /* IPv4 address information */
18757 static mblk_t *
18758 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18759 {
18760 	struct opthdr		*optp;
18761 	mblk_t			*mp2ctl;
18762 	mblk_t			*mp_tail = NULL;
18763 	ill_t			*ill;
18764 	ipif_t			*ipif;
18765 	uint_t			bitval;
18766 	mib2_ipAddrEntry_t	mae;
18767 	zoneid_t		zoneid;
18768 	ill_walk_context_t ctx;
18769 
18770 	/*
18771 	 * make a copy of the original message
18772 	 */
18773 	mp2ctl = copymsg(mpctl);
18774 
18775 	/* ipAddrEntryTable */
18776 
18777 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18778 	optp->level = MIB2_IP;
18779 	optp->name = MIB2_IP_ADDR;
18780 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18781 
18782 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18783 	ill = ILL_START_WALK_V4(&ctx, ipst);
18784 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18785 		for (ipif = ill->ill_ipif; ipif != NULL;
18786 		    ipif = ipif->ipif_next) {
18787 			if (ipif->ipif_zoneid != zoneid &&
18788 			    ipif->ipif_zoneid != ALL_ZONES)
18789 				continue;
18790 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18791 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18792 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18793 
18794 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18795 			    OCTET_LENGTH);
18796 			mae.ipAdEntIfIndex.o_length =
18797 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18798 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18799 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18800 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18801 			mae.ipAdEntInfo.ae_subnet_len =
18802 			    ip_mask_to_plen(ipif->ipif_net_mask);
18803 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18804 			for (bitval = 1;
18805 			    bitval &&
18806 			    !(bitval & ipif->ipif_brd_addr);
18807 			    bitval <<= 1)
18808 				noop;
18809 			mae.ipAdEntBcastAddr = bitval;
18810 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18811 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18812 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18813 			mae.ipAdEntInfo.ae_broadcast_addr =
18814 			    ipif->ipif_brd_addr;
18815 			mae.ipAdEntInfo.ae_pp_dst_addr =
18816 			    ipif->ipif_pp_dst_addr;
18817 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18818 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18819 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18820 
18821 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18822 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18823 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18824 				    "allocate %u bytes\n",
18825 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18826 			}
18827 		}
18828 	}
18829 	rw_exit(&ipst->ips_ill_g_lock);
18830 
18831 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18832 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18833 	    (int)optp->level, (int)optp->name, (int)optp->len));
18834 	qreply(q, mpctl);
18835 	return (mp2ctl);
18836 }
18837 
18838 /* IPv6 address information */
18839 static mblk_t *
18840 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18841 {
18842 	struct opthdr		*optp;
18843 	mblk_t			*mp2ctl;
18844 	mblk_t			*mp_tail = NULL;
18845 	ill_t			*ill;
18846 	ipif_t			*ipif;
18847 	mib2_ipv6AddrEntry_t	mae6;
18848 	zoneid_t		zoneid;
18849 	ill_walk_context_t	ctx;
18850 
18851 	/*
18852 	 * make a copy of the original message
18853 	 */
18854 	mp2ctl = copymsg(mpctl);
18855 
18856 	/* ipv6AddrEntryTable */
18857 
18858 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18859 	optp->level = MIB2_IP6;
18860 	optp->name = MIB2_IP6_ADDR;
18861 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18862 
18863 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18864 	ill = ILL_START_WALK_V6(&ctx, ipst);
18865 	for (; ill != NULL; ill = ill_next(&ctx, 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;
18871 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18872 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18873 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18874 
18875 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18876 			    OCTET_LENGTH);
18877 			mae6.ipv6AddrIfIndex.o_length =
18878 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18879 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18880 			mae6.ipv6AddrPfxLength =
18881 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18882 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18883 			mae6.ipv6AddrInfo.ae_subnet_len =
18884 			    mae6.ipv6AddrPfxLength;
18885 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18886 
18887 			/* Type: stateless(1), stateful(2), unknown(3) */
18888 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18889 				mae6.ipv6AddrType = 1;
18890 			else
18891 				mae6.ipv6AddrType = 2;
18892 			/* Anycast: true(1), false(2) */
18893 			if (ipif->ipif_flags & IPIF_ANYCAST)
18894 				mae6.ipv6AddrAnycastFlag = 1;
18895 			else
18896 				mae6.ipv6AddrAnycastFlag = 2;
18897 
18898 			/*
18899 			 * Address status: preferred(1), deprecated(2),
18900 			 * invalid(3), inaccessible(4), unknown(5)
18901 			 */
18902 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18903 				mae6.ipv6AddrStatus = 3;
18904 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18905 				mae6.ipv6AddrStatus = 2;
18906 			else
18907 				mae6.ipv6AddrStatus = 1;
18908 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18909 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18910 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18911 			    ipif->ipif_v6pp_dst_addr;
18912 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18913 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18914 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18915 			mae6.ipv6AddrIdentifier = ill->ill_token;
18916 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18917 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18918 			mae6.ipv6AddrRetransmitTime =
18919 			    ill->ill_reachable_retrans_time;
18920 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18921 			    (char *)&mae6,
18922 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18923 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18924 				    "allocate %u bytes\n",
18925 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18926 			}
18927 		}
18928 	}
18929 	rw_exit(&ipst->ips_ill_g_lock);
18930 
18931 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18932 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18933 	    (int)optp->level, (int)optp->name, (int)optp->len));
18934 	qreply(q, mpctl);
18935 	return (mp2ctl);
18936 }
18937 
18938 /* IPv4 multicast group membership. */
18939 static mblk_t *
18940 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18941 {
18942 	struct opthdr		*optp;
18943 	mblk_t			*mp2ctl;
18944 	ill_t			*ill;
18945 	ipif_t			*ipif;
18946 	ilm_t			*ilm;
18947 	ip_member_t		ipm;
18948 	mblk_t			*mp_tail = NULL;
18949 	ill_walk_context_t	ctx;
18950 	zoneid_t		zoneid;
18951 	ilm_walker_t		ilw;
18952 
18953 	/*
18954 	 * make a copy of the original message
18955 	 */
18956 	mp2ctl = copymsg(mpctl);
18957 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18958 
18959 	/* ipGroupMember table */
18960 	optp = (struct opthdr *)&mpctl->b_rptr[
18961 	    sizeof (struct T_optmgmt_ack)];
18962 	optp->level = MIB2_IP;
18963 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18964 
18965 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18966 	ill = ILL_START_WALK_V4(&ctx, ipst);
18967 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18968 		if (IS_UNDER_IPMP(ill))
18969 			continue;
18970 
18971 		ilm = ilm_walker_start(&ilw, ill);
18972 		for (ipif = ill->ill_ipif; ipif != NULL;
18973 		    ipif = ipif->ipif_next) {
18974 			if (ipif->ipif_zoneid != zoneid &&
18975 			    ipif->ipif_zoneid != ALL_ZONES)
18976 				continue;	/* not this zone */
18977 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18978 			    OCTET_LENGTH);
18979 			ipm.ipGroupMemberIfIndex.o_length =
18980 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18981 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18982 				ASSERT(ilm->ilm_ipif != NULL);
18983 				ASSERT(ilm->ilm_ill == NULL);
18984 				if (ilm->ilm_ipif != ipif)
18985 					continue;
18986 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18987 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18988 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18989 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18990 				    (char *)&ipm, (int)sizeof (ipm))) {
18991 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18992 					    "failed to allocate %u bytes\n",
18993 					    (uint_t)sizeof (ipm)));
18994 				}
18995 			}
18996 		}
18997 		ilm_walker_finish(&ilw);
18998 	}
18999 	rw_exit(&ipst->ips_ill_g_lock);
19000 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19001 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19002 	    (int)optp->level, (int)optp->name, (int)optp->len));
19003 	qreply(q, mpctl);
19004 	return (mp2ctl);
19005 }
19006 
19007 /* IPv6 multicast group membership. */
19008 static mblk_t *
19009 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19010 {
19011 	struct opthdr		*optp;
19012 	mblk_t			*mp2ctl;
19013 	ill_t			*ill;
19014 	ilm_t			*ilm;
19015 	ipv6_member_t		ipm6;
19016 	mblk_t			*mp_tail = NULL;
19017 	ill_walk_context_t	ctx;
19018 	zoneid_t		zoneid;
19019 	ilm_walker_t		ilw;
19020 
19021 	/*
19022 	 * make a copy of the original message
19023 	 */
19024 	mp2ctl = copymsg(mpctl);
19025 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19026 
19027 	/* ip6GroupMember table */
19028 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19029 	optp->level = MIB2_IP6;
19030 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19031 
19032 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19033 	ill = ILL_START_WALK_V6(&ctx, ipst);
19034 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19035 		if (IS_UNDER_IPMP(ill))
19036 			continue;
19037 
19038 		ilm = ilm_walker_start(&ilw, ill);
19039 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19040 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19041 			ASSERT(ilm->ilm_ipif == NULL);
19042 			ASSERT(ilm->ilm_ill != NULL);
19043 			if (ilm->ilm_zoneid != zoneid)
19044 				continue;	/* not this zone */
19045 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19046 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19047 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19048 			if (!snmp_append_data2(mpctl->b_cont,
19049 			    &mp_tail,
19050 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19051 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19052 				    "failed to allocate %u bytes\n",
19053 				    (uint_t)sizeof (ipm6)));
19054 			}
19055 		}
19056 		ilm_walker_finish(&ilw);
19057 	}
19058 	rw_exit(&ipst->ips_ill_g_lock);
19059 
19060 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19061 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19062 	    (int)optp->level, (int)optp->name, (int)optp->len));
19063 	qreply(q, mpctl);
19064 	return (mp2ctl);
19065 }
19066 
19067 /* IP multicast filtered sources */
19068 static mblk_t *
19069 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19070 {
19071 	struct opthdr		*optp;
19072 	mblk_t			*mp2ctl;
19073 	ill_t			*ill;
19074 	ipif_t			*ipif;
19075 	ilm_t			*ilm;
19076 	ip_grpsrc_t		ips;
19077 	mblk_t			*mp_tail = NULL;
19078 	ill_walk_context_t	ctx;
19079 	zoneid_t		zoneid;
19080 	int			i;
19081 	slist_t			*sl;
19082 	ilm_walker_t		ilw;
19083 
19084 	/*
19085 	 * make a copy of the original message
19086 	 */
19087 	mp2ctl = copymsg(mpctl);
19088 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19089 
19090 	/* ipGroupSource table */
19091 	optp = (struct opthdr *)&mpctl->b_rptr[
19092 	    sizeof (struct T_optmgmt_ack)];
19093 	optp->level = MIB2_IP;
19094 	optp->name = EXPER_IP_GROUP_SOURCES;
19095 
19096 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19097 	ill = ILL_START_WALK_V4(&ctx, ipst);
19098 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19099 		if (IS_UNDER_IPMP(ill))
19100 			continue;
19101 
19102 		ilm = ilm_walker_start(&ilw, ill);
19103 		for (ipif = ill->ill_ipif; ipif != NULL;
19104 		    ipif = ipif->ipif_next) {
19105 			if (ipif->ipif_zoneid != zoneid)
19106 				continue;	/* not this zone */
19107 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19108 			    OCTET_LENGTH);
19109 			ips.ipGroupSourceIfIndex.o_length =
19110 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19111 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19112 				ASSERT(ilm->ilm_ipif != NULL);
19113 				ASSERT(ilm->ilm_ill == NULL);
19114 				sl = ilm->ilm_filter;
19115 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19116 					continue;
19117 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19118 				for (i = 0; i < sl->sl_numsrc; i++) {
19119 					if (!IN6_IS_ADDR_V4MAPPED(
19120 					    &sl->sl_addr[i]))
19121 						continue;
19122 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19123 					    ips.ipGroupSourceAddress);
19124 					if (snmp_append_data2(mpctl->b_cont,
19125 					    &mp_tail, (char *)&ips,
19126 					    (int)sizeof (ips)) == 0) {
19127 						ip1dbg(("ip_snmp_get_mib2_"
19128 						    "ip_group_src: failed to "
19129 						    "allocate %u bytes\n",
19130 						    (uint_t)sizeof (ips)));
19131 					}
19132 				}
19133 			}
19134 		}
19135 		ilm_walker_finish(&ilw);
19136 	}
19137 	rw_exit(&ipst->ips_ill_g_lock);
19138 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19139 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19140 	    (int)optp->level, (int)optp->name, (int)optp->len));
19141 	qreply(q, mpctl);
19142 	return (mp2ctl);
19143 }
19144 
19145 /* IPv6 multicast filtered sources. */
19146 static mblk_t *
19147 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19148 {
19149 	struct opthdr		*optp;
19150 	mblk_t			*mp2ctl;
19151 	ill_t			*ill;
19152 	ilm_t			*ilm;
19153 	ipv6_grpsrc_t		ips6;
19154 	mblk_t			*mp_tail = NULL;
19155 	ill_walk_context_t	ctx;
19156 	zoneid_t		zoneid;
19157 	int			i;
19158 	slist_t			*sl;
19159 	ilm_walker_t		ilw;
19160 
19161 	/*
19162 	 * make a copy of the original message
19163 	 */
19164 	mp2ctl = copymsg(mpctl);
19165 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19166 
19167 	/* ip6GroupMember table */
19168 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19169 	optp->level = MIB2_IP6;
19170 	optp->name = EXPER_IP6_GROUP_SOURCES;
19171 
19172 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19173 	ill = ILL_START_WALK_V6(&ctx, ipst);
19174 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19175 		if (IS_UNDER_IPMP(ill))
19176 			continue;
19177 
19178 		ilm = ilm_walker_start(&ilw, ill);
19179 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19180 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19181 			ASSERT(ilm->ilm_ipif == NULL);
19182 			ASSERT(ilm->ilm_ill != NULL);
19183 			sl = ilm->ilm_filter;
19184 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19185 				continue;
19186 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19187 			for (i = 0; i < sl->sl_numsrc; i++) {
19188 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19189 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19190 				    (char *)&ips6, (int)sizeof (ips6))) {
19191 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19192 					    "group_src: failed to allocate "
19193 					    "%u bytes\n",
19194 					    (uint_t)sizeof (ips6)));
19195 				}
19196 			}
19197 		}
19198 		ilm_walker_finish(&ilw);
19199 	}
19200 	rw_exit(&ipst->ips_ill_g_lock);
19201 
19202 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19203 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19204 	    (int)optp->level, (int)optp->name, (int)optp->len));
19205 	qreply(q, mpctl);
19206 	return (mp2ctl);
19207 }
19208 
19209 /* Multicast routing virtual interface table. */
19210 static mblk_t *
19211 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19212 {
19213 	struct opthdr		*optp;
19214 	mblk_t			*mp2ctl;
19215 
19216 	/*
19217 	 * make a copy of the original message
19218 	 */
19219 	mp2ctl = copymsg(mpctl);
19220 
19221 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19222 	optp->level = EXPER_DVMRP;
19223 	optp->name = EXPER_DVMRP_VIF;
19224 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19225 		ip0dbg(("ip_mroute_vif: failed\n"));
19226 	}
19227 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19228 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19229 	    (int)optp->level, (int)optp->name, (int)optp->len));
19230 	qreply(q, mpctl);
19231 	return (mp2ctl);
19232 }
19233 
19234 /* Multicast routing table. */
19235 static mblk_t *
19236 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19237 {
19238 	struct opthdr		*optp;
19239 	mblk_t			*mp2ctl;
19240 
19241 	/*
19242 	 * make a copy of the original message
19243 	 */
19244 	mp2ctl = copymsg(mpctl);
19245 
19246 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19247 	optp->level = EXPER_DVMRP;
19248 	optp->name = EXPER_DVMRP_MRT;
19249 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19250 		ip0dbg(("ip_mroute_mrt: failed\n"));
19251 	}
19252 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19253 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19254 	    (int)optp->level, (int)optp->name, (int)optp->len));
19255 	qreply(q, mpctl);
19256 	return (mp2ctl);
19257 }
19258 
19259 /*
19260  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19261  * in one IRE walk.
19262  */
19263 static mblk_t *
19264 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19265     ip_stack_t *ipst)
19266 {
19267 	struct opthdr	*optp;
19268 	mblk_t		*mp2ctl;	/* Returned */
19269 	mblk_t		*mp3ctl;	/* nettomedia */
19270 	mblk_t		*mp4ctl;	/* routeattrs */
19271 	iproutedata_t	ird;
19272 	zoneid_t	zoneid;
19273 
19274 	/*
19275 	 * make copies of the original message
19276 	 *	- mp2ctl is returned unchanged to the caller for his use
19277 	 *	- mpctl is sent upstream as ipRouteEntryTable
19278 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19279 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19280 	 */
19281 	mp2ctl = copymsg(mpctl);
19282 	mp3ctl = copymsg(mpctl);
19283 	mp4ctl = copymsg(mpctl);
19284 	if (mp3ctl == NULL || mp4ctl == NULL) {
19285 		freemsg(mp4ctl);
19286 		freemsg(mp3ctl);
19287 		freemsg(mp2ctl);
19288 		freemsg(mpctl);
19289 		return (NULL);
19290 	}
19291 
19292 	bzero(&ird, sizeof (ird));
19293 
19294 	ird.ird_route.lp_head = mpctl->b_cont;
19295 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19296 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19297 	/*
19298 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19299 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19300 	 * intended a temporary solution until a proper MIB API is provided
19301 	 * that provides complete filtering/caller-opt-in.
19302 	 */
19303 	if (level == EXPER_IP_AND_TESTHIDDEN)
19304 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19305 
19306 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19307 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19308 
19309 	/* ipRouteEntryTable in mpctl */
19310 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19311 	optp->level = MIB2_IP;
19312 	optp->name = MIB2_IP_ROUTE;
19313 	optp->len = msgdsize(ird.ird_route.lp_head);
19314 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19315 	    (int)optp->level, (int)optp->name, (int)optp->len));
19316 	qreply(q, mpctl);
19317 
19318 	/* ipNetToMediaEntryTable in mp3ctl */
19319 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19320 	optp->level = MIB2_IP;
19321 	optp->name = MIB2_IP_MEDIA;
19322 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19323 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19324 	    (int)optp->level, (int)optp->name, (int)optp->len));
19325 	qreply(q, mp3ctl);
19326 
19327 	/* ipRouteAttributeTable in mp4ctl */
19328 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19329 	optp->level = MIB2_IP;
19330 	optp->name = EXPER_IP_RTATTR;
19331 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19332 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19333 	    (int)optp->level, (int)optp->name, (int)optp->len));
19334 	if (optp->len == 0)
19335 		freemsg(mp4ctl);
19336 	else
19337 		qreply(q, mp4ctl);
19338 
19339 	return (mp2ctl);
19340 }
19341 
19342 /*
19343  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19344  * ipv6NetToMediaEntryTable in an NDP walk.
19345  */
19346 static mblk_t *
19347 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19348     ip_stack_t *ipst)
19349 {
19350 	struct opthdr	*optp;
19351 	mblk_t		*mp2ctl;	/* Returned */
19352 	mblk_t		*mp3ctl;	/* nettomedia */
19353 	mblk_t		*mp4ctl;	/* routeattrs */
19354 	iproutedata_t	ird;
19355 	zoneid_t	zoneid;
19356 
19357 	/*
19358 	 * make copies of the original message
19359 	 *	- mp2ctl is returned unchanged to the caller for his use
19360 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19361 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19362 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19363 	 */
19364 	mp2ctl = copymsg(mpctl);
19365 	mp3ctl = copymsg(mpctl);
19366 	mp4ctl = copymsg(mpctl);
19367 	if (mp3ctl == NULL || mp4ctl == NULL) {
19368 		freemsg(mp4ctl);
19369 		freemsg(mp3ctl);
19370 		freemsg(mp2ctl);
19371 		freemsg(mpctl);
19372 		return (NULL);
19373 	}
19374 
19375 	bzero(&ird, sizeof (ird));
19376 
19377 	ird.ird_route.lp_head = mpctl->b_cont;
19378 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19379 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19380 	/*
19381 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19382 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19383 	 * intended a temporary solution until a proper MIB API is provided
19384 	 * that provides complete filtering/caller-opt-in.
19385 	 */
19386 	if (level == EXPER_IP_AND_TESTHIDDEN)
19387 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19388 
19389 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19390 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19391 
19392 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19393 	optp->level = MIB2_IP6;
19394 	optp->name = MIB2_IP6_ROUTE;
19395 	optp->len = msgdsize(ird.ird_route.lp_head);
19396 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19397 	    (int)optp->level, (int)optp->name, (int)optp->len));
19398 	qreply(q, mpctl);
19399 
19400 	/* ipv6NetToMediaEntryTable in mp3ctl */
19401 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19402 
19403 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19404 	optp->level = MIB2_IP6;
19405 	optp->name = MIB2_IP6_MEDIA;
19406 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19407 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19408 	    (int)optp->level, (int)optp->name, (int)optp->len));
19409 	qreply(q, mp3ctl);
19410 
19411 	/* ipv6RouteAttributeTable in mp4ctl */
19412 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19413 	optp->level = MIB2_IP6;
19414 	optp->name = EXPER_IP_RTATTR;
19415 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19416 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19417 	    (int)optp->level, (int)optp->name, (int)optp->len));
19418 	if (optp->len == 0)
19419 		freemsg(mp4ctl);
19420 	else
19421 		qreply(q, mp4ctl);
19422 
19423 	return (mp2ctl);
19424 }
19425 
19426 /*
19427  * IPv6 mib: One per ill
19428  */
19429 static mblk_t *
19430 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19431 {
19432 	struct opthdr		*optp;
19433 	mblk_t			*mp2ctl;
19434 	ill_t			*ill;
19435 	ill_walk_context_t	ctx;
19436 	mblk_t			*mp_tail = NULL;
19437 
19438 	/*
19439 	 * Make a copy of the original message
19440 	 */
19441 	mp2ctl = copymsg(mpctl);
19442 
19443 	/* fixed length IPv6 structure ... */
19444 
19445 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19446 	optp->level = MIB2_IP6;
19447 	optp->name = 0;
19448 	/* Include "unknown interface" ip6_mib */
19449 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19450 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19451 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19452 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19453 	    ipst->ips_ipv6_forward ? 1 : 2);
19454 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19455 	    ipst->ips_ipv6_def_hops);
19456 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19457 	    sizeof (mib2_ipIfStatsEntry_t));
19458 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19459 	    sizeof (mib2_ipv6AddrEntry_t));
19460 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19461 	    sizeof (mib2_ipv6RouteEntry_t));
19462 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19463 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19464 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19465 	    sizeof (ipv6_member_t));
19466 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19467 	    sizeof (ipv6_grpsrc_t));
19468 
19469 	/*
19470 	 * Synchronize 64- and 32-bit counters
19471 	 */
19472 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19473 	    ipIfStatsHCInReceives);
19474 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19475 	    ipIfStatsHCInDelivers);
19476 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19477 	    ipIfStatsHCOutRequests);
19478 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19479 	    ipIfStatsHCOutForwDatagrams);
19480 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19481 	    ipIfStatsHCOutMcastPkts);
19482 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19483 	    ipIfStatsHCInMcastPkts);
19484 
19485 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19486 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19487 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19488 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19489 	}
19490 
19491 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19492 	ill = ILL_START_WALK_V6(&ctx, ipst);
19493 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19494 		ill->ill_ip_mib->ipIfStatsIfIndex =
19495 		    ill->ill_phyint->phyint_ifindex;
19496 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19497 		    ipst->ips_ipv6_forward ? 1 : 2);
19498 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19499 		    ill->ill_max_hops);
19500 
19501 		/*
19502 		 * Synchronize 64- and 32-bit counters
19503 		 */
19504 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19505 		    ipIfStatsHCInReceives);
19506 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19507 		    ipIfStatsHCInDelivers);
19508 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19509 		    ipIfStatsHCOutRequests);
19510 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19511 		    ipIfStatsHCOutForwDatagrams);
19512 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19513 		    ipIfStatsHCOutMcastPkts);
19514 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19515 		    ipIfStatsHCInMcastPkts);
19516 
19517 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19518 		    (char *)ill->ill_ip_mib,
19519 		    (int)sizeof (*ill->ill_ip_mib))) {
19520 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19521 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19522 		}
19523 	}
19524 	rw_exit(&ipst->ips_ill_g_lock);
19525 
19526 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19527 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19528 	    (int)optp->level, (int)optp->name, (int)optp->len));
19529 	qreply(q, mpctl);
19530 	return (mp2ctl);
19531 }
19532 
19533 /*
19534  * ICMPv6 mib: One per ill
19535  */
19536 static mblk_t *
19537 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19538 {
19539 	struct opthdr		*optp;
19540 	mblk_t			*mp2ctl;
19541 	ill_t			*ill;
19542 	ill_walk_context_t	ctx;
19543 	mblk_t			*mp_tail = NULL;
19544 	/*
19545 	 * Make a copy of the original message
19546 	 */
19547 	mp2ctl = copymsg(mpctl);
19548 
19549 	/* fixed length ICMPv6 structure ... */
19550 
19551 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19552 	optp->level = MIB2_ICMP6;
19553 	optp->name = 0;
19554 	/* Include "unknown interface" icmp6_mib */
19555 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19556 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19557 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19558 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19559 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19560 	    (char *)&ipst->ips_icmp6_mib,
19561 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19562 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19563 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19564 	}
19565 
19566 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19567 	ill = ILL_START_WALK_V6(&ctx, ipst);
19568 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19569 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19570 		    ill->ill_phyint->phyint_ifindex;
19571 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19572 		    (char *)ill->ill_icmp6_mib,
19573 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19574 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19575 			    "%u bytes\n",
19576 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19577 		}
19578 	}
19579 	rw_exit(&ipst->ips_ill_g_lock);
19580 
19581 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19582 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19583 	    (int)optp->level, (int)optp->name, (int)optp->len));
19584 	qreply(q, mpctl);
19585 	return (mp2ctl);
19586 }
19587 
19588 /*
19589  * ire_walk routine to create both ipRouteEntryTable and
19590  * ipRouteAttributeTable in one IRE walk
19591  */
19592 static void
19593 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19594 {
19595 	ill_t				*ill;
19596 	ipif_t				*ipif;
19597 	mib2_ipRouteEntry_t		*re;
19598 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19599 	ipaddr_t			gw_addr;
19600 	tsol_ire_gw_secattr_t		*attrp;
19601 	tsol_gc_t			*gc = NULL;
19602 	tsol_gcgrp_t			*gcgrp = NULL;
19603 	uint_t				sacnt = 0;
19604 	int				i;
19605 
19606 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19607 
19608 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19609 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19610 		return;
19611 	}
19612 
19613 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19614 		return;
19615 
19616 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19617 		mutex_enter(&attrp->igsa_lock);
19618 		if ((gc = attrp->igsa_gc) != NULL) {
19619 			gcgrp = gc->gc_grp;
19620 			ASSERT(gcgrp != NULL);
19621 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19622 			sacnt = 1;
19623 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19624 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19625 			gc = gcgrp->gcgrp_head;
19626 			sacnt = gcgrp->gcgrp_count;
19627 		}
19628 		mutex_exit(&attrp->igsa_lock);
19629 
19630 		/* do nothing if there's no gc to report */
19631 		if (gc == NULL) {
19632 			ASSERT(sacnt == 0);
19633 			if (gcgrp != NULL) {
19634 				/* we might as well drop the lock now */
19635 				rw_exit(&gcgrp->gcgrp_rwlock);
19636 				gcgrp = NULL;
19637 			}
19638 			attrp = NULL;
19639 		}
19640 
19641 		ASSERT(gc == NULL || (gcgrp != NULL &&
19642 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19643 	}
19644 	ASSERT(sacnt == 0 || gc != NULL);
19645 
19646 	if (sacnt != 0 &&
19647 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19648 		kmem_free(re, sizeof (*re));
19649 		rw_exit(&gcgrp->gcgrp_rwlock);
19650 		return;
19651 	}
19652 
19653 	/*
19654 	 * Return all IRE types for route table... let caller pick and choose
19655 	 */
19656 	re->ipRouteDest = ire->ire_addr;
19657 	ipif = ire->ire_ipif;
19658 	re->ipRouteIfIndex.o_length = 0;
19659 	if (ire->ire_type == IRE_CACHE) {
19660 		ill = (ill_t *)ire->ire_stq->q_ptr;
19661 		re->ipRouteIfIndex.o_length =
19662 		    ill->ill_name_length == 0 ? 0 :
19663 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19664 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19665 		    re->ipRouteIfIndex.o_length);
19666 	} else if (ipif != NULL) {
19667 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19668 		re->ipRouteIfIndex.o_length =
19669 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19670 	}
19671 	re->ipRouteMetric1 = -1;
19672 	re->ipRouteMetric2 = -1;
19673 	re->ipRouteMetric3 = -1;
19674 	re->ipRouteMetric4 = -1;
19675 
19676 	gw_addr = ire->ire_gateway_addr;
19677 
19678 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19679 		re->ipRouteNextHop = ire->ire_src_addr;
19680 	else
19681 		re->ipRouteNextHop = gw_addr;
19682 	/* indirect(4), direct(3), or invalid(2) */
19683 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19684 		re->ipRouteType = 2;
19685 	else
19686 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19687 	re->ipRouteProto = -1;
19688 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19689 	re->ipRouteMask = ire->ire_mask;
19690 	re->ipRouteMetric5 = -1;
19691 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19692 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19693 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19694 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19695 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19696 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19697 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19698 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19699 
19700 	if (ire->ire_flags & RTF_DYNAMIC) {
19701 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19702 	} else {
19703 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19704 	}
19705 
19706 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19707 	    (char *)re, (int)sizeof (*re))) {
19708 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19709 		    (uint_t)sizeof (*re)));
19710 	}
19711 
19712 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19713 		iaeptr->iae_routeidx = ird->ird_idx;
19714 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19715 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19716 	}
19717 
19718 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19719 	    (char *)iae, sacnt * sizeof (*iae))) {
19720 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19721 		    (unsigned)(sacnt * sizeof (*iae))));
19722 	}
19723 
19724 	/* bump route index for next pass */
19725 	ird->ird_idx++;
19726 
19727 	kmem_free(re, sizeof (*re));
19728 	if (sacnt != 0)
19729 		kmem_free(iae, sacnt * sizeof (*iae));
19730 
19731 	if (gcgrp != NULL)
19732 		rw_exit(&gcgrp->gcgrp_rwlock);
19733 }
19734 
19735 /*
19736  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19737  */
19738 static void
19739 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19740 {
19741 	ill_t				*ill;
19742 	ipif_t				*ipif;
19743 	mib2_ipv6RouteEntry_t		*re;
19744 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19745 	in6_addr_t			gw_addr_v6;
19746 	tsol_ire_gw_secattr_t		*attrp;
19747 	tsol_gc_t			*gc = NULL;
19748 	tsol_gcgrp_t			*gcgrp = NULL;
19749 	uint_t				sacnt = 0;
19750 	int				i;
19751 
19752 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19753 
19754 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19755 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19756 		return;
19757 	}
19758 
19759 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19760 		return;
19761 
19762 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19763 		mutex_enter(&attrp->igsa_lock);
19764 		if ((gc = attrp->igsa_gc) != NULL) {
19765 			gcgrp = gc->gc_grp;
19766 			ASSERT(gcgrp != NULL);
19767 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19768 			sacnt = 1;
19769 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19770 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19771 			gc = gcgrp->gcgrp_head;
19772 			sacnt = gcgrp->gcgrp_count;
19773 		}
19774 		mutex_exit(&attrp->igsa_lock);
19775 
19776 		/* do nothing if there's no gc to report */
19777 		if (gc == NULL) {
19778 			ASSERT(sacnt == 0);
19779 			if (gcgrp != NULL) {
19780 				/* we might as well drop the lock now */
19781 				rw_exit(&gcgrp->gcgrp_rwlock);
19782 				gcgrp = NULL;
19783 			}
19784 			attrp = NULL;
19785 		}
19786 
19787 		ASSERT(gc == NULL || (gcgrp != NULL &&
19788 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19789 	}
19790 	ASSERT(sacnt == 0 || gc != NULL);
19791 
19792 	if (sacnt != 0 &&
19793 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19794 		kmem_free(re, sizeof (*re));
19795 		rw_exit(&gcgrp->gcgrp_rwlock);
19796 		return;
19797 	}
19798 
19799 	/*
19800 	 * Return all IRE types for route table... let caller pick and choose
19801 	 */
19802 	re->ipv6RouteDest = ire->ire_addr_v6;
19803 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19804 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19805 	re->ipv6RouteIfIndex.o_length = 0;
19806 	ipif = ire->ire_ipif;
19807 	if (ire->ire_type == IRE_CACHE) {
19808 		ill = (ill_t *)ire->ire_stq->q_ptr;
19809 		re->ipv6RouteIfIndex.o_length =
19810 		    ill->ill_name_length == 0 ? 0 :
19811 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19812 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19813 		    re->ipv6RouteIfIndex.o_length);
19814 	} else if (ipif != NULL) {
19815 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19816 		re->ipv6RouteIfIndex.o_length =
19817 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19818 	}
19819 
19820 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19821 
19822 	mutex_enter(&ire->ire_lock);
19823 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19824 	mutex_exit(&ire->ire_lock);
19825 
19826 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19827 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19828 	else
19829 		re->ipv6RouteNextHop = gw_addr_v6;
19830 
19831 	/* remote(4), local(3), or discard(2) */
19832 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19833 		re->ipv6RouteType = 2;
19834 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19835 		re->ipv6RouteType = 3;
19836 	else
19837 		re->ipv6RouteType = 4;
19838 
19839 	re->ipv6RouteProtocol	= -1;
19840 	re->ipv6RoutePolicy	= 0;
19841 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19842 	re->ipv6RouteNextHopRDI	= 0;
19843 	re->ipv6RouteWeight	= 0;
19844 	re->ipv6RouteMetric	= 0;
19845 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19846 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19847 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19848 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19849 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19850 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19851 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19852 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19853 
19854 	if (ire->ire_flags & RTF_DYNAMIC) {
19855 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19856 	} else {
19857 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19858 	}
19859 
19860 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19861 	    (char *)re, (int)sizeof (*re))) {
19862 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19863 		    (uint_t)sizeof (*re)));
19864 	}
19865 
19866 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19867 		iaeptr->iae_routeidx = ird->ird_idx;
19868 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19869 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19870 	}
19871 
19872 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19873 	    (char *)iae, sacnt * sizeof (*iae))) {
19874 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19875 		    (unsigned)(sacnt * sizeof (*iae))));
19876 	}
19877 
19878 	/* bump route index for next pass */
19879 	ird->ird_idx++;
19880 
19881 	kmem_free(re, sizeof (*re));
19882 	if (sacnt != 0)
19883 		kmem_free(iae, sacnt * sizeof (*iae));
19884 
19885 	if (gcgrp != NULL)
19886 		rw_exit(&gcgrp->gcgrp_rwlock);
19887 }
19888 
19889 /*
19890  * ndp_walk routine to create ipv6NetToMediaEntryTable
19891  */
19892 static int
19893 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19894 {
19895 	ill_t				*ill;
19896 	mib2_ipv6NetToMediaEntry_t	ntme;
19897 	dl_unitdata_req_t		*dl;
19898 
19899 	ill = nce->nce_ill;
19900 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19901 		return (0);
19902 
19903 	/*
19904 	 * Neighbor cache entry attached to IRE with on-link
19905 	 * destination.
19906 	 */
19907 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19908 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19909 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19910 	    (nce->nce_res_mp != NULL)) {
19911 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19912 		ntme.ipv6NetToMediaPhysAddress.o_length =
19913 		    dl->dl_dest_addr_length;
19914 	} else {
19915 		ntme.ipv6NetToMediaPhysAddress.o_length =
19916 		    ill->ill_phys_addr_length;
19917 	}
19918 	if (nce->nce_res_mp != NULL) {
19919 		bcopy((char *)nce->nce_res_mp->b_rptr +
19920 		    NCE_LL_ADDR_OFFSET(ill),
19921 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19922 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19923 	} else {
19924 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19925 		    ill->ill_phys_addr_length);
19926 	}
19927 	/*
19928 	 * Note: Returns ND_* states. Should be:
19929 	 * reachable(1), stale(2), delay(3), probe(4),
19930 	 * invalid(5), unknown(6)
19931 	 */
19932 	ntme.ipv6NetToMediaState = nce->nce_state;
19933 	ntme.ipv6NetToMediaLastUpdated = 0;
19934 
19935 	/* other(1), dynamic(2), static(3), local(4) */
19936 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19937 		ntme.ipv6NetToMediaType = 4;
19938 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19939 		ntme.ipv6NetToMediaType = 1;
19940 	} else {
19941 		ntme.ipv6NetToMediaType = 2;
19942 	}
19943 
19944 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19945 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19946 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19947 		    (uint_t)sizeof (ntme)));
19948 	}
19949 	return (0);
19950 }
19951 
19952 /*
19953  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19954  */
19955 /* ARGSUSED */
19956 int
19957 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19958 {
19959 	switch (level) {
19960 	case MIB2_IP:
19961 	case MIB2_ICMP:
19962 		switch (name) {
19963 		default:
19964 			break;
19965 		}
19966 		return (1);
19967 	default:
19968 		return (1);
19969 	}
19970 }
19971 
19972 /*
19973  * When there exists both a 64- and 32-bit counter of a particular type
19974  * (i.e., InReceives), only the 64-bit counters are added.
19975  */
19976 void
19977 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19978 {
19979 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19980 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19981 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19982 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19983 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19984 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19985 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19986 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19987 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19988 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19989 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19990 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19991 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19992 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19993 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19994 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19995 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19996 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19997 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19998 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19999 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
20000 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
20001 	    o2->ipIfStatsInWrongIPVersion);
20002 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
20003 	    o2->ipIfStatsInWrongIPVersion);
20004 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
20005 	    o2->ipIfStatsOutSwitchIPVersion);
20006 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
20007 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
20008 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
20009 	    o2->ipIfStatsHCInForwDatagrams);
20010 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
20011 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
20012 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
20013 	    o2->ipIfStatsHCOutForwDatagrams);
20014 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20015 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20016 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20017 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20018 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20019 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20020 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20021 	    o2->ipIfStatsHCOutMcastOctets);
20022 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20023 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20024 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20025 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20026 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20027 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20028 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20029 }
20030 
20031 void
20032 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20033 {
20034 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20035 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20036 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20037 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20038 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20039 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20040 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20041 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20042 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20043 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20044 	    o2->ipv6IfIcmpInRouterSolicits);
20045 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20046 	    o2->ipv6IfIcmpInRouterAdvertisements);
20047 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20048 	    o2->ipv6IfIcmpInNeighborSolicits);
20049 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20050 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20051 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20052 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20053 	    o2->ipv6IfIcmpInGroupMembQueries);
20054 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20055 	    o2->ipv6IfIcmpInGroupMembResponses);
20056 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20057 	    o2->ipv6IfIcmpInGroupMembReductions);
20058 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20059 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20060 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20061 	    o2->ipv6IfIcmpOutDestUnreachs);
20062 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20063 	    o2->ipv6IfIcmpOutAdminProhibs);
20064 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20065 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20066 	    o2->ipv6IfIcmpOutParmProblems);
20067 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20068 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20069 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20070 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20071 	    o2->ipv6IfIcmpOutRouterSolicits);
20072 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20073 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20074 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20075 	    o2->ipv6IfIcmpOutNeighborSolicits);
20076 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20077 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20078 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20079 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20080 	    o2->ipv6IfIcmpOutGroupMembQueries);
20081 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20082 	    o2->ipv6IfIcmpOutGroupMembResponses);
20083 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20084 	    o2->ipv6IfIcmpOutGroupMembReductions);
20085 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20086 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20087 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20088 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20089 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20090 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20091 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20092 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20093 	    o2->ipv6IfIcmpInGroupMembTotal);
20094 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20095 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20096 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20097 	    o2->ipv6IfIcmpInGroupMembBadReports);
20098 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20099 	    o2->ipv6IfIcmpInGroupMembOurReports);
20100 }
20101 
20102 /*
20103  * Called before the options are updated to check if this packet will
20104  * be source routed from here.
20105  * This routine assumes that the options are well formed i.e. that they
20106  * have already been checked.
20107  */
20108 static boolean_t
20109 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20110 {
20111 	ipoptp_t	opts;
20112 	uchar_t		*opt;
20113 	uint8_t		optval;
20114 	uint8_t		optlen;
20115 	ipaddr_t	dst;
20116 	ire_t		*ire;
20117 
20118 	if (IS_SIMPLE_IPH(ipha)) {
20119 		ip2dbg(("not source routed\n"));
20120 		return (B_FALSE);
20121 	}
20122 	dst = ipha->ipha_dst;
20123 	for (optval = ipoptp_first(&opts, ipha);
20124 	    optval != IPOPT_EOL;
20125 	    optval = ipoptp_next(&opts)) {
20126 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20127 		opt = opts.ipoptp_cur;
20128 		optlen = opts.ipoptp_len;
20129 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20130 		    optval, optlen));
20131 		switch (optval) {
20132 			uint32_t off;
20133 		case IPOPT_SSRR:
20134 		case IPOPT_LSRR:
20135 			/*
20136 			 * If dst is one of our addresses and there are some
20137 			 * entries left in the source route return (true).
20138 			 */
20139 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20140 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20141 			if (ire == NULL) {
20142 				ip2dbg(("ip_source_routed: not next"
20143 				    " source route 0x%x\n",
20144 				    ntohl(dst)));
20145 				return (B_FALSE);
20146 			}
20147 			ire_refrele(ire);
20148 			off = opt[IPOPT_OFFSET];
20149 			off--;
20150 			if (optlen < IP_ADDR_LEN ||
20151 			    off > optlen - IP_ADDR_LEN) {
20152 				/* End of source route */
20153 				ip1dbg(("ip_source_routed: end of SR\n"));
20154 				return (B_FALSE);
20155 			}
20156 			return (B_TRUE);
20157 		}
20158 	}
20159 	ip2dbg(("not source routed\n"));
20160 	return (B_FALSE);
20161 }
20162 
20163 /*
20164  * Check if the packet contains any source route.
20165  */
20166 static boolean_t
20167 ip_source_route_included(ipha_t *ipha)
20168 {
20169 	ipoptp_t	opts;
20170 	uint8_t		optval;
20171 
20172 	if (IS_SIMPLE_IPH(ipha))
20173 		return (B_FALSE);
20174 	for (optval = ipoptp_first(&opts, ipha);
20175 	    optval != IPOPT_EOL;
20176 	    optval = ipoptp_next(&opts)) {
20177 		switch (optval) {
20178 		case IPOPT_SSRR:
20179 		case IPOPT_LSRR:
20180 			return (B_TRUE);
20181 		}
20182 	}
20183 	return (B_FALSE);
20184 }
20185 
20186 /*
20187  * Called when the IRE expiration timer fires.
20188  */
20189 void
20190 ip_trash_timer_expire(void *args)
20191 {
20192 	int			flush_flag = 0;
20193 	ire_expire_arg_t	iea;
20194 	ip_stack_t		*ipst = (ip_stack_t *)args;
20195 
20196 	iea.iea_ipst = ipst;	/* No netstack_hold */
20197 
20198 	/*
20199 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20200 	 * This lock makes sure that a new invocation of this function
20201 	 * that occurs due to an almost immediate timer firing will not
20202 	 * progress beyond this point until the current invocation is done
20203 	 */
20204 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20205 	ipst->ips_ip_ire_expire_id = 0;
20206 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20207 
20208 	/* Periodic timer */
20209 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20210 	    ipst->ips_ip_ire_arp_interval) {
20211 		/*
20212 		 * Remove all IRE_CACHE entries since they might
20213 		 * contain arp information.
20214 		 */
20215 		flush_flag |= FLUSH_ARP_TIME;
20216 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20217 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20218 	}
20219 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20220 	    ipst->ips_ip_ire_redir_interval) {
20221 		/* Remove all redirects */
20222 		flush_flag |= FLUSH_REDIRECT_TIME;
20223 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20224 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20225 	}
20226 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20227 	    ipst->ips_ip_ire_pathmtu_interval) {
20228 		/* Increase path mtu */
20229 		flush_flag |= FLUSH_MTU_TIME;
20230 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20231 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20232 	}
20233 
20234 	/*
20235 	 * Optimize for the case when there are no redirects in the
20236 	 * ftable, that is, no need to walk the ftable in that case.
20237 	 */
20238 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20239 		iea.iea_flush_flag = flush_flag;
20240 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20241 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20242 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20243 		    NULL, ALL_ZONES, ipst);
20244 	}
20245 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20246 	    ipst->ips_ip_redirect_cnt > 0) {
20247 		iea.iea_flush_flag = flush_flag;
20248 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20249 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20250 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20251 	}
20252 	if (flush_flag & FLUSH_MTU_TIME) {
20253 		/*
20254 		 * Walk all IPv6 IRE's and update them
20255 		 * Note that ARP and redirect timers are not
20256 		 * needed since NUD handles stale entries.
20257 		 */
20258 		flush_flag = FLUSH_MTU_TIME;
20259 		iea.iea_flush_flag = flush_flag;
20260 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20261 		    ALL_ZONES, ipst);
20262 	}
20263 
20264 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20265 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20266 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20267 
20268 	/*
20269 	 * Hold the lock to serialize timeout calls and prevent
20270 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20271 	 * for the timer to fire and a new invocation of this function
20272 	 * to start before the return value of timeout has been stored
20273 	 * in ip_ire_expire_id by the current invocation.
20274 	 */
20275 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20276 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20277 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20278 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20279 }
20280 
20281 /*
20282  * Called by the memory allocator subsystem directly, when the system
20283  * is running low on memory.
20284  */
20285 /* ARGSUSED */
20286 void
20287 ip_trash_ire_reclaim(void *args)
20288 {
20289 	netstack_handle_t nh;
20290 	netstack_t *ns;
20291 
20292 	netstack_next_init(&nh);
20293 	while ((ns = netstack_next(&nh)) != NULL) {
20294 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20295 		netstack_rele(ns);
20296 	}
20297 	netstack_next_fini(&nh);
20298 }
20299 
20300 static void
20301 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20302 {
20303 	ire_cache_count_t icc;
20304 	ire_cache_reclaim_t icr;
20305 	ncc_cache_count_t ncc;
20306 	nce_cache_reclaim_t ncr;
20307 	uint_t delete_cnt;
20308 	/*
20309 	 * Memory reclaim call back.
20310 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20311 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20312 	 * entries, determine what fraction to free for
20313 	 * each category of IRE_CACHE entries giving absolute priority
20314 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20315 	 * entry will be freed unless all offlink entries are freed).
20316 	 */
20317 	icc.icc_total = 0;
20318 	icc.icc_unused = 0;
20319 	icc.icc_offlink = 0;
20320 	icc.icc_pmtu = 0;
20321 	icc.icc_onlink = 0;
20322 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20323 
20324 	/*
20325 	 * Free NCEs for IPv6 like the onlink ires.
20326 	 */
20327 	ncc.ncc_total = 0;
20328 	ncc.ncc_host = 0;
20329 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20330 
20331 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20332 	    icc.icc_pmtu + icc.icc_onlink);
20333 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20334 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20335 	if (delete_cnt == 0)
20336 		return;
20337 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20338 	/* Always delete all unused offlink entries */
20339 	icr.icr_ipst = ipst;
20340 	icr.icr_unused = 1;
20341 	if (delete_cnt <= icc.icc_unused) {
20342 		/*
20343 		 * Only need to free unused entries.  In other words,
20344 		 * there are enough unused entries to free to meet our
20345 		 * target number of freed ire cache entries.
20346 		 */
20347 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20348 		ncr.ncr_host = 0;
20349 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20350 		/*
20351 		 * Only need to free unused entries, plus a fraction of offlink
20352 		 * entries.  It follows from the first if statement that
20353 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20354 		 */
20355 		delete_cnt -= icc.icc_unused;
20356 		/* Round up # deleted by truncating fraction */
20357 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20358 		icr.icr_pmtu = icr.icr_onlink = 0;
20359 		ncr.ncr_host = 0;
20360 	} else if (delete_cnt <=
20361 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20362 		/*
20363 		 * Free all unused and offlink entries, plus a fraction of
20364 		 * pmtu entries.  It follows from the previous if statement
20365 		 * that icc_pmtu is non-zero, and that
20366 		 * delete_cnt != icc_unused + icc_offlink.
20367 		 */
20368 		icr.icr_offlink = 1;
20369 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20370 		/* Round up # deleted by truncating fraction */
20371 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20372 		icr.icr_onlink = 0;
20373 		ncr.ncr_host = 0;
20374 	} else {
20375 		/*
20376 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20377 		 * of onlink entries.  If we're here, then we know that
20378 		 * icc_onlink is non-zero, and that
20379 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20380 		 */
20381 		icr.icr_offlink = icr.icr_pmtu = 1;
20382 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20383 		    icc.icc_pmtu;
20384 		/* Round up # deleted by truncating fraction */
20385 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20386 		/* Using the same delete fraction as for onlink IREs */
20387 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20388 	}
20389 #ifdef DEBUG
20390 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20391 	    "fractions %d/%d/%d/%d\n",
20392 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20393 	    icc.icc_unused, icc.icc_offlink,
20394 	    icc.icc_pmtu, icc.icc_onlink,
20395 	    icr.icr_unused, icr.icr_offlink,
20396 	    icr.icr_pmtu, icr.icr_onlink));
20397 #endif
20398 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20399 	if (ncr.ncr_host != 0)
20400 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20401 		    (uchar_t *)&ncr, ipst);
20402 #ifdef DEBUG
20403 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20404 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20405 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20406 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20407 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20408 	    icc.icc_pmtu, icc.icc_onlink));
20409 #endif
20410 }
20411 
20412 /*
20413  * ip_unbind is called when a copy of an unbind request is received from the
20414  * upper level protocol.  We remove this conn from any fanout hash list it is
20415  * on, and zero out the bind information.  No reply is expected up above.
20416  */
20417 void
20418 ip_unbind(conn_t *connp)
20419 {
20420 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20421 
20422 	if (is_system_labeled() && connp->conn_anon_port) {
20423 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20424 		    connp->conn_mlp_type, connp->conn_ulp,
20425 		    ntohs(connp->conn_lport), B_FALSE);
20426 		connp->conn_anon_port = 0;
20427 	}
20428 	connp->conn_mlp_type = mlptSingle;
20429 
20430 	ipcl_hash_remove(connp);
20431 
20432 }
20433 
20434 /*
20435  * Write side put procedure.  Outbound data, IOCTLs, responses from
20436  * resolvers, etc, come down through here.
20437  *
20438  * arg2 is always a queue_t *.
20439  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20440  * the zoneid.
20441  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20442  */
20443 void
20444 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20445 {
20446 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20447 }
20448 
20449 void
20450 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20451     ip_opt_info_t *infop)
20452 {
20453 	conn_t		*connp = NULL;
20454 	queue_t		*q = (queue_t *)arg2;
20455 	ipha_t		*ipha;
20456 #define	rptr	((uchar_t *)ipha)
20457 	ire_t		*ire = NULL;
20458 	ire_t		*sctp_ire = NULL;
20459 	uint32_t	v_hlen_tos_len;
20460 	ipaddr_t	dst;
20461 	mblk_t		*first_mp = NULL;
20462 	boolean_t	mctl_present;
20463 	ipsec_out_t	*io;
20464 	int		match_flags;
20465 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20466 	ipif_t		*dst_ipif;
20467 	boolean_t	multirt_need_resolve = B_FALSE;
20468 	mblk_t		*copy_mp = NULL;
20469 	int		err;
20470 	zoneid_t	zoneid;
20471 	boolean_t	need_decref = B_FALSE;
20472 	boolean_t	ignore_dontroute = B_FALSE;
20473 	boolean_t	ignore_nexthop = B_FALSE;
20474 	boolean_t	ip_nexthop = B_FALSE;
20475 	ipaddr_t	nexthop_addr;
20476 	ip_stack_t	*ipst;
20477 
20478 #ifdef	_BIG_ENDIAN
20479 #define	V_HLEN	(v_hlen_tos_len >> 24)
20480 #else
20481 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20482 #endif
20483 
20484 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20485 	    "ip_wput_start: q %p", q);
20486 
20487 	/*
20488 	 * ip_wput fast path
20489 	 */
20490 
20491 	/* is packet from ARP ? */
20492 	if (q->q_next != NULL) {
20493 		zoneid = (zoneid_t)(uintptr_t)arg;
20494 		goto qnext;
20495 	}
20496 
20497 	connp = (conn_t *)arg;
20498 	ASSERT(connp != NULL);
20499 	zoneid = connp->conn_zoneid;
20500 	ipst = connp->conn_netstack->netstack_ip;
20501 	ASSERT(ipst != NULL);
20502 
20503 	/* is queue flow controlled? */
20504 	if ((q->q_first != NULL || connp->conn_draining) &&
20505 	    (caller == IP_WPUT)) {
20506 		ASSERT(!need_decref);
20507 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20508 		(void) putq(q, mp);
20509 		return;
20510 	}
20511 
20512 	/* Multidata transmit? */
20513 	if (DB_TYPE(mp) == M_MULTIDATA) {
20514 		/*
20515 		 * We should never get here, since all Multidata messages
20516 		 * originating from tcp should have been directed over to
20517 		 * tcp_multisend() in the first place.
20518 		 */
20519 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20520 		freemsg(mp);
20521 		return;
20522 	} else if (DB_TYPE(mp) != M_DATA)
20523 		goto notdata;
20524 
20525 	if (mp->b_flag & MSGHASREF) {
20526 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20527 		mp->b_flag &= ~MSGHASREF;
20528 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20529 		need_decref = B_TRUE;
20530 	}
20531 	ipha = (ipha_t *)mp->b_rptr;
20532 
20533 	/* is IP header non-aligned or mblk smaller than basic IP header */
20534 #ifndef SAFETY_BEFORE_SPEED
20535 	if (!OK_32PTR(rptr) ||
20536 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20537 		goto hdrtoosmall;
20538 #endif
20539 
20540 	ASSERT(OK_32PTR(ipha));
20541 
20542 	/*
20543 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20544 	 * wrong version, we'll catch it again in ip_output_v6.
20545 	 *
20546 	 * Note that this is *only* locally-generated output here, and never
20547 	 * forwarded data, and that we need to deal only with transports that
20548 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20549 	 * label.)
20550 	 */
20551 	if (is_system_labeled() &&
20552 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20553 	    !connp->conn_ulp_labeled) {
20554 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20555 		    connp->conn_mac_exempt, ipst);
20556 		ipha = (ipha_t *)mp->b_rptr;
20557 		if (err != 0) {
20558 			first_mp = mp;
20559 			if (err == EINVAL)
20560 				goto icmp_parameter_problem;
20561 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20562 			goto discard_pkt;
20563 		}
20564 	}
20565 
20566 	ASSERT(infop != NULL);
20567 
20568 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20569 		/*
20570 		 * IP_PKTINFO ancillary option is present.
20571 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20572 		 * allows using address of any zone as the source address.
20573 		 */
20574 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20575 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20576 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20577 		if (ire == NULL)
20578 			goto drop_pkt;
20579 		ire_refrele(ire);
20580 		ire = NULL;
20581 	}
20582 
20583 	/*
20584 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20585 	 */
20586 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20587 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20588 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20589 
20590 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20591 			goto drop_pkt;
20592 		/*
20593 		 * check that there is an ipif belonging
20594 		 * to our zone. IPCL_ZONEID is not used because
20595 		 * IP_ALLZONES option is valid only when the ill is
20596 		 * accessible from all zones i.e has a valid ipif in
20597 		 * all zones.
20598 		 */
20599 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20600 			goto drop_pkt;
20601 		}
20602 	}
20603 
20604 	/*
20605 	 * If there is a policy, try to attach an ipsec_out in
20606 	 * the front. At the end, first_mp either points to a
20607 	 * M_DATA message or IPSEC_OUT message linked to a
20608 	 * M_DATA message. We have to do it now as we might
20609 	 * lose the "conn" if we go through ip_newroute.
20610 	 */
20611 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20612 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20613 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20614 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20615 			if (need_decref)
20616 				CONN_DEC_REF(connp);
20617 			return;
20618 		} else {
20619 			ASSERT(mp->b_datap->db_type == M_CTL);
20620 			first_mp = mp;
20621 			mp = mp->b_cont;
20622 			mctl_present = B_TRUE;
20623 		}
20624 	} else {
20625 		first_mp = mp;
20626 		mctl_present = B_FALSE;
20627 	}
20628 
20629 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20630 
20631 	/* is wrong version or IP options present */
20632 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20633 		goto version_hdrlen_check;
20634 	dst = ipha->ipha_dst;
20635 
20636 	/* If IP_BOUND_IF has been set, use that ill. */
20637 	if (connp->conn_outgoing_ill != NULL) {
20638 		xmit_ill = conn_get_held_ill(connp,
20639 		    &connp->conn_outgoing_ill, &err);
20640 		if (err == ILL_LOOKUP_FAILED)
20641 			goto drop_pkt;
20642 
20643 		goto send_from_ill;
20644 	}
20645 
20646 	/* is packet multicast? */
20647 	if (CLASSD(dst))
20648 		goto multicast;
20649 
20650 	/*
20651 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20652 	 * takes precedence over conn_dontroute and conn_nexthop_set
20653 	 */
20654 	if (xmit_ill != NULL)
20655 		goto send_from_ill;
20656 
20657 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20658 		/*
20659 		 * If the destination is a broadcast, local, or loopback
20660 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20661 		 * standard path.
20662 		 */
20663 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20664 		if ((ire == NULL) || (ire->ire_type &
20665 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20666 			if (ire != NULL) {
20667 				ire_refrele(ire);
20668 				/* No more access to ire */
20669 				ire = NULL;
20670 			}
20671 			/*
20672 			 * bypass routing checks and go directly to interface.
20673 			 */
20674 			if (connp->conn_dontroute)
20675 				goto dontroute;
20676 
20677 			ASSERT(connp->conn_nexthop_set);
20678 			ip_nexthop = B_TRUE;
20679 			nexthop_addr = connp->conn_nexthop_v4;
20680 			goto send_from_ill;
20681 		}
20682 
20683 		/* Must be a broadcast, a loopback or a local ire */
20684 		ire_refrele(ire);
20685 		/* No more access to ire */
20686 		ire = NULL;
20687 	}
20688 
20689 	/*
20690 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20691 	 * this for the tcp global queue and listen end point
20692 	 * as it does not really have a real destination to
20693 	 * talk to.  This is also true for SCTP.
20694 	 */
20695 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20696 	    !connp->conn_fully_bound) {
20697 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20698 		if (ire == NULL)
20699 			goto noirefound;
20700 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20701 		    "ip_wput_end: q %p (%S)", q, "end");
20702 
20703 		/*
20704 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20705 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20706 		 */
20707 		if (ire->ire_flags & RTF_MULTIRT) {
20708 
20709 			/*
20710 			 * Force the TTL of multirouted packets if required.
20711 			 * The TTL of such packets is bounded by the
20712 			 * ip_multirt_ttl ndd variable.
20713 			 */
20714 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20715 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20716 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20717 				    "(was %d), dst 0x%08x\n",
20718 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20719 				    ntohl(ire->ire_addr)));
20720 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20721 			}
20722 			/*
20723 			 * We look at this point if there are pending
20724 			 * unresolved routes. ire_multirt_resolvable()
20725 			 * checks in O(n) that all IRE_OFFSUBNET ire
20726 			 * entries for the packet's destination and
20727 			 * flagged RTF_MULTIRT are currently resolved.
20728 			 * If some remain unresolved, we make a copy
20729 			 * of the current message. It will be used
20730 			 * to initiate additional route resolutions.
20731 			 */
20732 			multirt_need_resolve =
20733 			    ire_multirt_need_resolve(ire->ire_addr,
20734 			    msg_getlabel(first_mp), ipst);
20735 			ip2dbg(("ip_wput[TCP]: ire %p, "
20736 			    "multirt_need_resolve %d, first_mp %p\n",
20737 			    (void *)ire, multirt_need_resolve,
20738 			    (void *)first_mp));
20739 			if (multirt_need_resolve) {
20740 				copy_mp = copymsg(first_mp);
20741 				if (copy_mp != NULL) {
20742 					MULTIRT_DEBUG_TAG(copy_mp);
20743 				}
20744 			}
20745 		}
20746 
20747 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20748 
20749 		/*
20750 		 * Try to resolve another multiroute if
20751 		 * ire_multirt_need_resolve() deemed it necessary.
20752 		 */
20753 		if (copy_mp != NULL)
20754 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20755 		if (need_decref)
20756 			CONN_DEC_REF(connp);
20757 		return;
20758 	}
20759 
20760 	/*
20761 	 * Access to conn_ire_cache. (protected by conn_lock)
20762 	 *
20763 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20764 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20765 	 * send a packet or two with the IRE_CACHE that is going away.
20766 	 * Access to the ire requires an ire refhold on the ire prior to
20767 	 * its use since an interface unplumb thread may delete the cached
20768 	 * ire and release the refhold at any time.
20769 	 *
20770 	 * Caching an ire in the conn_ire_cache
20771 	 *
20772 	 * o Caching an ire pointer in the conn requires a strict check for
20773 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20774 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20775 	 * in the conn is done after making sure under the bucket lock that the
20776 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20777 	 * caching an ire after the unplumb thread has cleaned up the conn.
20778 	 * If the conn does not send a packet subsequently the unplumb thread
20779 	 * will be hanging waiting for the ire count to drop to zero.
20780 	 *
20781 	 * o We also need to atomically test for a null conn_ire_cache and
20782 	 * set the conn_ire_cache under the the protection of the conn_lock
20783 	 * to avoid races among concurrent threads trying to simultaneously
20784 	 * cache an ire in the conn_ire_cache.
20785 	 */
20786 	mutex_enter(&connp->conn_lock);
20787 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20788 
20789 	if (ire != NULL && ire->ire_addr == dst &&
20790 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20791 
20792 		IRE_REFHOLD(ire);
20793 		mutex_exit(&connp->conn_lock);
20794 
20795 	} else {
20796 		boolean_t cached = B_FALSE;
20797 		connp->conn_ire_cache = NULL;
20798 		mutex_exit(&connp->conn_lock);
20799 		/* Release the old ire */
20800 		if (ire != NULL && sctp_ire == NULL)
20801 			IRE_REFRELE_NOTR(ire);
20802 
20803 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20804 		if (ire == NULL)
20805 			goto noirefound;
20806 		IRE_REFHOLD_NOTR(ire);
20807 
20808 		mutex_enter(&connp->conn_lock);
20809 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20810 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20811 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20812 				if (connp->conn_ulp == IPPROTO_TCP)
20813 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20814 				connp->conn_ire_cache = ire;
20815 				cached = B_TRUE;
20816 			}
20817 			rw_exit(&ire->ire_bucket->irb_lock);
20818 		}
20819 		mutex_exit(&connp->conn_lock);
20820 
20821 		/*
20822 		 * We can continue to use the ire but since it was
20823 		 * not cached, we should drop the extra reference.
20824 		 */
20825 		if (!cached)
20826 			IRE_REFRELE_NOTR(ire);
20827 	}
20828 
20829 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20830 	    "ip_wput_end: q %p (%S)", q, "end");
20831 
20832 	/*
20833 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20834 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20835 	 */
20836 	if (ire->ire_flags & RTF_MULTIRT) {
20837 		/*
20838 		 * Force the TTL of multirouted packets if required.
20839 		 * The TTL of such packets is bounded by the
20840 		 * ip_multirt_ttl ndd variable.
20841 		 */
20842 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20843 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20844 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20845 			    "(was %d), dst 0x%08x\n",
20846 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20847 			    ntohl(ire->ire_addr)));
20848 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20849 		}
20850 
20851 		/*
20852 		 * At this point, we check to see if there are any pending
20853 		 * unresolved routes. ire_multirt_resolvable()
20854 		 * checks in O(n) that all IRE_OFFSUBNET ire
20855 		 * entries for the packet's destination and
20856 		 * flagged RTF_MULTIRT are currently resolved.
20857 		 * If some remain unresolved, we make a copy
20858 		 * of the current message. It will be used
20859 		 * to initiate additional route resolutions.
20860 		 */
20861 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20862 		    msg_getlabel(first_mp), ipst);
20863 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20864 		    "multirt_need_resolve %d, first_mp %p\n",
20865 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20866 		if (multirt_need_resolve) {
20867 			copy_mp = copymsg(first_mp);
20868 			if (copy_mp != NULL) {
20869 				MULTIRT_DEBUG_TAG(copy_mp);
20870 			}
20871 		}
20872 	}
20873 
20874 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20875 
20876 	/*
20877 	 * Try to resolve another multiroute if
20878 	 * ire_multirt_resolvable() deemed it necessary
20879 	 */
20880 	if (copy_mp != NULL)
20881 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20882 	if (need_decref)
20883 		CONN_DEC_REF(connp);
20884 	return;
20885 
20886 qnext:
20887 	/*
20888 	 * Upper Level Protocols pass down complete IP datagrams
20889 	 * as M_DATA messages.	Everything else is a sideshow.
20890 	 *
20891 	 * 1) We could be re-entering ip_wput because of ip_neworute
20892 	 *    in which case we could have a IPSEC_OUT message. We
20893 	 *    need to pass through ip_wput like other datagrams and
20894 	 *    hence cannot branch to ip_wput_nondata.
20895 	 *
20896 	 * 2) ARP, AH, ESP, and other clients who are on the module
20897 	 *    instance of IP stream, give us something to deal with.
20898 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20899 	 *
20900 	 * 3) ICMP replies also could come here.
20901 	 */
20902 	ipst = ILLQ_TO_IPST(q);
20903 
20904 	if (DB_TYPE(mp) != M_DATA) {
20905 notdata:
20906 		if (DB_TYPE(mp) == M_CTL) {
20907 			/*
20908 			 * M_CTL messages are used by ARP, AH and ESP to
20909 			 * communicate with IP. We deal with IPSEC_IN and
20910 			 * IPSEC_OUT here. ip_wput_nondata handles other
20911 			 * cases.
20912 			 */
20913 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20914 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20915 				first_mp = mp->b_cont;
20916 				first_mp->b_flag &= ~MSGHASREF;
20917 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20918 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20919 				CONN_DEC_REF(connp);
20920 				connp = NULL;
20921 			}
20922 			if (ii->ipsec_info_type == IPSEC_IN) {
20923 				/*
20924 				 * Either this message goes back to
20925 				 * IPsec for further processing or to
20926 				 * ULP after policy checks.
20927 				 */
20928 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20929 				return;
20930 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20931 				io = (ipsec_out_t *)ii;
20932 				if (io->ipsec_out_proc_begin) {
20933 					/*
20934 					 * IPsec processing has already started.
20935 					 * Complete it.
20936 					 * IPQoS notes: We don't care what is
20937 					 * in ipsec_out_ill_index since this
20938 					 * won't be processed for IPQoS policies
20939 					 * in ipsec_out_process.
20940 					 */
20941 					ipsec_out_process(q, mp, NULL,
20942 					    io->ipsec_out_ill_index);
20943 					return;
20944 				} else {
20945 					connp = (q->q_next != NULL) ?
20946 					    NULL : Q_TO_CONN(q);
20947 					first_mp = mp;
20948 					mp = mp->b_cont;
20949 					mctl_present = B_TRUE;
20950 				}
20951 				zoneid = io->ipsec_out_zoneid;
20952 				ASSERT(zoneid != ALL_ZONES);
20953 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20954 				/*
20955 				 * It's an IPsec control message requesting
20956 				 * an SADB update to be sent to the IPsec
20957 				 * hardware acceleration capable ills.
20958 				 */
20959 				ipsec_ctl_t *ipsec_ctl =
20960 				    (ipsec_ctl_t *)mp->b_rptr;
20961 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20962 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20963 				mblk_t *cmp = mp->b_cont;
20964 
20965 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20966 				ASSERT(cmp != NULL);
20967 
20968 				freeb(mp);
20969 				ill_ipsec_capab_send_all(satype, cmp, sa,
20970 				    ipst->ips_netstack);
20971 				return;
20972 			} else {
20973 				/*
20974 				 * This must be ARP or special TSOL signaling.
20975 				 */
20976 				ip_wput_nondata(NULL, q, mp, NULL);
20977 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20978 				    "ip_wput_end: q %p (%S)", q, "nondata");
20979 				return;
20980 			}
20981 		} else {
20982 			/*
20983 			 * This must be non-(ARP/AH/ESP) messages.
20984 			 */
20985 			ASSERT(!need_decref);
20986 			ip_wput_nondata(NULL, q, mp, NULL);
20987 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20988 			    "ip_wput_end: q %p (%S)", q, "nondata");
20989 			return;
20990 		}
20991 	} else {
20992 		first_mp = mp;
20993 		mctl_present = B_FALSE;
20994 	}
20995 
20996 	ASSERT(first_mp != NULL);
20997 
20998 	if (mctl_present) {
20999 		io = (ipsec_out_t *)first_mp->b_rptr;
21000 		if (io->ipsec_out_ip_nexthop) {
21001 			/*
21002 			 * We may have lost the conn context if we are
21003 			 * coming here from ip_newroute(). Copy the
21004 			 * nexthop information.
21005 			 */
21006 			ip_nexthop = B_TRUE;
21007 			nexthop_addr = io->ipsec_out_nexthop_addr;
21008 
21009 			ipha = (ipha_t *)mp->b_rptr;
21010 			dst = ipha->ipha_dst;
21011 			goto send_from_ill;
21012 		}
21013 	}
21014 
21015 	ASSERT(xmit_ill == NULL);
21016 
21017 	/* We have a complete IP datagram heading outbound. */
21018 	ipha = (ipha_t *)mp->b_rptr;
21019 
21020 #ifndef SPEED_BEFORE_SAFETY
21021 	/*
21022 	 * Make sure we have a full-word aligned message and that at least
21023 	 * a simple IP header is accessible in the first message.  If not,
21024 	 * try a pullup.  For labeled systems we need to always take this
21025 	 * path as M_CTLs are "notdata" but have trailing data to process.
21026 	 */
21027 	if (!OK_32PTR(rptr) ||
21028 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21029 hdrtoosmall:
21030 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21031 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21032 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21033 			if (first_mp == NULL)
21034 				first_mp = mp;
21035 			goto discard_pkt;
21036 		}
21037 
21038 		/* This function assumes that mp points to an IPv4 packet. */
21039 		if (is_system_labeled() && q->q_next == NULL &&
21040 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21041 		    !connp->conn_ulp_labeled) {
21042 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
21043 			    connp->conn_mac_exempt, ipst);
21044 			ipha = (ipha_t *)mp->b_rptr;
21045 			if (first_mp != NULL)
21046 				first_mp->b_cont = mp;
21047 			if (err != 0) {
21048 				if (first_mp == NULL)
21049 					first_mp = mp;
21050 				if (err == EINVAL)
21051 					goto icmp_parameter_problem;
21052 				ip2dbg(("ip_wput: label check failed (%d)\n",
21053 				    err));
21054 				goto discard_pkt;
21055 			}
21056 		}
21057 
21058 		ipha = (ipha_t *)mp->b_rptr;
21059 		if (first_mp == NULL) {
21060 			ASSERT(xmit_ill == NULL);
21061 			/*
21062 			 * If we got here because of "goto hdrtoosmall"
21063 			 * We need to attach a IPSEC_OUT.
21064 			 */
21065 			if (connp->conn_out_enforce_policy) {
21066 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21067 				    NULL, ipha->ipha_protocol,
21068 				    ipst->ips_netstack)) == NULL)) {
21069 					BUMP_MIB(&ipst->ips_ip_mib,
21070 					    ipIfStatsOutDiscards);
21071 					if (need_decref)
21072 						CONN_DEC_REF(connp);
21073 					return;
21074 				} else {
21075 					ASSERT(mp->b_datap->db_type == M_CTL);
21076 					first_mp = mp;
21077 					mp = mp->b_cont;
21078 					mctl_present = B_TRUE;
21079 				}
21080 			} else {
21081 				first_mp = mp;
21082 				mctl_present = B_FALSE;
21083 			}
21084 		}
21085 	}
21086 #endif
21087 
21088 	/* Most of the code below is written for speed, not readability */
21089 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21090 
21091 	/*
21092 	 * If ip_newroute() fails, we're going to need a full
21093 	 * header for the icmp wraparound.
21094 	 */
21095 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21096 		uint_t	v_hlen;
21097 version_hdrlen_check:
21098 		ASSERT(first_mp != NULL);
21099 		v_hlen = V_HLEN;
21100 		/*
21101 		 * siphon off IPv6 packets coming down from transport
21102 		 * layer modules here.
21103 		 * Note: high-order bit carries NUD reachability confirmation
21104 		 */
21105 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21106 			/*
21107 			 * FIXME: assume that callers of ip_output* call
21108 			 * the right version?
21109 			 */
21110 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21111 			ASSERT(xmit_ill == NULL);
21112 			if (need_decref)
21113 				mp->b_flag |= MSGHASREF;
21114 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21115 			return;
21116 		}
21117 
21118 		if ((v_hlen >> 4) != IP_VERSION) {
21119 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21120 			    "ip_wput_end: q %p (%S)", q, "badvers");
21121 			goto discard_pkt;
21122 		}
21123 		/*
21124 		 * Is the header length at least 20 bytes?
21125 		 *
21126 		 * Are there enough bytes accessible in the header?  If
21127 		 * not, try a pullup.
21128 		 */
21129 		v_hlen &= 0xF;
21130 		v_hlen <<= 2;
21131 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21132 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21133 			    "ip_wput_end: q %p (%S)", q, "badlen");
21134 			goto discard_pkt;
21135 		}
21136 		if (v_hlen > (mp->b_wptr - rptr)) {
21137 			if (!pullupmsg(mp, v_hlen)) {
21138 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21139 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21140 				goto discard_pkt;
21141 			}
21142 			ipha = (ipha_t *)mp->b_rptr;
21143 		}
21144 		/*
21145 		 * Move first entry from any source route into ipha_dst and
21146 		 * verify the options
21147 		 */
21148 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21149 		    zoneid, ipst)) {
21150 			ASSERT(xmit_ill == NULL);
21151 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21152 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21153 			    "ip_wput_end: q %p (%S)", q, "badopts");
21154 			if (need_decref)
21155 				CONN_DEC_REF(connp);
21156 			return;
21157 		}
21158 	}
21159 	dst = ipha->ipha_dst;
21160 
21161 	/*
21162 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21163 	 * we have to run the packet through ip_newroute which will take
21164 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21165 	 * a resolver, or assigning a default gateway, etc.
21166 	 */
21167 	if (CLASSD(dst)) {
21168 		ipif_t	*ipif;
21169 		uint32_t setsrc = 0;
21170 
21171 multicast:
21172 		ASSERT(first_mp != NULL);
21173 		ip2dbg(("ip_wput: CLASSD\n"));
21174 		if (connp == NULL) {
21175 			/*
21176 			 * Use the first good ipif on the ill.
21177 			 * XXX Should this ever happen? (Appears
21178 			 * to show up with just ppp and no ethernet due
21179 			 * to in.rdisc.)
21180 			 * However, ire_send should be able to
21181 			 * call ip_wput_ire directly.
21182 			 *
21183 			 * XXX Also, this can happen for ICMP and other packets
21184 			 * with multicast source addresses.  Perhaps we should
21185 			 * fix things so that we drop the packet in question,
21186 			 * but for now, just run with it.
21187 			 */
21188 			ill_t *ill = (ill_t *)q->q_ptr;
21189 
21190 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21191 			if (ipif == NULL) {
21192 				if (need_decref)
21193 					CONN_DEC_REF(connp);
21194 				freemsg(first_mp);
21195 				return;
21196 			}
21197 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21198 			    ntohl(dst), ill->ill_name));
21199 		} else {
21200 			/*
21201 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21202 			 * and IP_MULTICAST_IF.  The block comment above this
21203 			 * function explains the locking mechanism used here.
21204 			 */
21205 			if (xmit_ill == NULL) {
21206 				xmit_ill = conn_get_held_ill(connp,
21207 				    &connp->conn_outgoing_ill, &err);
21208 				if (err == ILL_LOOKUP_FAILED) {
21209 					ip1dbg(("ip_wput: No ill for "
21210 					    "IP_BOUND_IF\n"));
21211 					BUMP_MIB(&ipst->ips_ip_mib,
21212 					    ipIfStatsOutNoRoutes);
21213 					goto drop_pkt;
21214 				}
21215 			}
21216 
21217 			if (xmit_ill == NULL) {
21218 				ipif = conn_get_held_ipif(connp,
21219 				    &connp->conn_multicast_ipif, &err);
21220 				if (err == IPIF_LOOKUP_FAILED) {
21221 					ip1dbg(("ip_wput: No ipif for "
21222 					    "multicast\n"));
21223 					BUMP_MIB(&ipst->ips_ip_mib,
21224 					    ipIfStatsOutNoRoutes);
21225 					goto drop_pkt;
21226 				}
21227 			}
21228 			if (xmit_ill != NULL) {
21229 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21230 				if (ipif == NULL) {
21231 					ip1dbg(("ip_wput: No ipif for "
21232 					    "xmit_ill\n"));
21233 					BUMP_MIB(&ipst->ips_ip_mib,
21234 					    ipIfStatsOutNoRoutes);
21235 					goto drop_pkt;
21236 				}
21237 			} else if (ipif == NULL || ipif->ipif_isv6) {
21238 				/*
21239 				 * We must do this ipif determination here
21240 				 * else we could pass through ip_newroute
21241 				 * and come back here without the conn context.
21242 				 *
21243 				 * Note: we do late binding i.e. we bind to
21244 				 * the interface when the first packet is sent.
21245 				 * For performance reasons we do not rebind on
21246 				 * each packet but keep the binding until the
21247 				 * next IP_MULTICAST_IF option.
21248 				 *
21249 				 * conn_multicast_{ipif,ill} are shared between
21250 				 * IPv4 and IPv6 and AF_INET6 sockets can
21251 				 * send both IPv4 and IPv6 packets. Hence
21252 				 * we have to check that "isv6" matches above.
21253 				 */
21254 				if (ipif != NULL)
21255 					ipif_refrele(ipif);
21256 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21257 				if (ipif == NULL) {
21258 					ip1dbg(("ip_wput: No ipif for "
21259 					    "multicast\n"));
21260 					BUMP_MIB(&ipst->ips_ip_mib,
21261 					    ipIfStatsOutNoRoutes);
21262 					goto drop_pkt;
21263 				}
21264 				err = conn_set_held_ipif(connp,
21265 				    &connp->conn_multicast_ipif, ipif);
21266 				if (err == IPIF_LOOKUP_FAILED) {
21267 					ipif_refrele(ipif);
21268 					ip1dbg(("ip_wput: No ipif for "
21269 					    "multicast\n"));
21270 					BUMP_MIB(&ipst->ips_ip_mib,
21271 					    ipIfStatsOutNoRoutes);
21272 					goto drop_pkt;
21273 				}
21274 			}
21275 		}
21276 		ASSERT(!ipif->ipif_isv6);
21277 		/*
21278 		 * As we may lose the conn by the time we reach ip_wput_ire,
21279 		 * we copy conn_multicast_loop and conn_dontroute on to an
21280 		 * ipsec_out. In case if this datagram goes out secure,
21281 		 * we need the ill_index also. Copy that also into the
21282 		 * ipsec_out.
21283 		 */
21284 		if (mctl_present) {
21285 			io = (ipsec_out_t *)first_mp->b_rptr;
21286 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21287 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21288 		} else {
21289 			ASSERT(mp == first_mp);
21290 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21291 			    BPRI_HI)) == NULL) {
21292 				ipif_refrele(ipif);
21293 				first_mp = mp;
21294 				goto discard_pkt;
21295 			}
21296 			first_mp->b_datap->db_type = M_CTL;
21297 			first_mp->b_wptr += sizeof (ipsec_info_t);
21298 			/* ipsec_out_secure is B_FALSE now */
21299 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21300 			io = (ipsec_out_t *)first_mp->b_rptr;
21301 			io->ipsec_out_type = IPSEC_OUT;
21302 			io->ipsec_out_len = sizeof (ipsec_out_t);
21303 			io->ipsec_out_use_global_policy = B_TRUE;
21304 			io->ipsec_out_ns = ipst->ips_netstack;
21305 			first_mp->b_cont = mp;
21306 			mctl_present = B_TRUE;
21307 		}
21308 
21309 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21310 		io->ipsec_out_ill_index =
21311 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21312 
21313 		if (connp != NULL) {
21314 			io->ipsec_out_multicast_loop =
21315 			    connp->conn_multicast_loop;
21316 			io->ipsec_out_dontroute = connp->conn_dontroute;
21317 			io->ipsec_out_zoneid = connp->conn_zoneid;
21318 		}
21319 		/*
21320 		 * If the application uses IP_MULTICAST_IF with
21321 		 * different logical addresses of the same ILL, we
21322 		 * need to make sure that the soruce address of
21323 		 * the packet matches the logical IP address used
21324 		 * in the option. We do it by initializing ipha_src
21325 		 * here. This should keep IPsec also happy as
21326 		 * when we return from IPsec processing, we don't
21327 		 * have to worry about getting the right address on
21328 		 * the packet. Thus it is sufficient to look for
21329 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21330 		 * MATCH_IRE_IPIF.
21331 		 *
21332 		 * NOTE : We need to do it for non-secure case also as
21333 		 * this might go out secure if there is a global policy
21334 		 * match in ip_wput_ire.
21335 		 *
21336 		 * As we do not have the ire yet, it is possible that
21337 		 * we set the source address here and then later discover
21338 		 * that the ire implies the source address to be assigned
21339 		 * through the RTF_SETSRC flag.
21340 		 * In that case, the setsrc variable will remind us
21341 		 * that overwritting the source address by the one
21342 		 * of the RTF_SETSRC-flagged ire is allowed.
21343 		 */
21344 		if (ipha->ipha_src == INADDR_ANY &&
21345 		    (connp == NULL || !connp->conn_unspec_src)) {
21346 			ipha->ipha_src = ipif->ipif_src_addr;
21347 			setsrc = RTF_SETSRC;
21348 		}
21349 		/*
21350 		 * Find an IRE which matches the destination and the outgoing
21351 		 * queue (i.e. the outgoing interface.)
21352 		 * For loopback use a unicast IP address for
21353 		 * the ire lookup.
21354 		 */
21355 		if (IS_LOOPBACK(ipif->ipif_ill))
21356 			dst = ipif->ipif_lcl_addr;
21357 
21358 		/*
21359 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21360 		 * We don't need to lookup ire in ctable as the packet
21361 		 * needs to be sent to the destination through the specified
21362 		 * ill irrespective of ires in the cache table.
21363 		 */
21364 		ire = NULL;
21365 		if (xmit_ill == NULL) {
21366 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21367 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21368 		}
21369 
21370 		if (ire == NULL) {
21371 			/*
21372 			 * Multicast loopback and multicast forwarding is
21373 			 * done in ip_wput_ire.
21374 			 *
21375 			 * Mark this packet to make it be delivered to
21376 			 * ip_wput_ire after the new ire has been
21377 			 * created.
21378 			 *
21379 			 * The call to ip_newroute_ipif takes into account
21380 			 * the setsrc reminder. In any case, we take care
21381 			 * of the RTF_MULTIRT flag.
21382 			 */
21383 			mp->b_prev = mp->b_next = NULL;
21384 			if (xmit_ill == NULL ||
21385 			    xmit_ill->ill_ipif_up_count > 0) {
21386 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21387 				    setsrc | RTF_MULTIRT, zoneid, infop);
21388 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21389 				    "ip_wput_end: q %p (%S)", q, "noire");
21390 			} else {
21391 				freemsg(first_mp);
21392 			}
21393 			ipif_refrele(ipif);
21394 			if (xmit_ill != NULL)
21395 				ill_refrele(xmit_ill);
21396 			if (need_decref)
21397 				CONN_DEC_REF(connp);
21398 			return;
21399 		}
21400 
21401 		ipif_refrele(ipif);
21402 		ipif = NULL;
21403 		ASSERT(xmit_ill == NULL);
21404 
21405 		/*
21406 		 * Honor the RTF_SETSRC flag for multicast packets,
21407 		 * if allowed by the setsrc reminder.
21408 		 */
21409 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21410 			ipha->ipha_src = ire->ire_src_addr;
21411 		}
21412 
21413 		/*
21414 		 * Unconditionally force the TTL to 1 for
21415 		 * multirouted multicast packets:
21416 		 * multirouted multicast should not cross
21417 		 * multicast routers.
21418 		 */
21419 		if (ire->ire_flags & RTF_MULTIRT) {
21420 			if (ipha->ipha_ttl > 1) {
21421 				ip2dbg(("ip_wput: forcing multicast "
21422 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21423 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21424 				ipha->ipha_ttl = 1;
21425 			}
21426 		}
21427 	} else {
21428 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21429 		if ((ire != NULL) && (ire->ire_type &
21430 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21431 			ignore_dontroute = B_TRUE;
21432 			ignore_nexthop = B_TRUE;
21433 		}
21434 		if (ire != NULL) {
21435 			ire_refrele(ire);
21436 			ire = NULL;
21437 		}
21438 		/*
21439 		 * Guard against coming in from arp in which case conn is NULL.
21440 		 * Also guard against non M_DATA with dontroute set but
21441 		 * destined to local, loopback or broadcast addresses.
21442 		 */
21443 		if (connp != NULL && connp->conn_dontroute &&
21444 		    !ignore_dontroute) {
21445 dontroute:
21446 			/*
21447 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21448 			 * routing protocols from seeing false direct
21449 			 * connectivity.
21450 			 */
21451 			ipha->ipha_ttl = 1;
21452 			/* If suitable ipif not found, drop packet */
21453 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21454 			if (dst_ipif == NULL) {
21455 noroute:
21456 				ip1dbg(("ip_wput: no route for dst using"
21457 				    " SO_DONTROUTE\n"));
21458 				BUMP_MIB(&ipst->ips_ip_mib,
21459 				    ipIfStatsOutNoRoutes);
21460 				mp->b_prev = mp->b_next = NULL;
21461 				if (first_mp == NULL)
21462 					first_mp = mp;
21463 				goto drop_pkt;
21464 			} else {
21465 				/*
21466 				 * If suitable ipif has been found, set
21467 				 * xmit_ill to the corresponding
21468 				 * ipif_ill because we'll be using the
21469 				 * send_from_ill logic below.
21470 				 */
21471 				ASSERT(xmit_ill == NULL);
21472 				xmit_ill = dst_ipif->ipif_ill;
21473 				mutex_enter(&xmit_ill->ill_lock);
21474 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21475 					mutex_exit(&xmit_ill->ill_lock);
21476 					xmit_ill = NULL;
21477 					ipif_refrele(dst_ipif);
21478 					goto noroute;
21479 				}
21480 				ill_refhold_locked(xmit_ill);
21481 				mutex_exit(&xmit_ill->ill_lock);
21482 				ipif_refrele(dst_ipif);
21483 			}
21484 		}
21485 
21486 send_from_ill:
21487 		if (xmit_ill != NULL) {
21488 			ipif_t *ipif;
21489 
21490 			/*
21491 			 * Mark this packet as originated locally
21492 			 */
21493 			mp->b_prev = mp->b_next = NULL;
21494 
21495 			/*
21496 			 * Could be SO_DONTROUTE case also.
21497 			 * Verify that at least one ipif is up on the ill.
21498 			 */
21499 			if (xmit_ill->ill_ipif_up_count == 0) {
21500 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21501 				    xmit_ill->ill_name));
21502 				goto drop_pkt;
21503 			}
21504 
21505 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21506 			if (ipif == NULL) {
21507 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21508 				    xmit_ill->ill_name));
21509 				goto drop_pkt;
21510 			}
21511 
21512 			match_flags = 0;
21513 			if (IS_UNDER_IPMP(xmit_ill))
21514 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21515 
21516 			/*
21517 			 * Look for a ire that is part of the group,
21518 			 * if found use it else call ip_newroute_ipif.
21519 			 * IPCL_ZONEID is not used for matching because
21520 			 * IP_ALLZONES option is valid only when the
21521 			 * ill is accessible from all zones i.e has a
21522 			 * valid ipif in all zones.
21523 			 */
21524 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21525 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21526 			    msg_getlabel(mp), match_flags, ipst);
21527 			/*
21528 			 * If an ire exists use it or else create
21529 			 * an ire but don't add it to the cache.
21530 			 * Adding an ire may cause issues with
21531 			 * asymmetric routing.
21532 			 * In case of multiroute always act as if
21533 			 * ire does not exist.
21534 			 */
21535 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21536 				if (ire != NULL)
21537 					ire_refrele(ire);
21538 				ip_newroute_ipif(q, first_mp, ipif,
21539 				    dst, connp, 0, zoneid, infop);
21540 				ipif_refrele(ipif);
21541 				ip1dbg(("ip_output: xmit_ill via %s\n",
21542 				    xmit_ill->ill_name));
21543 				ill_refrele(xmit_ill);
21544 				if (need_decref)
21545 					CONN_DEC_REF(connp);
21546 				return;
21547 			}
21548 			ipif_refrele(ipif);
21549 		} else if (ip_nexthop || (connp != NULL &&
21550 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21551 			if (!ip_nexthop) {
21552 				ip_nexthop = B_TRUE;
21553 				nexthop_addr = connp->conn_nexthop_v4;
21554 			}
21555 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21556 			    MATCH_IRE_GW;
21557 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21558 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21559 		} else {
21560 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21561 			    ipst);
21562 		}
21563 		if (!ire) {
21564 			if (ip_nexthop && !ignore_nexthop) {
21565 				if (mctl_present) {
21566 					io = (ipsec_out_t *)first_mp->b_rptr;
21567 					ASSERT(first_mp->b_datap->db_type ==
21568 					    M_CTL);
21569 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21570 				} else {
21571 					ASSERT(mp == first_mp);
21572 					first_mp = allocb(
21573 					    sizeof (ipsec_info_t), BPRI_HI);
21574 					if (first_mp == NULL) {
21575 						first_mp = mp;
21576 						goto discard_pkt;
21577 					}
21578 					first_mp->b_datap->db_type = M_CTL;
21579 					first_mp->b_wptr +=
21580 					    sizeof (ipsec_info_t);
21581 					/* ipsec_out_secure is B_FALSE now */
21582 					bzero(first_mp->b_rptr,
21583 					    sizeof (ipsec_info_t));
21584 					io = (ipsec_out_t *)first_mp->b_rptr;
21585 					io->ipsec_out_type = IPSEC_OUT;
21586 					io->ipsec_out_len =
21587 					    sizeof (ipsec_out_t);
21588 					io->ipsec_out_use_global_policy =
21589 					    B_TRUE;
21590 					io->ipsec_out_ns = ipst->ips_netstack;
21591 					first_mp->b_cont = mp;
21592 					mctl_present = B_TRUE;
21593 				}
21594 				io->ipsec_out_ip_nexthop = ip_nexthop;
21595 				io->ipsec_out_nexthop_addr = nexthop_addr;
21596 			}
21597 noirefound:
21598 			/*
21599 			 * Mark this packet as having originated on
21600 			 * this machine.  This will be noted in
21601 			 * ire_add_then_send, which needs to know
21602 			 * whether to run it back through ip_wput or
21603 			 * ip_rput following successful resolution.
21604 			 */
21605 			mp->b_prev = NULL;
21606 			mp->b_next = NULL;
21607 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21608 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21609 			    "ip_wput_end: q %p (%S)", q, "newroute");
21610 			if (xmit_ill != NULL)
21611 				ill_refrele(xmit_ill);
21612 			if (need_decref)
21613 				CONN_DEC_REF(connp);
21614 			return;
21615 		}
21616 	}
21617 
21618 	/* We now know where we are going with it. */
21619 
21620 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21621 	    "ip_wput_end: q %p (%S)", q, "end");
21622 
21623 	/*
21624 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21625 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21626 	 */
21627 	if (ire->ire_flags & RTF_MULTIRT) {
21628 		/*
21629 		 * Force the TTL of multirouted packets if required.
21630 		 * The TTL of such packets is bounded by the
21631 		 * ip_multirt_ttl ndd variable.
21632 		 */
21633 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21634 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21635 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21636 			    "(was %d), dst 0x%08x\n",
21637 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21638 			    ntohl(ire->ire_addr)));
21639 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21640 		}
21641 		/*
21642 		 * At this point, we check to see if there are any pending
21643 		 * unresolved routes. ire_multirt_resolvable()
21644 		 * checks in O(n) that all IRE_OFFSUBNET ire
21645 		 * entries for the packet's destination and
21646 		 * flagged RTF_MULTIRT are currently resolved.
21647 		 * If some remain unresolved, we make a copy
21648 		 * of the current message. It will be used
21649 		 * to initiate additional route resolutions.
21650 		 */
21651 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21652 		    msg_getlabel(first_mp), ipst);
21653 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21654 		    "multirt_need_resolve %d, first_mp %p\n",
21655 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21656 		if (multirt_need_resolve) {
21657 			copy_mp = copymsg(first_mp);
21658 			if (copy_mp != NULL) {
21659 				MULTIRT_DEBUG_TAG(copy_mp);
21660 			}
21661 		}
21662 	}
21663 
21664 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21665 	/*
21666 	 * Try to resolve another multiroute if
21667 	 * ire_multirt_resolvable() deemed it necessary.
21668 	 * At this point, we need to distinguish
21669 	 * multicasts from other packets. For multicasts,
21670 	 * we call ip_newroute_ipif() and request that both
21671 	 * multirouting and setsrc flags are checked.
21672 	 */
21673 	if (copy_mp != NULL) {
21674 		if (CLASSD(dst)) {
21675 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21676 			if (ipif) {
21677 				ASSERT(infop->ip_opt_ill_index == 0);
21678 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21679 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21680 				ipif_refrele(ipif);
21681 			} else {
21682 				MULTIRT_DEBUG_UNTAG(copy_mp);
21683 				freemsg(copy_mp);
21684 				copy_mp = NULL;
21685 			}
21686 		} else {
21687 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21688 		}
21689 	}
21690 	if (xmit_ill != NULL)
21691 		ill_refrele(xmit_ill);
21692 	if (need_decref)
21693 		CONN_DEC_REF(connp);
21694 	return;
21695 
21696 icmp_parameter_problem:
21697 	/* could not have originated externally */
21698 	ASSERT(mp->b_prev == NULL);
21699 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21700 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21701 		/* it's the IP header length that's in trouble */
21702 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21703 		first_mp = NULL;
21704 	}
21705 
21706 discard_pkt:
21707 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21708 drop_pkt:
21709 	ip1dbg(("ip_wput: dropped packet\n"));
21710 	if (ire != NULL)
21711 		ire_refrele(ire);
21712 	if (need_decref)
21713 		CONN_DEC_REF(connp);
21714 	freemsg(first_mp);
21715 	if (xmit_ill != NULL)
21716 		ill_refrele(xmit_ill);
21717 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21718 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21719 }
21720 
21721 /*
21722  * If this is a conn_t queue, then we pass in the conn. This includes the
21723  * zoneid.
21724  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21725  * in which case we use the global zoneid since those are all part of
21726  * the global zone.
21727  */
21728 void
21729 ip_wput(queue_t *q, mblk_t *mp)
21730 {
21731 	if (CONN_Q(q))
21732 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21733 	else
21734 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21735 }
21736 
21737 /*
21738  *
21739  * The following rules must be observed when accessing any ipif or ill
21740  * that has been cached in the conn. Typically conn_outgoing_ill,
21741  * conn_multicast_ipif and conn_multicast_ill.
21742  *
21743  * Access: The ipif or ill pointed to from the conn can be accessed under
21744  * the protection of the conn_lock or after it has been refheld under the
21745  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21746  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21747  * The reason for this is that a concurrent unplumb could actually be
21748  * cleaning up these cached pointers by walking the conns and might have
21749  * finished cleaning up the conn in question. The macros check that an
21750  * unplumb has not yet started on the ipif or ill.
21751  *
21752  * Caching: An ipif or ill pointer may be cached in the conn only after
21753  * making sure that an unplumb has not started. So the caching is done
21754  * while holding both the conn_lock and the ill_lock and after using the
21755  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21756  * flag before starting the cleanup of conns.
21757  *
21758  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21759  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21760  * or a reference to the ipif or a reference to an ire that references the
21761  * ipif. An ipif only changes its ill when migrating from an underlying ill
21762  * to an IPMP ill in ipif_up().
21763  */
21764 ipif_t *
21765 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21766 {
21767 	ipif_t	*ipif;
21768 	ill_t	*ill;
21769 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21770 
21771 	*err = 0;
21772 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21773 	mutex_enter(&connp->conn_lock);
21774 	ipif = *ipifp;
21775 	if (ipif != NULL) {
21776 		ill = ipif->ipif_ill;
21777 		mutex_enter(&ill->ill_lock);
21778 		if (IPIF_CAN_LOOKUP(ipif)) {
21779 			ipif_refhold_locked(ipif);
21780 			mutex_exit(&ill->ill_lock);
21781 			mutex_exit(&connp->conn_lock);
21782 			rw_exit(&ipst->ips_ill_g_lock);
21783 			return (ipif);
21784 		} else {
21785 			*err = IPIF_LOOKUP_FAILED;
21786 		}
21787 		mutex_exit(&ill->ill_lock);
21788 	}
21789 	mutex_exit(&connp->conn_lock);
21790 	rw_exit(&ipst->ips_ill_g_lock);
21791 	return (NULL);
21792 }
21793 
21794 ill_t *
21795 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21796 {
21797 	ill_t	*ill;
21798 
21799 	*err = 0;
21800 	mutex_enter(&connp->conn_lock);
21801 	ill = *illp;
21802 	if (ill != NULL) {
21803 		mutex_enter(&ill->ill_lock);
21804 		if (ILL_CAN_LOOKUP(ill)) {
21805 			ill_refhold_locked(ill);
21806 			mutex_exit(&ill->ill_lock);
21807 			mutex_exit(&connp->conn_lock);
21808 			return (ill);
21809 		} else {
21810 			*err = ILL_LOOKUP_FAILED;
21811 		}
21812 		mutex_exit(&ill->ill_lock);
21813 	}
21814 	mutex_exit(&connp->conn_lock);
21815 	return (NULL);
21816 }
21817 
21818 static int
21819 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21820 {
21821 	ill_t	*ill;
21822 
21823 	ill = ipif->ipif_ill;
21824 	mutex_enter(&connp->conn_lock);
21825 	mutex_enter(&ill->ill_lock);
21826 	if (IPIF_CAN_LOOKUP(ipif)) {
21827 		*ipifp = ipif;
21828 		mutex_exit(&ill->ill_lock);
21829 		mutex_exit(&connp->conn_lock);
21830 		return (0);
21831 	}
21832 	mutex_exit(&ill->ill_lock);
21833 	mutex_exit(&connp->conn_lock);
21834 	return (IPIF_LOOKUP_FAILED);
21835 }
21836 
21837 /*
21838  * This is called if the outbound datagram needs fragmentation.
21839  *
21840  * NOTE : This function does not ire_refrele the ire argument passed in.
21841  */
21842 static void
21843 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21844     ip_stack_t *ipst, conn_t *connp)
21845 {
21846 	ipha_t		*ipha;
21847 	mblk_t		*mp;
21848 	uint32_t	v_hlen_tos_len;
21849 	uint32_t	max_frag;
21850 	uint32_t	frag_flag;
21851 	boolean_t	dont_use;
21852 
21853 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21854 		mp = ipsec_mp->b_cont;
21855 	} else {
21856 		mp = ipsec_mp;
21857 	}
21858 
21859 	ipha = (ipha_t *)mp->b_rptr;
21860 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21861 
21862 #ifdef	_BIG_ENDIAN
21863 #define	V_HLEN	(v_hlen_tos_len >> 24)
21864 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21865 #else
21866 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21867 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21868 #endif
21869 
21870 #ifndef SPEED_BEFORE_SAFETY
21871 	/*
21872 	 * Check that ipha_length is consistent with
21873 	 * the mblk length
21874 	 */
21875 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21876 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21877 		    LENGTH, msgdsize(mp)));
21878 		freemsg(ipsec_mp);
21879 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21880 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21881 		    "packet length mismatch");
21882 		return;
21883 	}
21884 #endif
21885 	/*
21886 	 * Don't use frag_flag if pre-built packet or source
21887 	 * routed or if multicast (since multicast packets do not solicit
21888 	 * ICMP "packet too big" messages). Get the values of
21889 	 * max_frag and frag_flag atomically by acquiring the
21890 	 * ire_lock.
21891 	 */
21892 	mutex_enter(&ire->ire_lock);
21893 	max_frag = ire->ire_max_frag;
21894 	frag_flag = ire->ire_frag_flag;
21895 	mutex_exit(&ire->ire_lock);
21896 
21897 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21898 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21899 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21900 
21901 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21902 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21903 }
21904 
21905 /*
21906  * Used for deciding the MSS size for the upper layer. Thus
21907  * we need to check the outbound policy values in the conn.
21908  */
21909 int
21910 conn_ipsec_length(conn_t *connp)
21911 {
21912 	ipsec_latch_t *ipl;
21913 
21914 	ipl = connp->conn_latch;
21915 	if (ipl == NULL)
21916 		return (0);
21917 
21918 	if (ipl->ipl_out_policy == NULL)
21919 		return (0);
21920 
21921 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21922 }
21923 
21924 /*
21925  * Returns an estimate of the IPsec headers size. This is used if
21926  * we don't want to call into IPsec to get the exact size.
21927  */
21928 int
21929 ipsec_out_extra_length(mblk_t *ipsec_mp)
21930 {
21931 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21932 	ipsec_action_t *a;
21933 
21934 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21935 	if (!io->ipsec_out_secure)
21936 		return (0);
21937 
21938 	a = io->ipsec_out_act;
21939 
21940 	if (a == NULL) {
21941 		ASSERT(io->ipsec_out_policy != NULL);
21942 		a = io->ipsec_out_policy->ipsp_act;
21943 	}
21944 	ASSERT(a != NULL);
21945 
21946 	return (a->ipa_ovhd);
21947 }
21948 
21949 /*
21950  * Returns an estimate of the IPsec headers size. This is used if
21951  * we don't want to call into IPsec to get the exact size.
21952  */
21953 int
21954 ipsec_in_extra_length(mblk_t *ipsec_mp)
21955 {
21956 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21957 	ipsec_action_t *a;
21958 
21959 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21960 
21961 	a = ii->ipsec_in_action;
21962 	return (a == NULL ? 0 : a->ipa_ovhd);
21963 }
21964 
21965 /*
21966  * If there are any source route options, return the true final
21967  * destination. Otherwise, return the destination.
21968  */
21969 ipaddr_t
21970 ip_get_dst(ipha_t *ipha)
21971 {
21972 	ipoptp_t	opts;
21973 	uchar_t		*opt;
21974 	uint8_t		optval;
21975 	uint8_t		optlen;
21976 	ipaddr_t	dst;
21977 	uint32_t off;
21978 
21979 	dst = ipha->ipha_dst;
21980 
21981 	if (IS_SIMPLE_IPH(ipha))
21982 		return (dst);
21983 
21984 	for (optval = ipoptp_first(&opts, ipha);
21985 	    optval != IPOPT_EOL;
21986 	    optval = ipoptp_next(&opts)) {
21987 		opt = opts.ipoptp_cur;
21988 		optlen = opts.ipoptp_len;
21989 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21990 		switch (optval) {
21991 		case IPOPT_SSRR:
21992 		case IPOPT_LSRR:
21993 			off = opt[IPOPT_OFFSET];
21994 			/*
21995 			 * If one of the conditions is true, it means
21996 			 * end of options and dst already has the right
21997 			 * value.
21998 			 */
21999 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22000 				off = optlen - IP_ADDR_LEN;
22001 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22002 			}
22003 			return (dst);
22004 		default:
22005 			break;
22006 		}
22007 	}
22008 
22009 	return (dst);
22010 }
22011 
22012 mblk_t *
22013 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22014     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22015 {
22016 	ipsec_out_t	*io;
22017 	mblk_t		*first_mp;
22018 	boolean_t policy_present;
22019 	ip_stack_t	*ipst;
22020 	ipsec_stack_t	*ipss;
22021 
22022 	ASSERT(ire != NULL);
22023 	ipst = ire->ire_ipst;
22024 	ipss = ipst->ips_netstack->netstack_ipsec;
22025 
22026 	first_mp = mp;
22027 	if (mp->b_datap->db_type == M_CTL) {
22028 		io = (ipsec_out_t *)first_mp->b_rptr;
22029 		/*
22030 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22031 		 *
22032 		 * 1) There is per-socket policy (including cached global
22033 		 *    policy) or a policy on the IP-in-IP tunnel.
22034 		 * 2) There is no per-socket policy, but it is
22035 		 *    a multicast packet that needs to go out
22036 		 *    on a specific interface. This is the case
22037 		 *    where (ip_wput and ip_wput_multicast) attaches
22038 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22039 		 *
22040 		 * In case (2) we check with global policy to
22041 		 * see if there is a match and set the ill_index
22042 		 * appropriately so that we can lookup the ire
22043 		 * properly in ip_wput_ipsec_out.
22044 		 */
22045 
22046 		/*
22047 		 * ipsec_out_use_global_policy is set to B_FALSE
22048 		 * in ipsec_in_to_out(). Refer to that function for
22049 		 * details.
22050 		 */
22051 		if ((io->ipsec_out_latch == NULL) &&
22052 		    (io->ipsec_out_use_global_policy)) {
22053 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22054 			    ire, connp, unspec_src, zoneid));
22055 		}
22056 		if (!io->ipsec_out_secure) {
22057 			/*
22058 			 * If this is not a secure packet, drop
22059 			 * the IPSEC_OUT mp and treat it as a clear
22060 			 * packet. This happens when we are sending
22061 			 * a ICMP reply back to a clear packet. See
22062 			 * ipsec_in_to_out() for details.
22063 			 */
22064 			mp = first_mp->b_cont;
22065 			freeb(first_mp);
22066 		}
22067 		return (mp);
22068 	}
22069 	/*
22070 	 * See whether we need to attach a global policy here. We
22071 	 * don't depend on the conn (as it could be null) for deciding
22072 	 * what policy this datagram should go through because it
22073 	 * should have happened in ip_wput if there was some
22074 	 * policy. This normally happens for connections which are not
22075 	 * fully bound preventing us from caching policies in
22076 	 * ip_bind. Packets coming from the TCP listener/global queue
22077 	 * - which are non-hard_bound - could also be affected by
22078 	 * applying policy here.
22079 	 *
22080 	 * If this packet is coming from tcp global queue or listener,
22081 	 * we will be applying policy here.  This may not be *right*
22082 	 * if these packets are coming from the detached connection as
22083 	 * it could have gone in clear before. This happens only if a
22084 	 * TCP connection started when there is no policy and somebody
22085 	 * added policy before it became detached. Thus packets of the
22086 	 * detached connection could go out secure and the other end
22087 	 * would drop it because it will be expecting in clear. The
22088 	 * converse is not true i.e if somebody starts a TCP
22089 	 * connection and deletes the policy, all the packets will
22090 	 * still go out with the policy that existed before deleting
22091 	 * because ip_unbind sends up policy information which is used
22092 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22093 	 * TCP to attach a dummy IPSEC_OUT and set
22094 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22095 	 * affect performance for normal cases, we are not doing it.
22096 	 * Thus, set policy before starting any TCP connections.
22097 	 *
22098 	 * NOTE - We might apply policy even for a hard bound connection
22099 	 * - for which we cached policy in ip_bind - if somebody added
22100 	 * global policy after we inherited the policy in ip_bind.
22101 	 * This means that the packets that were going out in clear
22102 	 * previously would start going secure and hence get dropped
22103 	 * on the other side. To fix this, TCP attaches a dummy
22104 	 * ipsec_out and make sure that we don't apply global policy.
22105 	 */
22106 	if (ipha != NULL)
22107 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22108 	else
22109 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22110 	if (!policy_present)
22111 		return (mp);
22112 
22113 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22114 	    zoneid));
22115 }
22116 
22117 /*
22118  * This function does the ire_refrele of the ire passed in as the
22119  * argument. As this function looks up more ires i.e broadcast ires,
22120  * it needs to REFRELE them. Currently, for simplicity we don't
22121  * differentiate the one passed in and looked up here. We always
22122  * REFRELE.
22123  * IPQoS Notes:
22124  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22125  * IPsec packets are done in ipsec_out_process.
22126  */
22127 void
22128 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22129     zoneid_t zoneid)
22130 {
22131 	ipha_t		*ipha;
22132 #define	rptr	((uchar_t *)ipha)
22133 	queue_t		*stq;
22134 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22135 	uint32_t	v_hlen_tos_len;
22136 	uint32_t	ttl_protocol;
22137 	ipaddr_t	src;
22138 	ipaddr_t	dst;
22139 	uint32_t	cksum;
22140 	ipaddr_t	orig_src;
22141 	ire_t		*ire1;
22142 	mblk_t		*next_mp;
22143 	uint_t		hlen;
22144 	uint16_t	*up;
22145 	uint32_t	max_frag = ire->ire_max_frag;
22146 	ill_t		*ill = ire_to_ill(ire);
22147 	int		clusterwide;
22148 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22149 	int		ipsec_len;
22150 	mblk_t		*first_mp;
22151 	ipsec_out_t	*io;
22152 	boolean_t	conn_dontroute;		/* conn value for multicast */
22153 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22154 	boolean_t	multicast_forward;	/* Should we forward ? */
22155 	boolean_t	unspec_src;
22156 	ill_t		*conn_outgoing_ill = NULL;
22157 	ill_t		*ire_ill;
22158 	ill_t		*ire1_ill;
22159 	ill_t		*out_ill;
22160 	uint32_t 	ill_index = 0;
22161 	boolean_t	multirt_send = B_FALSE;
22162 	int		err;
22163 	ipxmit_state_t	pktxmit_state;
22164 	ip_stack_t	*ipst = ire->ire_ipst;
22165 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22166 
22167 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22168 	    "ip_wput_ire_start: q %p", q);
22169 
22170 	multicast_forward = B_FALSE;
22171 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22172 
22173 	if (ire->ire_flags & RTF_MULTIRT) {
22174 		/*
22175 		 * Multirouting case. The bucket where ire is stored
22176 		 * probably holds other RTF_MULTIRT flagged ire
22177 		 * to the destination. In this call to ip_wput_ire,
22178 		 * we attempt to send the packet through all
22179 		 * those ires. Thus, we first ensure that ire is the
22180 		 * first RTF_MULTIRT ire in the bucket,
22181 		 * before walking the ire list.
22182 		 */
22183 		ire_t *first_ire;
22184 		irb_t *irb = ire->ire_bucket;
22185 		ASSERT(irb != NULL);
22186 
22187 		/* Make sure we do not omit any multiroute ire. */
22188 		IRB_REFHOLD(irb);
22189 		for (first_ire = irb->irb_ire;
22190 		    first_ire != NULL;
22191 		    first_ire = first_ire->ire_next) {
22192 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22193 			    (first_ire->ire_addr == ire->ire_addr) &&
22194 			    !(first_ire->ire_marks &
22195 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22196 				break;
22197 		}
22198 
22199 		if ((first_ire != NULL) && (first_ire != ire)) {
22200 			IRE_REFHOLD(first_ire);
22201 			ire_refrele(ire);
22202 			ire = first_ire;
22203 			ill = ire_to_ill(ire);
22204 		}
22205 		IRB_REFRELE(irb);
22206 	}
22207 
22208 	/*
22209 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22210 	 * for performance we don't grab the mutexs in the fastpath
22211 	 */
22212 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22213 	    connp->conn_outgoing_ill != NULL) {
22214 		conn_outgoing_ill = conn_get_held_ill(connp,
22215 		    &connp->conn_outgoing_ill, &err);
22216 		if (err == ILL_LOOKUP_FAILED) {
22217 			ire_refrele(ire);
22218 			freemsg(mp);
22219 			return;
22220 		}
22221 	}
22222 
22223 	if (mp->b_datap->db_type != M_CTL) {
22224 		ipha = (ipha_t *)mp->b_rptr;
22225 	} else {
22226 		io = (ipsec_out_t *)mp->b_rptr;
22227 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22228 		ASSERT(zoneid == io->ipsec_out_zoneid);
22229 		ASSERT(zoneid != ALL_ZONES);
22230 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22231 		dst = ipha->ipha_dst;
22232 		/*
22233 		 * For the multicast case, ipsec_out carries conn_dontroute and
22234 		 * conn_multicast_loop as conn may not be available here. We
22235 		 * need this for multicast loopback and forwarding which is done
22236 		 * later in the code.
22237 		 */
22238 		if (CLASSD(dst)) {
22239 			conn_dontroute = io->ipsec_out_dontroute;
22240 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22241 			/*
22242 			 * If conn_dontroute is not set or conn_multicast_loop
22243 			 * is set, we need to do forwarding/loopback. For
22244 			 * datagrams from ip_wput_multicast, conn_dontroute is
22245 			 * set to B_TRUE and conn_multicast_loop is set to
22246 			 * B_FALSE so that we neither do forwarding nor
22247 			 * loopback.
22248 			 */
22249 			if (!conn_dontroute || conn_multicast_loop)
22250 				multicast_forward = B_TRUE;
22251 		}
22252 	}
22253 
22254 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22255 	    ire->ire_zoneid != ALL_ZONES) {
22256 		/*
22257 		 * When a zone sends a packet to another zone, we try to deliver
22258 		 * the packet under the same conditions as if the destination
22259 		 * was a real node on the network. To do so, we look for a
22260 		 * matching route in the forwarding table.
22261 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22262 		 * ip_newroute() does.
22263 		 * Note that IRE_LOCAL are special, since they are used
22264 		 * when the zoneid doesn't match in some cases. This means that
22265 		 * we need to handle ipha_src differently since ire_src_addr
22266 		 * belongs to the receiving zone instead of the sending zone.
22267 		 * When ip_restrict_interzone_loopback is set, then
22268 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22269 		 * for loopback between zones when the logical "Ethernet" would
22270 		 * have looped them back.
22271 		 */
22272 		ire_t *src_ire;
22273 
22274 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22275 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22276 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22277 		if (src_ire != NULL &&
22278 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22279 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22280 		    ire_local_same_lan(ire, src_ire))) {
22281 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22282 				ipha->ipha_src = src_ire->ire_src_addr;
22283 			ire_refrele(src_ire);
22284 		} else {
22285 			ire_refrele(ire);
22286 			if (conn_outgoing_ill != NULL)
22287 				ill_refrele(conn_outgoing_ill);
22288 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22289 			if (src_ire != NULL) {
22290 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22291 					ire_refrele(src_ire);
22292 					freemsg(mp);
22293 					return;
22294 				}
22295 				ire_refrele(src_ire);
22296 			}
22297 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22298 				/* Failed */
22299 				freemsg(mp);
22300 				return;
22301 			}
22302 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22303 			    ipst);
22304 			return;
22305 		}
22306 	}
22307 
22308 	if (mp->b_datap->db_type == M_CTL ||
22309 	    ipss->ipsec_outbound_v4_policy_present) {
22310 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22311 		    unspec_src, zoneid);
22312 		if (mp == NULL) {
22313 			ire_refrele(ire);
22314 			if (conn_outgoing_ill != NULL)
22315 				ill_refrele(conn_outgoing_ill);
22316 			return;
22317 		}
22318 		/*
22319 		 * Trusted Extensions supports all-zones interfaces, so
22320 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22321 		 * the global zone.
22322 		 */
22323 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22324 			io = (ipsec_out_t *)mp->b_rptr;
22325 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22326 			zoneid = io->ipsec_out_zoneid;
22327 		}
22328 	}
22329 
22330 	first_mp = mp;
22331 	ipsec_len = 0;
22332 
22333 	if (first_mp->b_datap->db_type == M_CTL) {
22334 		io = (ipsec_out_t *)first_mp->b_rptr;
22335 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22336 		mp = first_mp->b_cont;
22337 		ipsec_len = ipsec_out_extra_length(first_mp);
22338 		ASSERT(ipsec_len >= 0);
22339 		/* We already picked up the zoneid from the M_CTL above */
22340 		ASSERT(zoneid == io->ipsec_out_zoneid);
22341 		ASSERT(zoneid != ALL_ZONES);
22342 
22343 		/*
22344 		 * Drop M_CTL here if IPsec processing is not needed.
22345 		 * (Non-IPsec use of M_CTL extracted any information it
22346 		 * needed above).
22347 		 */
22348 		if (ipsec_len == 0) {
22349 			freeb(first_mp);
22350 			first_mp = mp;
22351 		}
22352 	}
22353 
22354 	/*
22355 	 * Fast path for ip_wput_ire
22356 	 */
22357 
22358 	ipha = (ipha_t *)mp->b_rptr;
22359 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22360 	dst = ipha->ipha_dst;
22361 
22362 	/*
22363 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22364 	 * if the socket is a SOCK_RAW type. The transport checksum should
22365 	 * be provided in the pre-built packet, so we don't need to compute it.
22366 	 * Also, other application set flags, like DF, should not be altered.
22367 	 * Other transport MUST pass down zero.
22368 	 */
22369 	ip_hdr_included = ipha->ipha_ident;
22370 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22371 
22372 	if (CLASSD(dst)) {
22373 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22374 		    ntohl(dst),
22375 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22376 		    ntohl(ire->ire_addr)));
22377 	}
22378 
22379 /* Macros to extract header fields from data already in registers */
22380 #ifdef	_BIG_ENDIAN
22381 #define	V_HLEN	(v_hlen_tos_len >> 24)
22382 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22383 #define	PROTO	(ttl_protocol & 0xFF)
22384 #else
22385 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22386 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22387 #define	PROTO	(ttl_protocol >> 8)
22388 #endif
22389 
22390 	orig_src = src = ipha->ipha_src;
22391 	/* (The loop back to "another" is explained down below.) */
22392 another:;
22393 	/*
22394 	 * Assign an ident value for this packet.  We assign idents on
22395 	 * a per destination basis out of the IRE.  There could be
22396 	 * other threads targeting the same destination, so we have to
22397 	 * arrange for a atomic increment.  Note that we use a 32-bit
22398 	 * atomic add because it has better performance than its
22399 	 * 16-bit sibling.
22400 	 *
22401 	 * If running in cluster mode and if the source address
22402 	 * belongs to a replicated service then vector through
22403 	 * cl_inet_ipident vector to allocate ip identifier
22404 	 * NOTE: This is a contract private interface with the
22405 	 * clustering group.
22406 	 */
22407 	clusterwide = 0;
22408 	if (cl_inet_ipident) {
22409 		ASSERT(cl_inet_isclusterwide);
22410 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22411 
22412 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22413 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22414 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22415 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22416 			    (uint8_t *)(uintptr_t)dst, NULL);
22417 			clusterwide = 1;
22418 		}
22419 	}
22420 	if (!clusterwide) {
22421 		ipha->ipha_ident =
22422 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22423 	}
22424 
22425 #ifndef _BIG_ENDIAN
22426 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22427 #endif
22428 
22429 	/*
22430 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22431 	 * This is needed to obey conn_unspec_src when packets go through
22432 	 * ip_newroute + arp.
22433 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22434 	 */
22435 	if (src == INADDR_ANY && !unspec_src) {
22436 		/*
22437 		 * Assign the appropriate source address from the IRE if none
22438 		 * was specified.
22439 		 */
22440 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22441 
22442 		src = ire->ire_src_addr;
22443 		if (connp == NULL) {
22444 			ip1dbg(("ip_wput_ire: no connp and no src "
22445 			    "address for dst 0x%x, using src 0x%x\n",
22446 			    ntohl(dst),
22447 			    ntohl(src)));
22448 		}
22449 		ipha->ipha_src = src;
22450 	}
22451 	stq = ire->ire_stq;
22452 
22453 	/*
22454 	 * We only allow ire chains for broadcasts since there will
22455 	 * be multiple IRE_CACHE entries for the same multicast
22456 	 * address (one per ipif).
22457 	 */
22458 	next_mp = NULL;
22459 
22460 	/* broadcast packet */
22461 	if (ire->ire_type == IRE_BROADCAST)
22462 		goto broadcast;
22463 
22464 	/* loopback ? */
22465 	if (stq == NULL)
22466 		goto nullstq;
22467 
22468 	/* The ill_index for outbound ILL */
22469 	ill_index = Q_TO_INDEX(stq);
22470 
22471 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22472 	ttl_protocol = ((uint16_t *)ipha)[4];
22473 
22474 	/* pseudo checksum (do it in parts for IP header checksum) */
22475 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22476 
22477 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22478 		queue_t *dev_q = stq->q_next;
22479 
22480 		/*
22481 		 * For DIRECT_CAPABLE, we do flow control at
22482 		 * the time of sending the packet. See
22483 		 * ILL_SEND_TX().
22484 		 */
22485 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22486 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22487 			goto blocked;
22488 
22489 		if ((PROTO == IPPROTO_UDP) &&
22490 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22491 			hlen = (V_HLEN & 0xF) << 2;
22492 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22493 			if (*up != 0) {
22494 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22495 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22496 				/* Software checksum? */
22497 				if (DB_CKSUMFLAGS(mp) == 0) {
22498 					IP_STAT(ipst, ip_out_sw_cksum);
22499 					IP_STAT_UPDATE(ipst,
22500 					    ip_udp_out_sw_cksum_bytes,
22501 					    LENGTH - hlen);
22502 				}
22503 			}
22504 		}
22505 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22506 		hlen = (V_HLEN & 0xF) << 2;
22507 		if (PROTO == IPPROTO_TCP) {
22508 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22509 			/*
22510 			 * The packet header is processed once and for all, even
22511 			 * in the multirouting case. We disable hardware
22512 			 * checksum if the packet is multirouted, as it will be
22513 			 * replicated via several interfaces, and not all of
22514 			 * them may have this capability.
22515 			 */
22516 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22517 			    LENGTH, max_frag, ipsec_len, cksum);
22518 			/* Software checksum? */
22519 			if (DB_CKSUMFLAGS(mp) == 0) {
22520 				IP_STAT(ipst, ip_out_sw_cksum);
22521 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22522 				    LENGTH - hlen);
22523 			}
22524 		} else {
22525 			sctp_hdr_t	*sctph;
22526 
22527 			ASSERT(PROTO == IPPROTO_SCTP);
22528 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22529 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22530 			/*
22531 			 * Zero out the checksum field to ensure proper
22532 			 * checksum calculation.
22533 			 */
22534 			sctph->sh_chksum = 0;
22535 #ifdef	DEBUG
22536 			if (!skip_sctp_cksum)
22537 #endif
22538 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22539 		}
22540 	}
22541 
22542 	/*
22543 	 * If this is a multicast packet and originated from ip_wput
22544 	 * we need to do loopback and forwarding checks. If it comes
22545 	 * from ip_wput_multicast, we SHOULD not do this.
22546 	 */
22547 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22548 
22549 	/* checksum */
22550 	cksum += ttl_protocol;
22551 
22552 	/* fragment the packet */
22553 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22554 		goto fragmentit;
22555 	/*
22556 	 * Don't use frag_flag if packet is pre-built or source
22557 	 * routed or if multicast (since multicast packets do
22558 	 * not solicit ICMP "packet too big" messages).
22559 	 */
22560 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22561 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22562 	    !ip_source_route_included(ipha)) &&
22563 	    !CLASSD(ipha->ipha_dst))
22564 		ipha->ipha_fragment_offset_and_flags |=
22565 		    htons(ire->ire_frag_flag);
22566 
22567 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22568 		/* calculate IP header checksum */
22569 		cksum += ipha->ipha_ident;
22570 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22571 		cksum += ipha->ipha_fragment_offset_and_flags;
22572 
22573 		/* IP options present */
22574 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22575 		if (hlen)
22576 			goto checksumoptions;
22577 
22578 		/* calculate hdr checksum */
22579 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22580 		cksum = ~(cksum + (cksum >> 16));
22581 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22582 	}
22583 	if (ipsec_len != 0) {
22584 		/*
22585 		 * We will do the rest of the processing after
22586 		 * we come back from IPsec in ip_wput_ipsec_out().
22587 		 */
22588 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22589 
22590 		io = (ipsec_out_t *)first_mp->b_rptr;
22591 		io->ipsec_out_ill_index =
22592 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22593 		ipsec_out_process(q, first_mp, ire, 0);
22594 		ire_refrele(ire);
22595 		if (conn_outgoing_ill != NULL)
22596 			ill_refrele(conn_outgoing_ill);
22597 		return;
22598 	}
22599 
22600 	/*
22601 	 * In most cases, the emission loop below is entered only
22602 	 * once. Only in the case where the ire holds the
22603 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22604 	 * flagged ires in the bucket, and send the packet
22605 	 * through all crossed RTF_MULTIRT routes.
22606 	 */
22607 	if (ire->ire_flags & RTF_MULTIRT) {
22608 		multirt_send = B_TRUE;
22609 	}
22610 	do {
22611 		if (multirt_send) {
22612 			irb_t *irb;
22613 			/*
22614 			 * We are in a multiple send case, need to get
22615 			 * the next ire and make a duplicate of the packet.
22616 			 * ire1 holds here the next ire to process in the
22617 			 * bucket. If multirouting is expected,
22618 			 * any non-RTF_MULTIRT ire that has the
22619 			 * right destination address is ignored.
22620 			 */
22621 			irb = ire->ire_bucket;
22622 			ASSERT(irb != NULL);
22623 
22624 			IRB_REFHOLD(irb);
22625 			for (ire1 = ire->ire_next;
22626 			    ire1 != NULL;
22627 			    ire1 = ire1->ire_next) {
22628 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22629 					continue;
22630 				if (ire1->ire_addr != ire->ire_addr)
22631 					continue;
22632 				if (ire1->ire_marks &
22633 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22634 					continue;
22635 
22636 				/* Got one */
22637 				IRE_REFHOLD(ire1);
22638 				break;
22639 			}
22640 			IRB_REFRELE(irb);
22641 
22642 			if (ire1 != NULL) {
22643 				next_mp = copyb(mp);
22644 				if ((next_mp == NULL) ||
22645 				    ((mp->b_cont != NULL) &&
22646 				    ((next_mp->b_cont =
22647 				    dupmsg(mp->b_cont)) == NULL))) {
22648 					freemsg(next_mp);
22649 					next_mp = NULL;
22650 					ire_refrele(ire1);
22651 					ire1 = NULL;
22652 				}
22653 			}
22654 
22655 			/* Last multiroute ire; don't loop anymore. */
22656 			if (ire1 == NULL) {
22657 				multirt_send = B_FALSE;
22658 			}
22659 		}
22660 
22661 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22662 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22663 		    mblk_t *, mp);
22664 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22665 		    ipst->ips_ipv4firewall_physical_out,
22666 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22667 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22668 
22669 		if (mp == NULL)
22670 			goto release_ire_and_ill;
22671 
22672 		if (ipst->ips_ipobs_enabled) {
22673 			zoneid_t szone;
22674 
22675 			/*
22676 			 * On the outbound path the destination zone will be
22677 			 * unknown as we're sending this packet out on the
22678 			 * wire.
22679 			 */
22680 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22681 			    ALL_ZONES);
22682 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22683 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22684 		}
22685 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22686 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22687 
22688 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22689 
22690 		if ((pktxmit_state == SEND_FAILED) ||
22691 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22692 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22693 			    "- packet dropped\n"));
22694 release_ire_and_ill:
22695 			ire_refrele(ire);
22696 			if (next_mp != NULL) {
22697 				freemsg(next_mp);
22698 				ire_refrele(ire1);
22699 			}
22700 			if (conn_outgoing_ill != NULL)
22701 				ill_refrele(conn_outgoing_ill);
22702 			return;
22703 		}
22704 
22705 		if (CLASSD(dst)) {
22706 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22707 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22708 			    LENGTH);
22709 		}
22710 
22711 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22712 		    "ip_wput_ire_end: q %p (%S)",
22713 		    q, "last copy out");
22714 		IRE_REFRELE(ire);
22715 
22716 		if (multirt_send) {
22717 			ASSERT(ire1);
22718 			/*
22719 			 * Proceed with the next RTF_MULTIRT ire,
22720 			 * Also set up the send-to queue accordingly.
22721 			 */
22722 			ire = ire1;
22723 			ire1 = NULL;
22724 			stq = ire->ire_stq;
22725 			mp = next_mp;
22726 			next_mp = NULL;
22727 			ipha = (ipha_t *)mp->b_rptr;
22728 			ill_index = Q_TO_INDEX(stq);
22729 			ill = (ill_t *)stq->q_ptr;
22730 		}
22731 	} while (multirt_send);
22732 	if (conn_outgoing_ill != NULL)
22733 		ill_refrele(conn_outgoing_ill);
22734 	return;
22735 
22736 	/*
22737 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22738 	 */
22739 broadcast:
22740 	{
22741 		/*
22742 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22743 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22744 		 * can be overridden stack-wide through the ip_broadcast_ttl
22745 		 * ndd tunable, or on a per-connection basis through the
22746 		 * IP_BROADCAST_TTL socket option.
22747 		 *
22748 		 * In the event that we are replying to incoming ICMP packets,
22749 		 * connp could be NULL.
22750 		 */
22751 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22752 		if (connp != NULL) {
22753 			if (connp->conn_dontroute)
22754 				ipha->ipha_ttl = 1;
22755 			else if (connp->conn_broadcast_ttl != 0)
22756 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22757 		}
22758 
22759 		/*
22760 		 * Note that we are not doing a IRB_REFHOLD here.
22761 		 * Actually we don't care if the list changes i.e
22762 		 * if somebody deletes an IRE from the list while
22763 		 * we drop the lock, the next time we come around
22764 		 * ire_next will be NULL and hence we won't send
22765 		 * out multiple copies which is fine.
22766 		 */
22767 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22768 		ire1 = ire->ire_next;
22769 		if (conn_outgoing_ill != NULL) {
22770 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22771 				ASSERT(ire1 == ire->ire_next);
22772 				if (ire1 != NULL && ire1->ire_addr == dst) {
22773 					ire_refrele(ire);
22774 					ire = ire1;
22775 					IRE_REFHOLD(ire);
22776 					ire1 = ire->ire_next;
22777 					continue;
22778 				}
22779 				rw_exit(&ire->ire_bucket->irb_lock);
22780 				/* Did not find a matching ill */
22781 				ip1dbg(("ip_wput_ire: broadcast with no "
22782 				    "matching IP_BOUND_IF ill %s dst %x\n",
22783 				    conn_outgoing_ill->ill_name, dst));
22784 				freemsg(first_mp);
22785 				if (ire != NULL)
22786 					ire_refrele(ire);
22787 				ill_refrele(conn_outgoing_ill);
22788 				return;
22789 			}
22790 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22791 			/*
22792 			 * If the next IRE has the same address and is not one
22793 			 * of the two copies that we need to send, try to see
22794 			 * whether this copy should be sent at all. This
22795 			 * assumes that we insert loopbacks first and then
22796 			 * non-loopbacks. This is acheived by inserting the
22797 			 * loopback always before non-loopback.
22798 			 * This is used to send a single copy of a broadcast
22799 			 * packet out all physical interfaces that have an
22800 			 * matching IRE_BROADCAST while also looping
22801 			 * back one copy (to ip_wput_local) for each
22802 			 * matching physical interface. However, we avoid
22803 			 * sending packets out different logical that match by
22804 			 * having ipif_up/ipif_down supress duplicate
22805 			 * IRE_BROADCASTS.
22806 			 *
22807 			 * This feature is currently used to get broadcasts
22808 			 * sent to multiple interfaces, when the broadcast
22809 			 * address being used applies to multiple interfaces.
22810 			 * For example, a whole net broadcast will be
22811 			 * replicated on every connected subnet of
22812 			 * the target net.
22813 			 *
22814 			 * Each zone has its own set of IRE_BROADCASTs, so that
22815 			 * we're able to distribute inbound packets to multiple
22816 			 * zones who share a broadcast address. We avoid looping
22817 			 * back outbound packets in different zones but on the
22818 			 * same ill, as the application would see duplicates.
22819 			 *
22820 			 * This logic assumes that ire_add_v4() groups the
22821 			 * IRE_BROADCAST entries so that those with the same
22822 			 * ire_addr are kept together.
22823 			 */
22824 			ire_ill = ire->ire_ipif->ipif_ill;
22825 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22826 				while (ire1 != NULL && ire1->ire_addr == dst) {
22827 					ire1_ill = ire1->ire_ipif->ipif_ill;
22828 					if (ire1_ill != ire_ill)
22829 						break;
22830 					ire1 = ire1->ire_next;
22831 				}
22832 			}
22833 		}
22834 		ASSERT(multirt_send == B_FALSE);
22835 		if (ire1 != NULL && ire1->ire_addr == dst) {
22836 			if ((ire->ire_flags & RTF_MULTIRT) &&
22837 			    (ire1->ire_flags & RTF_MULTIRT)) {
22838 				/*
22839 				 * We are in the multirouting case.
22840 				 * The message must be sent at least
22841 				 * on both ires. These ires have been
22842 				 * inserted AFTER the standard ones
22843 				 * in ip_rt_add(). There are thus no
22844 				 * other ire entries for the destination
22845 				 * address in the rest of the bucket
22846 				 * that do not have the RTF_MULTIRT
22847 				 * flag. We don't process a copy
22848 				 * of the message here. This will be
22849 				 * done in the final sending loop.
22850 				 */
22851 				multirt_send = B_TRUE;
22852 			} else {
22853 				next_mp = ip_copymsg(first_mp);
22854 				if (next_mp != NULL)
22855 					IRE_REFHOLD(ire1);
22856 			}
22857 		}
22858 		rw_exit(&ire->ire_bucket->irb_lock);
22859 	}
22860 
22861 	if (stq) {
22862 		/*
22863 		 * A non-NULL send-to queue means this packet is going
22864 		 * out of this machine.
22865 		 */
22866 		out_ill = (ill_t *)stq->q_ptr;
22867 
22868 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22869 		ttl_protocol = ((uint16_t *)ipha)[4];
22870 		/*
22871 		 * We accumulate the pseudo header checksum in cksum.
22872 		 * This is pretty hairy code, so watch close.  One
22873 		 * thing to keep in mind is that UDP and TCP have
22874 		 * stored their respective datagram lengths in their
22875 		 * checksum fields.  This lines things up real nice.
22876 		 */
22877 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22878 		    (src >> 16) + (src & 0xFFFF);
22879 		/*
22880 		 * We assume the udp checksum field contains the
22881 		 * length, so to compute the pseudo header checksum,
22882 		 * all we need is the protocol number and src/dst.
22883 		 */
22884 		/* Provide the checksums for UDP and TCP. */
22885 		if ((PROTO == IPPROTO_TCP) &&
22886 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22887 			/* hlen gets the number of uchar_ts in the IP header */
22888 			hlen = (V_HLEN & 0xF) << 2;
22889 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22890 			IP_STAT(ipst, ip_out_sw_cksum);
22891 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22892 			    LENGTH - hlen);
22893 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22894 		} else if (PROTO == IPPROTO_SCTP &&
22895 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22896 			sctp_hdr_t	*sctph;
22897 
22898 			hlen = (V_HLEN & 0xF) << 2;
22899 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22900 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22901 			sctph->sh_chksum = 0;
22902 #ifdef	DEBUG
22903 			if (!skip_sctp_cksum)
22904 #endif
22905 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22906 		} else {
22907 			queue_t	*dev_q = stq->q_next;
22908 
22909 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22910 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22911 blocked:
22912 				ipha->ipha_ident = ip_hdr_included;
22913 				/*
22914 				 * If we don't have a conn to apply
22915 				 * backpressure, free the message.
22916 				 * In the ire_send path, we don't know
22917 				 * the position to requeue the packet. Rather
22918 				 * than reorder packets, we just drop this
22919 				 * packet.
22920 				 */
22921 				if (ipst->ips_ip_output_queue &&
22922 				    connp != NULL &&
22923 				    caller != IRE_SEND) {
22924 					if (caller == IP_WSRV) {
22925 						idl_tx_list_t *idl_txl;
22926 
22927 						idl_txl =
22928 						    &ipst->ips_idl_tx_list[0];
22929 						connp->conn_did_putbq = 1;
22930 						(void) putbq(connp->conn_wq,
22931 						    first_mp);
22932 						conn_drain_insert(connp,
22933 						    idl_txl);
22934 						/*
22935 						 * This is the service thread,
22936 						 * and the queue is already
22937 						 * noenabled. The check for
22938 						 * canput and the putbq is not
22939 						 * atomic. So we need to check
22940 						 * again.
22941 						 */
22942 						if (canput(stq->q_next))
22943 							connp->conn_did_putbq
22944 							    = 0;
22945 						IP_STAT(ipst, ip_conn_flputbq);
22946 					} else {
22947 						/*
22948 						 * We are not the service proc.
22949 						 * ip_wsrv will be scheduled or
22950 						 * is already running.
22951 						 */
22952 
22953 						(void) putq(connp->conn_wq,
22954 						    first_mp);
22955 					}
22956 				} else {
22957 					out_ill = (ill_t *)stq->q_ptr;
22958 					BUMP_MIB(out_ill->ill_ip_mib,
22959 					    ipIfStatsOutDiscards);
22960 					freemsg(first_mp);
22961 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22962 					    "ip_wput_ire_end: q %p (%S)",
22963 					    q, "discard");
22964 				}
22965 				ire_refrele(ire);
22966 				if (next_mp) {
22967 					ire_refrele(ire1);
22968 					freemsg(next_mp);
22969 				}
22970 				if (conn_outgoing_ill != NULL)
22971 					ill_refrele(conn_outgoing_ill);
22972 				return;
22973 			}
22974 			if ((PROTO == IPPROTO_UDP) &&
22975 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22976 				/*
22977 				 * hlen gets the number of uchar_ts in the
22978 				 * IP header
22979 				 */
22980 				hlen = (V_HLEN & 0xF) << 2;
22981 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22982 				max_frag = ire->ire_max_frag;
22983 				if (*up != 0) {
22984 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22985 					    up, PROTO, hlen, LENGTH, max_frag,
22986 					    ipsec_len, cksum);
22987 					/* Software checksum? */
22988 					if (DB_CKSUMFLAGS(mp) == 0) {
22989 						IP_STAT(ipst, ip_out_sw_cksum);
22990 						IP_STAT_UPDATE(ipst,
22991 						    ip_udp_out_sw_cksum_bytes,
22992 						    LENGTH - hlen);
22993 					}
22994 				}
22995 			}
22996 		}
22997 		/*
22998 		 * Need to do this even when fragmenting. The local
22999 		 * loopback can be done without computing checksums
23000 		 * but forwarding out other interface must be done
23001 		 * after the IP checksum (and ULP checksums) have been
23002 		 * computed.
23003 		 *
23004 		 * NOTE : multicast_forward is set only if this packet
23005 		 * originated from ip_wput. For packets originating from
23006 		 * ip_wput_multicast, it is not set.
23007 		 */
23008 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23009 multi_loopback:
23010 			ip2dbg(("ip_wput: multicast, loop %d\n",
23011 			    conn_multicast_loop));
23012 
23013 			/*  Forget header checksum offload */
23014 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23015 
23016 			/*
23017 			 * Local loopback of multicasts?  Check the
23018 			 * ill.
23019 			 *
23020 			 * Note that the loopback function will not come
23021 			 * in through ip_rput - it will only do the
23022 			 * client fanout thus we need to do an mforward
23023 			 * as well.  The is different from the BSD
23024 			 * logic.
23025 			 */
23026 			if (ill != NULL) {
23027 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
23028 				    ALL_ZONES) != NULL) {
23029 					/*
23030 					 * Pass along the virtual output q.
23031 					 * ip_wput_local() will distribute the
23032 					 * packet to all the matching zones,
23033 					 * except the sending zone when
23034 					 * IP_MULTICAST_LOOP is false.
23035 					 */
23036 					ip_multicast_loopback(q, ill, first_mp,
23037 					    conn_multicast_loop ? 0 :
23038 					    IP_FF_NO_MCAST_LOOP, zoneid);
23039 				}
23040 			}
23041 			if (ipha->ipha_ttl == 0) {
23042 				/*
23043 				 * 0 => only to this host i.e. we are
23044 				 * done. We are also done if this was the
23045 				 * loopback interface since it is sufficient
23046 				 * to loopback one copy of a multicast packet.
23047 				 */
23048 				freemsg(first_mp);
23049 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23050 				    "ip_wput_ire_end: q %p (%S)",
23051 				    q, "loopback");
23052 				ire_refrele(ire);
23053 				if (conn_outgoing_ill != NULL)
23054 					ill_refrele(conn_outgoing_ill);
23055 				return;
23056 			}
23057 			/*
23058 			 * ILLF_MULTICAST is checked in ip_newroute
23059 			 * i.e. we don't need to check it here since
23060 			 * all IRE_CACHEs come from ip_newroute.
23061 			 * For multicast traffic, SO_DONTROUTE is interpreted
23062 			 * to mean only send the packet out the interface
23063 			 * (optionally specified with IP_MULTICAST_IF)
23064 			 * and do not forward it out additional interfaces.
23065 			 * RSVP and the rsvp daemon is an example of a
23066 			 * protocol and user level process that
23067 			 * handles it's own routing. Hence, it uses the
23068 			 * SO_DONTROUTE option to accomplish this.
23069 			 */
23070 
23071 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23072 			    ill != NULL) {
23073 				/* Unconditionally redo the checksum */
23074 				ipha->ipha_hdr_checksum = 0;
23075 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23076 
23077 				/*
23078 				 * If this needs to go out secure, we need
23079 				 * to wait till we finish the IPsec
23080 				 * processing.
23081 				 */
23082 				if (ipsec_len == 0 &&
23083 				    ip_mforward(ill, ipha, mp)) {
23084 					freemsg(first_mp);
23085 					ip1dbg(("ip_wput: mforward failed\n"));
23086 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23087 					    "ip_wput_ire_end: q %p (%S)",
23088 					    q, "mforward failed");
23089 					ire_refrele(ire);
23090 					if (conn_outgoing_ill != NULL)
23091 						ill_refrele(conn_outgoing_ill);
23092 					return;
23093 				}
23094 			}
23095 		}
23096 		max_frag = ire->ire_max_frag;
23097 		cksum += ttl_protocol;
23098 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23099 			/* No fragmentation required for this one. */
23100 			/*
23101 			 * Don't use frag_flag if packet is pre-built or source
23102 			 * routed or if multicast (since multicast packets do
23103 			 * not solicit ICMP "packet too big" messages).
23104 			 */
23105 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23106 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23107 			    !ip_source_route_included(ipha)) &&
23108 			    !CLASSD(ipha->ipha_dst))
23109 				ipha->ipha_fragment_offset_and_flags |=
23110 				    htons(ire->ire_frag_flag);
23111 
23112 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23113 				/* Complete the IP header checksum. */
23114 				cksum += ipha->ipha_ident;
23115 				cksum += (v_hlen_tos_len >> 16)+
23116 				    (v_hlen_tos_len & 0xFFFF);
23117 				cksum += ipha->ipha_fragment_offset_and_flags;
23118 				hlen = (V_HLEN & 0xF) -
23119 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23120 				if (hlen) {
23121 checksumoptions:
23122 					/*
23123 					 * Account for the IP Options in the IP
23124 					 * header checksum.
23125 					 */
23126 					up = (uint16_t *)(rptr+
23127 					    IP_SIMPLE_HDR_LENGTH);
23128 					do {
23129 						cksum += up[0];
23130 						cksum += up[1];
23131 						up += 2;
23132 					} while (--hlen);
23133 				}
23134 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23135 				cksum = ~(cksum + (cksum >> 16));
23136 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23137 			}
23138 			if (ipsec_len != 0) {
23139 				ipsec_out_process(q, first_mp, ire, ill_index);
23140 				if (!next_mp) {
23141 					ire_refrele(ire);
23142 					if (conn_outgoing_ill != NULL)
23143 						ill_refrele(conn_outgoing_ill);
23144 					return;
23145 				}
23146 				goto next;
23147 			}
23148 
23149 			/*
23150 			 * multirt_send has already been handled
23151 			 * for broadcast, but not yet for multicast
23152 			 * or IP options.
23153 			 */
23154 			if (next_mp == NULL) {
23155 				if (ire->ire_flags & RTF_MULTIRT) {
23156 					multirt_send = B_TRUE;
23157 				}
23158 			}
23159 
23160 			/*
23161 			 * In most cases, the emission loop below is
23162 			 * entered only once. Only in the case where
23163 			 * the ire holds the RTF_MULTIRT flag, do we loop
23164 			 * to process all RTF_MULTIRT ires in the bucket,
23165 			 * and send the packet through all crossed
23166 			 * RTF_MULTIRT routes.
23167 			 */
23168 			do {
23169 				if (multirt_send) {
23170 					irb_t *irb;
23171 
23172 					irb = ire->ire_bucket;
23173 					ASSERT(irb != NULL);
23174 					/*
23175 					 * We are in a multiple send case,
23176 					 * need to get the next IRE and make
23177 					 * a duplicate of the packet.
23178 					 */
23179 					IRB_REFHOLD(irb);
23180 					for (ire1 = ire->ire_next;
23181 					    ire1 != NULL;
23182 					    ire1 = ire1->ire_next) {
23183 						if (!(ire1->ire_flags &
23184 						    RTF_MULTIRT))
23185 							continue;
23186 
23187 						if (ire1->ire_addr !=
23188 						    ire->ire_addr)
23189 							continue;
23190 
23191 						if (ire1->ire_marks &
23192 						    (IRE_MARK_CONDEMNED |
23193 						    IRE_MARK_TESTHIDDEN))
23194 							continue;
23195 
23196 						/* Got one */
23197 						IRE_REFHOLD(ire1);
23198 						break;
23199 					}
23200 					IRB_REFRELE(irb);
23201 
23202 					if (ire1 != NULL) {
23203 						next_mp = copyb(mp);
23204 						if ((next_mp == NULL) ||
23205 						    ((mp->b_cont != NULL) &&
23206 						    ((next_mp->b_cont =
23207 						    dupmsg(mp->b_cont))
23208 						    == NULL))) {
23209 							freemsg(next_mp);
23210 							next_mp = NULL;
23211 							ire_refrele(ire1);
23212 							ire1 = NULL;
23213 						}
23214 					}
23215 
23216 					/*
23217 					 * Last multiroute ire; don't loop
23218 					 * anymore. The emission is over
23219 					 * and next_mp is NULL.
23220 					 */
23221 					if (ire1 == NULL) {
23222 						multirt_send = B_FALSE;
23223 					}
23224 				}
23225 
23226 				out_ill = ire_to_ill(ire);
23227 				DTRACE_PROBE4(ip4__physical__out__start,
23228 				    ill_t *, NULL,
23229 				    ill_t *, out_ill,
23230 				    ipha_t *, ipha, mblk_t *, mp);
23231 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23232 				    ipst->ips_ipv4firewall_physical_out,
23233 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23234 				DTRACE_PROBE1(ip4__physical__out__end,
23235 				    mblk_t *, mp);
23236 				if (mp == NULL)
23237 					goto release_ire_and_ill_2;
23238 
23239 				ASSERT(ipsec_len == 0);
23240 				mp->b_prev =
23241 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23242 				DTRACE_PROBE2(ip__xmit__2,
23243 				    mblk_t *, mp, ire_t *, ire);
23244 				pktxmit_state = ip_xmit_v4(mp, ire,
23245 				    NULL, B_TRUE, connp);
23246 				if ((pktxmit_state == SEND_FAILED) ||
23247 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23248 release_ire_and_ill_2:
23249 					if (next_mp) {
23250 						freemsg(next_mp);
23251 						ire_refrele(ire1);
23252 					}
23253 					ire_refrele(ire);
23254 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23255 					    "ip_wput_ire_end: q %p (%S)",
23256 					    q, "discard MDATA");
23257 					if (conn_outgoing_ill != NULL)
23258 						ill_refrele(conn_outgoing_ill);
23259 					return;
23260 				}
23261 
23262 				if (CLASSD(dst)) {
23263 					BUMP_MIB(out_ill->ill_ip_mib,
23264 					    ipIfStatsHCOutMcastPkts);
23265 					UPDATE_MIB(out_ill->ill_ip_mib,
23266 					    ipIfStatsHCOutMcastOctets,
23267 					    LENGTH);
23268 				} else if (ire->ire_type == IRE_BROADCAST) {
23269 					BUMP_MIB(out_ill->ill_ip_mib,
23270 					    ipIfStatsHCOutBcastPkts);
23271 				}
23272 
23273 				if (multirt_send) {
23274 					/*
23275 					 * We are in a multiple send case,
23276 					 * need to re-enter the sending loop
23277 					 * using the next ire.
23278 					 */
23279 					ire_refrele(ire);
23280 					ire = ire1;
23281 					stq = ire->ire_stq;
23282 					mp = next_mp;
23283 					next_mp = NULL;
23284 					ipha = (ipha_t *)mp->b_rptr;
23285 					ill_index = Q_TO_INDEX(stq);
23286 				}
23287 			} while (multirt_send);
23288 
23289 			if (!next_mp) {
23290 				/*
23291 				 * Last copy going out (the ultra-common
23292 				 * case).  Note that we intentionally replicate
23293 				 * the putnext rather than calling it before
23294 				 * the next_mp check in hopes of a little
23295 				 * tail-call action out of the compiler.
23296 				 */
23297 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23298 				    "ip_wput_ire_end: q %p (%S)",
23299 				    q, "last copy out(1)");
23300 				ire_refrele(ire);
23301 				if (conn_outgoing_ill != NULL)
23302 					ill_refrele(conn_outgoing_ill);
23303 				return;
23304 			}
23305 			/* More copies going out below. */
23306 		} else {
23307 			int offset;
23308 fragmentit:
23309 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23310 			/*
23311 			 * If this would generate a icmp_frag_needed message,
23312 			 * we need to handle it before we do the IPsec
23313 			 * processing. Otherwise, we need to strip the IPsec
23314 			 * headers before we send up the message to the ULPs
23315 			 * which becomes messy and difficult.
23316 			 */
23317 			if (ipsec_len != 0) {
23318 				if ((max_frag < (unsigned int)(LENGTH +
23319 				    ipsec_len)) && (offset & IPH_DF)) {
23320 					out_ill = (ill_t *)stq->q_ptr;
23321 					BUMP_MIB(out_ill->ill_ip_mib,
23322 					    ipIfStatsOutFragFails);
23323 					BUMP_MIB(out_ill->ill_ip_mib,
23324 					    ipIfStatsOutFragReqds);
23325 					ipha->ipha_hdr_checksum = 0;
23326 					ipha->ipha_hdr_checksum =
23327 					    (uint16_t)ip_csum_hdr(ipha);
23328 					icmp_frag_needed(ire->ire_stq, first_mp,
23329 					    max_frag, zoneid, ipst);
23330 					if (!next_mp) {
23331 						ire_refrele(ire);
23332 						if (conn_outgoing_ill != NULL) {
23333 							ill_refrele(
23334 							    conn_outgoing_ill);
23335 						}
23336 						return;
23337 					}
23338 				} else {
23339 					/*
23340 					 * This won't cause a icmp_frag_needed
23341 					 * message. to be generated. Send it on
23342 					 * the wire. Note that this could still
23343 					 * cause fragmentation and all we
23344 					 * do is the generation of the message
23345 					 * to the ULP if needed before IPsec.
23346 					 */
23347 					if (!next_mp) {
23348 						ipsec_out_process(q, first_mp,
23349 						    ire, ill_index);
23350 						TRACE_2(TR_FAC_IP,
23351 						    TR_IP_WPUT_IRE_END,
23352 						    "ip_wput_ire_end: q %p "
23353 						    "(%S)", q,
23354 						    "last ipsec_out_process");
23355 						ire_refrele(ire);
23356 						if (conn_outgoing_ill != NULL) {
23357 							ill_refrele(
23358 							    conn_outgoing_ill);
23359 						}
23360 						return;
23361 					}
23362 					ipsec_out_process(q, first_mp,
23363 					    ire, ill_index);
23364 				}
23365 			} else {
23366 				/*
23367 				 * Initiate IPPF processing. For
23368 				 * fragmentable packets we finish
23369 				 * all QOS packet processing before
23370 				 * calling:
23371 				 * ip_wput_ire_fragmentit->ip_wput_frag
23372 				 */
23373 
23374 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23375 					ip_process(IPP_LOCAL_OUT, &mp,
23376 					    ill_index);
23377 					if (mp == NULL) {
23378 						out_ill = (ill_t *)stq->q_ptr;
23379 						BUMP_MIB(out_ill->ill_ip_mib,
23380 						    ipIfStatsOutDiscards);
23381 						if (next_mp != NULL) {
23382 							freemsg(next_mp);
23383 							ire_refrele(ire1);
23384 						}
23385 						ire_refrele(ire);
23386 						TRACE_2(TR_FAC_IP,
23387 						    TR_IP_WPUT_IRE_END,
23388 						    "ip_wput_ire: q %p (%S)",
23389 						    q, "discard MDATA");
23390 						if (conn_outgoing_ill != NULL) {
23391 							ill_refrele(
23392 							    conn_outgoing_ill);
23393 						}
23394 						return;
23395 					}
23396 				}
23397 				if (!next_mp) {
23398 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23399 					    "ip_wput_ire_end: q %p (%S)",
23400 					    q, "last fragmentation");
23401 					ip_wput_ire_fragmentit(mp, ire,
23402 					    zoneid, ipst, connp);
23403 					ire_refrele(ire);
23404 					if (conn_outgoing_ill != NULL)
23405 						ill_refrele(conn_outgoing_ill);
23406 					return;
23407 				}
23408 				ip_wput_ire_fragmentit(mp, ire,
23409 				    zoneid, ipst, connp);
23410 			}
23411 		}
23412 	} else {
23413 nullstq:
23414 		/* A NULL stq means the destination address is local. */
23415 		UPDATE_OB_PKT_COUNT(ire);
23416 		ire->ire_last_used_time = lbolt;
23417 		ASSERT(ire->ire_ipif != NULL);
23418 		if (!next_mp) {
23419 			/*
23420 			 * Is there an "in" and "out" for traffic local
23421 			 * to a host (loopback)?  The code in Solaris doesn't
23422 			 * explicitly draw a line in its code for in vs out,
23423 			 * so we've had to draw a line in the sand: ip_wput_ire
23424 			 * is considered to be the "output" side and
23425 			 * ip_wput_local to be the "input" side.
23426 			 */
23427 			out_ill = ire_to_ill(ire);
23428 
23429 			/*
23430 			 * DTrace this as ip:::send.  A blocked packet will
23431 			 * fire the send probe, but not the receive probe.
23432 			 */
23433 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23434 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23435 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23436 
23437 			DTRACE_PROBE4(ip4__loopback__out__start,
23438 			    ill_t *, NULL, ill_t *, out_ill,
23439 			    ipha_t *, ipha, mblk_t *, first_mp);
23440 
23441 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23442 			    ipst->ips_ipv4firewall_loopback_out,
23443 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23444 
23445 			DTRACE_PROBE1(ip4__loopback__out_end,
23446 			    mblk_t *, first_mp);
23447 
23448 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23449 			    "ip_wput_ire_end: q %p (%S)",
23450 			    q, "local address");
23451 
23452 			if (first_mp != NULL)
23453 				ip_wput_local(q, out_ill, ipha,
23454 				    first_mp, ire, 0, ire->ire_zoneid);
23455 			ire_refrele(ire);
23456 			if (conn_outgoing_ill != NULL)
23457 				ill_refrele(conn_outgoing_ill);
23458 			return;
23459 		}
23460 
23461 		out_ill = ire_to_ill(ire);
23462 
23463 		/*
23464 		 * DTrace this as ip:::send.  A blocked packet will fire the
23465 		 * send probe, but not the receive probe.
23466 		 */
23467 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23468 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23469 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23470 
23471 		DTRACE_PROBE4(ip4__loopback__out__start,
23472 		    ill_t *, NULL, ill_t *, out_ill,
23473 		    ipha_t *, ipha, mblk_t *, first_mp);
23474 
23475 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23476 		    ipst->ips_ipv4firewall_loopback_out,
23477 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23478 
23479 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23480 
23481 		if (first_mp != NULL)
23482 			ip_wput_local(q, out_ill, ipha,
23483 			    first_mp, ire, 0, ire->ire_zoneid);
23484 	}
23485 next:
23486 	/*
23487 	 * More copies going out to additional interfaces.
23488 	 * ire1 has already been held. We don't need the
23489 	 * "ire" anymore.
23490 	 */
23491 	ire_refrele(ire);
23492 	ire = ire1;
23493 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23494 	mp = next_mp;
23495 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23496 	ill = ire_to_ill(ire);
23497 	first_mp = mp;
23498 	if (ipsec_len != 0) {
23499 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23500 		mp = mp->b_cont;
23501 	}
23502 	dst = ire->ire_addr;
23503 	ipha = (ipha_t *)mp->b_rptr;
23504 	/*
23505 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23506 	 * Restore ipha_ident "no checksum" flag.
23507 	 */
23508 	src = orig_src;
23509 	ipha->ipha_ident = ip_hdr_included;
23510 	goto another;
23511 
23512 #undef	rptr
23513 #undef	Q_TO_INDEX
23514 }
23515 
23516 /*
23517  * Routine to allocate a message that is used to notify the ULP about MDT.
23518  * The caller may provide a pointer to the link-layer MDT capabilities,
23519  * or NULL if MDT is to be disabled on the stream.
23520  */
23521 mblk_t *
23522 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23523 {
23524 	mblk_t *mp;
23525 	ip_mdt_info_t *mdti;
23526 	ill_mdt_capab_t *idst;
23527 
23528 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23529 		DB_TYPE(mp) = M_CTL;
23530 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23531 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23532 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23533 		idst = &(mdti->mdt_capab);
23534 
23535 		/*
23536 		 * If the caller provides us with the capability, copy
23537 		 * it over into our notification message; otherwise
23538 		 * we zero out the capability portion.
23539 		 */
23540 		if (isrc != NULL)
23541 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23542 		else
23543 			bzero((caddr_t)idst, sizeof (*idst));
23544 	}
23545 	return (mp);
23546 }
23547 
23548 /*
23549  * Routine which determines whether MDT can be enabled on the destination
23550  * IRE and IPC combination, and if so, allocates and returns the MDT
23551  * notification mblk that may be used by ULP.  We also check if we need to
23552  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23553  * MDT usage in the past have been lifted.  This gets called during IP
23554  * and ULP binding.
23555  */
23556 mblk_t *
23557 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23558     ill_mdt_capab_t *mdt_cap)
23559 {
23560 	mblk_t *mp;
23561 	boolean_t rc = B_FALSE;
23562 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23563 
23564 	ASSERT(dst_ire != NULL);
23565 	ASSERT(connp != NULL);
23566 	ASSERT(mdt_cap != NULL);
23567 
23568 	/*
23569 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23570 	 * Multidata, which is handled in tcp_multisend().  This
23571 	 * is the reason why we do all these checks here, to ensure
23572 	 * that we don't enable Multidata for the cases which we
23573 	 * can't handle at the moment.
23574 	 */
23575 	do {
23576 		/* Only do TCP at the moment */
23577 		if (connp->conn_ulp != IPPROTO_TCP)
23578 			break;
23579 
23580 		/*
23581 		 * IPsec outbound policy present?  Note that we get here
23582 		 * after calling ipsec_conn_cache_policy() where the global
23583 		 * policy checking is performed.  conn_latch will be
23584 		 * non-NULL as long as there's a policy defined,
23585 		 * i.e. conn_out_enforce_policy may be NULL in such case
23586 		 * when the connection is non-secure, and hence we check
23587 		 * further if the latch refers to an outbound policy.
23588 		 */
23589 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23590 			break;
23591 
23592 		/* CGTP (multiroute) is enabled? */
23593 		if (dst_ire->ire_flags & RTF_MULTIRT)
23594 			break;
23595 
23596 		/* Outbound IPQoS enabled? */
23597 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23598 			/*
23599 			 * In this case, we disable MDT for this and all
23600 			 * future connections going over the interface.
23601 			 */
23602 			mdt_cap->ill_mdt_on = 0;
23603 			break;
23604 		}
23605 
23606 		/* socket option(s) present? */
23607 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23608 			break;
23609 
23610 		rc = B_TRUE;
23611 	/* CONSTCOND */
23612 	} while (0);
23613 
23614 	/* Remember the result */
23615 	connp->conn_mdt_ok = rc;
23616 
23617 	if (!rc)
23618 		return (NULL);
23619 	else if (!mdt_cap->ill_mdt_on) {
23620 		/*
23621 		 * If MDT has been previously turned off in the past, and we
23622 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23623 		 * then enable it for this interface.
23624 		 */
23625 		mdt_cap->ill_mdt_on = 1;
23626 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23627 		    "interface %s\n", ill_name));
23628 	}
23629 
23630 	/* Allocate the MDT info mblk */
23631 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23632 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23633 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23634 		return (NULL);
23635 	}
23636 	return (mp);
23637 }
23638 
23639 /*
23640  * Routine to allocate a message that is used to notify the ULP about LSO.
23641  * The caller may provide a pointer to the link-layer LSO capabilities,
23642  * or NULL if LSO is to be disabled on the stream.
23643  */
23644 mblk_t *
23645 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23646 {
23647 	mblk_t *mp;
23648 	ip_lso_info_t *lsoi;
23649 	ill_lso_capab_t *idst;
23650 
23651 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23652 		DB_TYPE(mp) = M_CTL;
23653 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23654 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23655 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23656 		idst = &(lsoi->lso_capab);
23657 
23658 		/*
23659 		 * If the caller provides us with the capability, copy
23660 		 * it over into our notification message; otherwise
23661 		 * we zero out the capability portion.
23662 		 */
23663 		if (isrc != NULL)
23664 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23665 		else
23666 			bzero((caddr_t)idst, sizeof (*idst));
23667 	}
23668 	return (mp);
23669 }
23670 
23671 /*
23672  * Routine which determines whether LSO can be enabled on the destination
23673  * IRE and IPC combination, and if so, allocates and returns the LSO
23674  * notification mblk that may be used by ULP.  We also check if we need to
23675  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23676  * LSO usage in the past have been lifted.  This gets called during IP
23677  * and ULP binding.
23678  */
23679 mblk_t *
23680 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23681     ill_lso_capab_t *lso_cap)
23682 {
23683 	mblk_t *mp;
23684 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23685 
23686 	ASSERT(dst_ire != NULL);
23687 	ASSERT(connp != NULL);
23688 	ASSERT(lso_cap != NULL);
23689 
23690 	connp->conn_lso_ok = B_TRUE;
23691 
23692 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23693 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23694 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23695 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23696 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23697 		connp->conn_lso_ok = B_FALSE;
23698 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23699 			/*
23700 			 * Disable LSO for this and all future connections going
23701 			 * over the interface.
23702 			 */
23703 			lso_cap->ill_lso_on = 0;
23704 		}
23705 	}
23706 
23707 	if (!connp->conn_lso_ok)
23708 		return (NULL);
23709 	else if (!lso_cap->ill_lso_on) {
23710 		/*
23711 		 * If LSO has been previously turned off in the past, and we
23712 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23713 		 * then enable it for this interface.
23714 		 */
23715 		lso_cap->ill_lso_on = 1;
23716 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23717 		    ill_name));
23718 	}
23719 
23720 	/* Allocate the LSO info mblk */
23721 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23722 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23723 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23724 
23725 	return (mp);
23726 }
23727 
23728 /*
23729  * Create destination address attribute, and fill it with the physical
23730  * destination address and SAP taken from the template DL_UNITDATA_REQ
23731  * message block.
23732  */
23733 boolean_t
23734 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23735 {
23736 	dl_unitdata_req_t *dlurp;
23737 	pattr_t *pa;
23738 	pattrinfo_t pa_info;
23739 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23740 	uint_t das_len, das_off;
23741 
23742 	ASSERT(dlmp != NULL);
23743 
23744 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23745 	das_len = dlurp->dl_dest_addr_length;
23746 	das_off = dlurp->dl_dest_addr_offset;
23747 
23748 	pa_info.type = PATTR_DSTADDRSAP;
23749 	pa_info.len = sizeof (**das) + das_len - 1;
23750 
23751 	/* create and associate the attribute */
23752 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23753 	if (pa != NULL) {
23754 		ASSERT(*das != NULL);
23755 		(*das)->addr_is_group = 0;
23756 		(*das)->addr_len = (uint8_t)das_len;
23757 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23758 	}
23759 
23760 	return (pa != NULL);
23761 }
23762 
23763 /*
23764  * Create hardware checksum attribute and fill it with the values passed.
23765  */
23766 boolean_t
23767 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23768     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23769 {
23770 	pattr_t *pa;
23771 	pattrinfo_t pa_info;
23772 
23773 	ASSERT(mmd != NULL);
23774 
23775 	pa_info.type = PATTR_HCKSUM;
23776 	pa_info.len = sizeof (pattr_hcksum_t);
23777 
23778 	/* create and associate the attribute */
23779 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23780 	if (pa != NULL) {
23781 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23782 
23783 		hck->hcksum_start_offset = start_offset;
23784 		hck->hcksum_stuff_offset = stuff_offset;
23785 		hck->hcksum_end_offset = end_offset;
23786 		hck->hcksum_flags = flags;
23787 	}
23788 	return (pa != NULL);
23789 }
23790 
23791 /*
23792  * Create zerocopy attribute and fill it with the specified flags
23793  */
23794 boolean_t
23795 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23796 {
23797 	pattr_t *pa;
23798 	pattrinfo_t pa_info;
23799 
23800 	ASSERT(mmd != NULL);
23801 	pa_info.type = PATTR_ZCOPY;
23802 	pa_info.len = sizeof (pattr_zcopy_t);
23803 
23804 	/* create and associate the attribute */
23805 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23806 	if (pa != NULL) {
23807 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23808 
23809 		zcopy->zcopy_flags = flags;
23810 	}
23811 	return (pa != NULL);
23812 }
23813 
23814 /*
23815  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23816  * block chain. We could rewrite to handle arbitrary message block chains but
23817  * that would make the code complicated and slow. Right now there three
23818  * restrictions:
23819  *
23820  *   1. The first message block must contain the complete IP header and
23821  *	at least 1 byte of payload data.
23822  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23823  *	so that we can use a single Multidata message.
23824  *   3. No frag must be distributed over two or more message blocks so
23825  *	that we don't need more than two packet descriptors per frag.
23826  *
23827  * The above restrictions allow us to support userland applications (which
23828  * will send down a single message block) and NFS over UDP (which will
23829  * send down a chain of at most three message blocks).
23830  *
23831  * We also don't use MDT for payloads with less than or equal to
23832  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23833  */
23834 boolean_t
23835 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23836 {
23837 	int	blocks;
23838 	ssize_t	total, missing, size;
23839 
23840 	ASSERT(mp != NULL);
23841 	ASSERT(hdr_len > 0);
23842 
23843 	size = MBLKL(mp) - hdr_len;
23844 	if (size <= 0)
23845 		return (B_FALSE);
23846 
23847 	/* The first mblk contains the header and some payload. */
23848 	blocks = 1;
23849 	total = size;
23850 	size %= len;
23851 	missing = (size == 0) ? 0 : (len - size);
23852 	mp = mp->b_cont;
23853 
23854 	while (mp != NULL) {
23855 		/*
23856 		 * Give up if we encounter a zero length message block.
23857 		 * In practice, this should rarely happen and therefore
23858 		 * not worth the trouble of freeing and re-linking the
23859 		 * mblk from the chain to handle such case.
23860 		 */
23861 		if ((size = MBLKL(mp)) == 0)
23862 			return (B_FALSE);
23863 
23864 		/* Too many payload buffers for a single Multidata message? */
23865 		if (++blocks > MULTIDATA_MAX_PBUFS)
23866 			return (B_FALSE);
23867 
23868 		total += size;
23869 		/* Is a frag distributed over two or more message blocks? */
23870 		if (missing > size)
23871 			return (B_FALSE);
23872 		size -= missing;
23873 
23874 		size %= len;
23875 		missing = (size == 0) ? 0 : (len - size);
23876 
23877 		mp = mp->b_cont;
23878 	}
23879 
23880 	return (total > ip_wput_frag_mdt_min);
23881 }
23882 
23883 /*
23884  * Outbound IPv4 fragmentation routine using MDT.
23885  */
23886 static void
23887 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23888     uint32_t frag_flag, int offset)
23889 {
23890 	ipha_t		*ipha_orig;
23891 	int		i1, ip_data_end;
23892 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23893 	mblk_t		*hdr_mp, *md_mp = NULL;
23894 	unsigned char	*hdr_ptr, *pld_ptr;
23895 	multidata_t	*mmd;
23896 	ip_pdescinfo_t	pdi;
23897 	ill_t		*ill;
23898 	ip_stack_t	*ipst = ire->ire_ipst;
23899 
23900 	ASSERT(DB_TYPE(mp) == M_DATA);
23901 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23902 
23903 	ill = ire_to_ill(ire);
23904 	ASSERT(ill != NULL);
23905 
23906 	ipha_orig = (ipha_t *)mp->b_rptr;
23907 	mp->b_rptr += sizeof (ipha_t);
23908 
23909 	/* Calculate how many packets we will send out */
23910 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23911 	pkts = (i1 + len - 1) / len;
23912 	ASSERT(pkts > 1);
23913 
23914 	/* Allocate a message block which will hold all the IP Headers. */
23915 	wroff = ipst->ips_ip_wroff_extra;
23916 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23917 
23918 	i1 = pkts * hdr_chunk_len;
23919 	/*
23920 	 * Create the header buffer, Multidata and destination address
23921 	 * and SAP attribute that should be associated with it.
23922 	 */
23923 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23924 	    ((hdr_mp->b_wptr += i1),
23925 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23926 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23927 		freemsg(mp);
23928 		if (md_mp == NULL) {
23929 			freemsg(hdr_mp);
23930 		} else {
23931 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23932 			freemsg(md_mp);
23933 		}
23934 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23935 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23936 		return;
23937 	}
23938 	IP_STAT(ipst, ip_frag_mdt_allocd);
23939 
23940 	/*
23941 	 * Add a payload buffer to the Multidata; this operation must not
23942 	 * fail, or otherwise our logic in this routine is broken.  There
23943 	 * is no memory allocation done by the routine, so any returned
23944 	 * failure simply tells us that we've done something wrong.
23945 	 *
23946 	 * A failure tells us that either we're adding the same payload
23947 	 * buffer more than once, or we're trying to add more buffers than
23948 	 * allowed.  None of the above cases should happen, and we panic
23949 	 * because either there's horrible heap corruption, and/or
23950 	 * programming mistake.
23951 	 */
23952 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23953 		goto pbuf_panic;
23954 
23955 	hdr_ptr = hdr_mp->b_rptr;
23956 	pld_ptr = mp->b_rptr;
23957 
23958 	/* Establish the ending byte offset, based on the starting offset. */
23959 	offset <<= 3;
23960 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23961 	    IP_SIMPLE_HDR_LENGTH;
23962 
23963 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23964 
23965 	while (pld_ptr < mp->b_wptr) {
23966 		ipha_t		*ipha;
23967 		uint16_t	offset_and_flags;
23968 		uint16_t	ip_len;
23969 		int		error;
23970 
23971 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23972 		ipha = (ipha_t *)(hdr_ptr + wroff);
23973 		ASSERT(OK_32PTR(ipha));
23974 		*ipha = *ipha_orig;
23975 
23976 		if (ip_data_end - offset > len) {
23977 			offset_and_flags = IPH_MF;
23978 		} else {
23979 			/*
23980 			 * Last frag. Set len to the length of this last piece.
23981 			 */
23982 			len = ip_data_end - offset;
23983 			/* A frag of a frag might have IPH_MF non-zero */
23984 			offset_and_flags =
23985 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23986 			    IPH_MF;
23987 		}
23988 		offset_and_flags |= (uint16_t)(offset >> 3);
23989 		offset_and_flags |= (uint16_t)frag_flag;
23990 		/* Store the offset and flags in the IP header. */
23991 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23992 
23993 		/* Store the length in the IP header. */
23994 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23995 		ipha->ipha_length = htons(ip_len);
23996 
23997 		/*
23998 		 * Set the IP header checksum.  Note that mp is just
23999 		 * the header, so this is easy to pass to ip_csum.
24000 		 */
24001 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24002 
24003 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24004 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24005 		    NULL, int, 0);
24006 
24007 		/*
24008 		 * Record offset and size of header and data of the next packet
24009 		 * in the multidata message.
24010 		 */
24011 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24012 		PDESC_PLD_INIT(&pdi);
24013 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24014 		ASSERT(i1 > 0);
24015 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24016 		if (i1 == len) {
24017 			pld_ptr += len;
24018 		} else {
24019 			i1 = len - i1;
24020 			mp = mp->b_cont;
24021 			ASSERT(mp != NULL);
24022 			ASSERT(MBLKL(mp) >= i1);
24023 			/*
24024 			 * Attach the next payload message block to the
24025 			 * multidata message.
24026 			 */
24027 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24028 				goto pbuf_panic;
24029 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24030 			pld_ptr = mp->b_rptr + i1;
24031 		}
24032 
24033 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24034 		    KM_NOSLEEP)) == NULL) {
24035 			/*
24036 			 * Any failure other than ENOMEM indicates that we
24037 			 * have passed in invalid pdesc info or parameters
24038 			 * to mmd_addpdesc, which must not happen.
24039 			 *
24040 			 * EINVAL is a result of failure on boundary checks
24041 			 * against the pdesc info contents.  It should not
24042 			 * happen, and we panic because either there's
24043 			 * horrible heap corruption, and/or programming
24044 			 * mistake.
24045 			 */
24046 			if (error != ENOMEM) {
24047 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24048 				    "pdesc logic error detected for "
24049 				    "mmd %p pinfo %p (%d)\n",
24050 				    (void *)mmd, (void *)&pdi, error);
24051 				/* NOTREACHED */
24052 			}
24053 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24054 			/* Free unattached payload message blocks as well */
24055 			md_mp->b_cont = mp->b_cont;
24056 			goto free_mmd;
24057 		}
24058 
24059 		/* Advance fragment offset. */
24060 		offset += len;
24061 
24062 		/* Advance to location for next header in the buffer. */
24063 		hdr_ptr += hdr_chunk_len;
24064 
24065 		/* Did we reach the next payload message block? */
24066 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24067 			mp = mp->b_cont;
24068 			/*
24069 			 * Attach the next message block with payload
24070 			 * data to the multidata message.
24071 			 */
24072 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24073 				goto pbuf_panic;
24074 			pld_ptr = mp->b_rptr;
24075 		}
24076 	}
24077 
24078 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24079 	ASSERT(mp->b_wptr == pld_ptr);
24080 
24081 	/* Update IP statistics */
24082 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24083 
24084 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24085 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24086 
24087 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24088 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24089 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24090 
24091 	if (pkt_type == OB_PKT) {
24092 		ire->ire_ob_pkt_count += pkts;
24093 		if (ire->ire_ipif != NULL)
24094 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24095 	} else {
24096 		/* The type is IB_PKT in the forwarding path. */
24097 		ire->ire_ib_pkt_count += pkts;
24098 		ASSERT(!IRE_IS_LOCAL(ire));
24099 		if (ire->ire_type & IRE_BROADCAST) {
24100 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24101 		} else {
24102 			UPDATE_MIB(ill->ill_ip_mib,
24103 			    ipIfStatsHCOutForwDatagrams, pkts);
24104 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24105 		}
24106 	}
24107 	ire->ire_last_used_time = lbolt;
24108 	/* Send it down */
24109 	putnext(ire->ire_stq, md_mp);
24110 	return;
24111 
24112 pbuf_panic:
24113 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24114 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24115 	    pbuf_idx);
24116 	/* NOTREACHED */
24117 }
24118 
24119 /*
24120  * Outbound IP fragmentation routine.
24121  *
24122  * NOTE : This routine does not ire_refrele the ire that is passed in
24123  * as the argument.
24124  */
24125 static void
24126 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24127     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24128 {
24129 	int		i1;
24130 	mblk_t		*ll_hdr_mp;
24131 	int 		ll_hdr_len;
24132 	int		hdr_len;
24133 	mblk_t		*hdr_mp;
24134 	ipha_t		*ipha;
24135 	int		ip_data_end;
24136 	int		len;
24137 	mblk_t		*mp = mp_orig, *mp1;
24138 	int		offset;
24139 	queue_t		*q;
24140 	uint32_t	v_hlen_tos_len;
24141 	mblk_t		*first_mp;
24142 	boolean_t	mctl_present;
24143 	ill_t		*ill;
24144 	ill_t		*out_ill;
24145 	mblk_t		*xmit_mp;
24146 	mblk_t		*carve_mp;
24147 	ire_t		*ire1 = NULL;
24148 	ire_t		*save_ire = NULL;
24149 	mblk_t  	*next_mp = NULL;
24150 	boolean_t	last_frag = B_FALSE;
24151 	boolean_t	multirt_send = B_FALSE;
24152 	ire_t		*first_ire = NULL;
24153 	irb_t		*irb = NULL;
24154 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24155 
24156 	ill = ire_to_ill(ire);
24157 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24158 
24159 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24160 
24161 	if (max_frag == 0) {
24162 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24163 		    " -  dropping packet\n"));
24164 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24165 		freemsg(mp);
24166 		return;
24167 	}
24168 
24169 	/*
24170 	 * IPsec does not allow hw accelerated packets to be fragmented
24171 	 * This check is made in ip_wput_ipsec_out prior to coming here
24172 	 * via ip_wput_ire_fragmentit.
24173 	 *
24174 	 * If at this point we have an ire whose ARP request has not
24175 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24176 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24177 	 * This packet and all fragmentable packets for this ire will
24178 	 * continue to get dropped while ire_nce->nce_state remains in
24179 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24180 	 * ND_REACHABLE, all subsquent large packets for this ire will
24181 	 * get fragemented and sent out by this function.
24182 	 */
24183 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24184 		/* If nce_state is ND_INITIAL, trigger ARP query */
24185 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24186 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24187 		    " -  dropping packet\n"));
24188 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24189 		freemsg(mp);
24190 		return;
24191 	}
24192 
24193 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24194 	    "ip_wput_frag_start:");
24195 
24196 	if (mp->b_datap->db_type == M_CTL) {
24197 		first_mp = mp;
24198 		mp_orig = mp = mp->b_cont;
24199 		mctl_present = B_TRUE;
24200 	} else {
24201 		first_mp = mp;
24202 		mctl_present = B_FALSE;
24203 	}
24204 
24205 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24206 	ipha = (ipha_t *)mp->b_rptr;
24207 
24208 	/*
24209 	 * If the Don't Fragment flag is on, generate an ICMP destination
24210 	 * unreachable, fragmentation needed.
24211 	 */
24212 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24213 	if (offset & IPH_DF) {
24214 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24215 		if (is_system_labeled()) {
24216 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24217 			    ire->ire_max_frag - max_frag, AF_INET);
24218 		}
24219 		/*
24220 		 * Need to compute hdr checksum if called from ip_wput_ire.
24221 		 * Note that ip_rput_forward verifies the checksum before
24222 		 * calling this routine so in that case this is a noop.
24223 		 */
24224 		ipha->ipha_hdr_checksum = 0;
24225 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24226 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24227 		    ipst);
24228 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24229 		    "ip_wput_frag_end:(%S)",
24230 		    "don't fragment");
24231 		return;
24232 	}
24233 	/*
24234 	 * Labeled systems adjust max_frag if they add a label
24235 	 * to send the correct path mtu.  We need the real mtu since we
24236 	 * are fragmenting the packet after label adjustment.
24237 	 */
24238 	if (is_system_labeled())
24239 		max_frag = ire->ire_max_frag;
24240 	if (mctl_present)
24241 		freeb(first_mp);
24242 	/*
24243 	 * Establish the starting offset.  May not be zero if we are fragging
24244 	 * a fragment that is being forwarded.
24245 	 */
24246 	offset = offset & IPH_OFFSET;
24247 
24248 	/* TODO why is this test needed? */
24249 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24250 	if (((max_frag - LENGTH) & ~7) < 8) {
24251 		/* TODO: notify ulp somehow */
24252 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24253 		freemsg(mp);
24254 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24255 		    "ip_wput_frag_end:(%S)",
24256 		    "len < 8");
24257 		return;
24258 	}
24259 
24260 	hdr_len = (V_HLEN & 0xF) << 2;
24261 
24262 	ipha->ipha_hdr_checksum = 0;
24263 
24264 	/*
24265 	 * Establish the number of bytes maximum per frag, after putting
24266 	 * in the header.
24267 	 */
24268 	len = (max_frag - hdr_len) & ~7;
24269 
24270 	/* Check if we can use MDT to send out the frags. */
24271 	ASSERT(!IRE_IS_LOCAL(ire));
24272 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24273 	    ipst->ips_ip_multidata_outbound &&
24274 	    !(ire->ire_flags & RTF_MULTIRT) &&
24275 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24276 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24277 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24278 		ASSERT(ill->ill_mdt_capab != NULL);
24279 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24280 			/*
24281 			 * If MDT has been previously turned off in the past,
24282 			 * and we currently can do MDT (due to IPQoS policy
24283 			 * removal, etc.) then enable it for this interface.
24284 			 */
24285 			ill->ill_mdt_capab->ill_mdt_on = 1;
24286 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24287 			    ill->ill_name));
24288 		}
24289 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24290 		    offset);
24291 		return;
24292 	}
24293 
24294 	/* Get a copy of the header for the trailing frags */
24295 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24296 	    mp);
24297 	if (!hdr_mp) {
24298 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24299 		freemsg(mp);
24300 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24301 		    "ip_wput_frag_end:(%S)",
24302 		    "couldn't copy hdr");
24303 		return;
24304 	}
24305 
24306 	/* Store the starting offset, with the MoreFrags flag. */
24307 	i1 = offset | IPH_MF | frag_flag;
24308 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24309 
24310 	/* Establish the ending byte offset, based on the starting offset. */
24311 	offset <<= 3;
24312 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24313 
24314 	/* Store the length of the first fragment in the IP header. */
24315 	i1 = len + hdr_len;
24316 	ASSERT(i1 <= IP_MAXPACKET);
24317 	ipha->ipha_length = htons((uint16_t)i1);
24318 
24319 	/*
24320 	 * Compute the IP header checksum for the first frag.  We have to
24321 	 * watch out that we stop at the end of the header.
24322 	 */
24323 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24324 
24325 	/*
24326 	 * Now carve off the first frag.  Note that this will include the
24327 	 * original IP header.
24328 	 */
24329 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24330 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24331 		freeb(hdr_mp);
24332 		freemsg(mp_orig);
24333 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24334 		    "ip_wput_frag_end:(%S)",
24335 		    "couldn't carve first");
24336 		return;
24337 	}
24338 
24339 	/*
24340 	 * Multirouting case. Each fragment is replicated
24341 	 * via all non-condemned RTF_MULTIRT routes
24342 	 * currently resolved.
24343 	 * We ensure that first_ire is the first RTF_MULTIRT
24344 	 * ire in the bucket.
24345 	 */
24346 	if (ire->ire_flags & RTF_MULTIRT) {
24347 		irb = ire->ire_bucket;
24348 		ASSERT(irb != NULL);
24349 
24350 		multirt_send = B_TRUE;
24351 
24352 		/* Make sure we do not omit any multiroute ire. */
24353 		IRB_REFHOLD(irb);
24354 		for (first_ire = irb->irb_ire;
24355 		    first_ire != NULL;
24356 		    first_ire = first_ire->ire_next) {
24357 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24358 			    (first_ire->ire_addr == ire->ire_addr) &&
24359 			    !(first_ire->ire_marks &
24360 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24361 				break;
24362 		}
24363 
24364 		if (first_ire != NULL) {
24365 			if (first_ire != ire) {
24366 				IRE_REFHOLD(first_ire);
24367 				/*
24368 				 * Do not release the ire passed in
24369 				 * as the argument.
24370 				 */
24371 				ire = first_ire;
24372 			} else {
24373 				first_ire = NULL;
24374 			}
24375 		}
24376 		IRB_REFRELE(irb);
24377 
24378 		/*
24379 		 * Save the first ire; we will need to restore it
24380 		 * for the trailing frags.
24381 		 * We REFHOLD save_ire, as each iterated ire will be
24382 		 * REFRELEd.
24383 		 */
24384 		save_ire = ire;
24385 		IRE_REFHOLD(save_ire);
24386 	}
24387 
24388 	/*
24389 	 * First fragment emission loop.
24390 	 * In most cases, the emission loop below is entered only
24391 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24392 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24393 	 * bucket, and send the fragment through all crossed
24394 	 * RTF_MULTIRT routes.
24395 	 */
24396 	do {
24397 		if (ire->ire_flags & RTF_MULTIRT) {
24398 			/*
24399 			 * We are in a multiple send case, need to get
24400 			 * the next ire and make a copy of the packet.
24401 			 * ire1 holds here the next ire to process in the
24402 			 * bucket. If multirouting is expected,
24403 			 * any non-RTF_MULTIRT ire that has the
24404 			 * right destination address is ignored.
24405 			 *
24406 			 * We have to take into account the MTU of
24407 			 * each walked ire. max_frag is set by the
24408 			 * the caller and generally refers to
24409 			 * the primary ire entry. Here we ensure that
24410 			 * no route with a lower MTU will be used, as
24411 			 * fragments are carved once for all ires,
24412 			 * then replicated.
24413 			 */
24414 			ASSERT(irb != NULL);
24415 			IRB_REFHOLD(irb);
24416 			for (ire1 = ire->ire_next;
24417 			    ire1 != NULL;
24418 			    ire1 = ire1->ire_next) {
24419 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24420 					continue;
24421 				if (ire1->ire_addr != ire->ire_addr)
24422 					continue;
24423 				if (ire1->ire_marks &
24424 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24425 					continue;
24426 				/*
24427 				 * Ensure we do not exceed the MTU
24428 				 * of the next route.
24429 				 */
24430 				if (ire1->ire_max_frag < max_frag) {
24431 					ip_multirt_bad_mtu(ire1, max_frag);
24432 					continue;
24433 				}
24434 
24435 				/* Got one. */
24436 				IRE_REFHOLD(ire1);
24437 				break;
24438 			}
24439 			IRB_REFRELE(irb);
24440 
24441 			if (ire1 != NULL) {
24442 				next_mp = copyb(mp);
24443 				if ((next_mp == NULL) ||
24444 				    ((mp->b_cont != NULL) &&
24445 				    ((next_mp->b_cont =
24446 				    dupmsg(mp->b_cont)) == NULL))) {
24447 					freemsg(next_mp);
24448 					next_mp = NULL;
24449 					ire_refrele(ire1);
24450 					ire1 = NULL;
24451 				}
24452 			}
24453 
24454 			/* Last multiroute ire; don't loop anymore. */
24455 			if (ire1 == NULL) {
24456 				multirt_send = B_FALSE;
24457 			}
24458 		}
24459 
24460 		ll_hdr_len = 0;
24461 		LOCK_IRE_FP_MP(ire);
24462 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24463 		if (ll_hdr_mp != NULL) {
24464 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24465 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24466 		} else {
24467 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24468 		}
24469 
24470 		/* If there is a transmit header, get a copy for this frag. */
24471 		/*
24472 		 * TODO: should check db_ref before calling ip_carve_mp since
24473 		 * it might give us a dup.
24474 		 */
24475 		if (!ll_hdr_mp) {
24476 			/* No xmit header. */
24477 			xmit_mp = mp;
24478 
24479 		/* We have a link-layer header that can fit in our mblk. */
24480 		} else if (mp->b_datap->db_ref == 1 &&
24481 		    ll_hdr_len != 0 &&
24482 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24483 			/* M_DATA fastpath */
24484 			mp->b_rptr -= ll_hdr_len;
24485 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24486 			xmit_mp = mp;
24487 
24488 		/* Corner case if copyb has failed */
24489 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24490 			UNLOCK_IRE_FP_MP(ire);
24491 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24492 			freeb(hdr_mp);
24493 			freemsg(mp);
24494 			freemsg(mp_orig);
24495 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24496 			    "ip_wput_frag_end:(%S)",
24497 			    "discard");
24498 
24499 			if (multirt_send) {
24500 				ASSERT(ire1);
24501 				ASSERT(next_mp);
24502 
24503 				freemsg(next_mp);
24504 				ire_refrele(ire1);
24505 			}
24506 			if (save_ire != NULL)
24507 				IRE_REFRELE(save_ire);
24508 
24509 			if (first_ire != NULL)
24510 				ire_refrele(first_ire);
24511 			return;
24512 
24513 		/*
24514 		 * Case of res_mp OR the fastpath mp can't fit
24515 		 * in the mblk
24516 		 */
24517 		} else {
24518 			xmit_mp->b_cont = mp;
24519 
24520 			/*
24521 			 * Get priority marking, if any.
24522 			 * We propagate the CoS marking from the
24523 			 * original packet that went to QoS processing
24524 			 * in ip_wput_ire to the newly carved mp.
24525 			 */
24526 			if (DB_TYPE(xmit_mp) == M_DATA)
24527 				xmit_mp->b_band = mp->b_band;
24528 		}
24529 		UNLOCK_IRE_FP_MP(ire);
24530 
24531 		q = ire->ire_stq;
24532 		out_ill = (ill_t *)q->q_ptr;
24533 
24534 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24535 
24536 		DTRACE_PROBE4(ip4__physical__out__start,
24537 		    ill_t *, NULL, ill_t *, out_ill,
24538 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24539 
24540 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24541 		    ipst->ips_ipv4firewall_physical_out,
24542 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24543 
24544 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24545 
24546 		if (xmit_mp != NULL) {
24547 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24548 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24549 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24550 
24551 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24552 
24553 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24554 			UPDATE_MIB(out_ill->ill_ip_mib,
24555 			    ipIfStatsHCOutOctets, i1);
24556 
24557 			if (pkt_type != OB_PKT) {
24558 				/*
24559 				 * Update the packet count and MIB stats
24560 				 * of trailing RTF_MULTIRT ires.
24561 				 */
24562 				UPDATE_OB_PKT_COUNT(ire);
24563 				BUMP_MIB(out_ill->ill_ip_mib,
24564 				    ipIfStatsOutFragReqds);
24565 			}
24566 		}
24567 
24568 		if (multirt_send) {
24569 			/*
24570 			 * We are in a multiple send case; look for
24571 			 * the next ire and re-enter the loop.
24572 			 */
24573 			ASSERT(ire1);
24574 			ASSERT(next_mp);
24575 			/* REFRELE the current ire before looping */
24576 			ire_refrele(ire);
24577 			ire = ire1;
24578 			ire1 = NULL;
24579 			mp = next_mp;
24580 			next_mp = NULL;
24581 		}
24582 	} while (multirt_send);
24583 
24584 	ASSERT(ire1 == NULL);
24585 
24586 	/* Restore the original ire; we need it for the trailing frags */
24587 	if (save_ire != NULL) {
24588 		/* REFRELE the last iterated ire */
24589 		ire_refrele(ire);
24590 		/* save_ire has been REFHOLDed */
24591 		ire = save_ire;
24592 		save_ire = NULL;
24593 		q = ire->ire_stq;
24594 	}
24595 
24596 	if (pkt_type == OB_PKT) {
24597 		UPDATE_OB_PKT_COUNT(ire);
24598 	} else {
24599 		out_ill = (ill_t *)q->q_ptr;
24600 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24601 		UPDATE_IB_PKT_COUNT(ire);
24602 	}
24603 
24604 	/* Advance the offset to the second frag starting point. */
24605 	offset += len;
24606 	/*
24607 	 * Update hdr_len from the copied header - there might be less options
24608 	 * in the later fragments.
24609 	 */
24610 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24611 	/* Loop until done. */
24612 	for (;;) {
24613 		uint16_t	offset_and_flags;
24614 		uint16_t	ip_len;
24615 
24616 		if (ip_data_end - offset > len) {
24617 			/*
24618 			 * Carve off the appropriate amount from the original
24619 			 * datagram.
24620 			 */
24621 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24622 				mp = NULL;
24623 				break;
24624 			}
24625 			/*
24626 			 * More frags after this one.  Get another copy
24627 			 * of the header.
24628 			 */
24629 			if (carve_mp->b_datap->db_ref == 1 &&
24630 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24631 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24632 				/* Inline IP header */
24633 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24634 				    hdr_mp->b_rptr;
24635 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24636 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24637 				mp = carve_mp;
24638 			} else {
24639 				if (!(mp = copyb(hdr_mp))) {
24640 					freemsg(carve_mp);
24641 					break;
24642 				}
24643 				/* Get priority marking, if any. */
24644 				mp->b_band = carve_mp->b_band;
24645 				mp->b_cont = carve_mp;
24646 			}
24647 			ipha = (ipha_t *)mp->b_rptr;
24648 			offset_and_flags = IPH_MF;
24649 		} else {
24650 			/*
24651 			 * Last frag.  Consume the header. Set len to
24652 			 * the length of this last piece.
24653 			 */
24654 			len = ip_data_end - offset;
24655 
24656 			/*
24657 			 * Carve off the appropriate amount from the original
24658 			 * datagram.
24659 			 */
24660 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24661 				mp = NULL;
24662 				break;
24663 			}
24664 			if (carve_mp->b_datap->db_ref == 1 &&
24665 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24666 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24667 				/* Inline IP header */
24668 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24669 				    hdr_mp->b_rptr;
24670 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24671 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24672 				mp = carve_mp;
24673 				freeb(hdr_mp);
24674 				hdr_mp = mp;
24675 			} else {
24676 				mp = hdr_mp;
24677 				/* Get priority marking, if any. */
24678 				mp->b_band = carve_mp->b_band;
24679 				mp->b_cont = carve_mp;
24680 			}
24681 			ipha = (ipha_t *)mp->b_rptr;
24682 			/* A frag of a frag might have IPH_MF non-zero */
24683 			offset_and_flags =
24684 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24685 			    IPH_MF;
24686 		}
24687 		offset_and_flags |= (uint16_t)(offset >> 3);
24688 		offset_and_flags |= (uint16_t)frag_flag;
24689 		/* Store the offset and flags in the IP header. */
24690 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24691 
24692 		/* Store the length in the IP header. */
24693 		ip_len = (uint16_t)(len + hdr_len);
24694 		ipha->ipha_length = htons(ip_len);
24695 
24696 		/*
24697 		 * Set the IP header checksum.	Note that mp is just
24698 		 * the header, so this is easy to pass to ip_csum.
24699 		 */
24700 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24701 
24702 		/* Attach a transmit header, if any, and ship it. */
24703 		if (pkt_type == OB_PKT) {
24704 			UPDATE_OB_PKT_COUNT(ire);
24705 		} else {
24706 			out_ill = (ill_t *)q->q_ptr;
24707 			BUMP_MIB(out_ill->ill_ip_mib,
24708 			    ipIfStatsHCOutForwDatagrams);
24709 			UPDATE_IB_PKT_COUNT(ire);
24710 		}
24711 
24712 		if (ire->ire_flags & RTF_MULTIRT) {
24713 			irb = ire->ire_bucket;
24714 			ASSERT(irb != NULL);
24715 
24716 			multirt_send = B_TRUE;
24717 
24718 			/*
24719 			 * Save the original ire; we will need to restore it
24720 			 * for the tailing frags.
24721 			 */
24722 			save_ire = ire;
24723 			IRE_REFHOLD(save_ire);
24724 		}
24725 		/*
24726 		 * Emission loop for this fragment, similar
24727 		 * to what is done for the first fragment.
24728 		 */
24729 		do {
24730 			if (multirt_send) {
24731 				/*
24732 				 * We are in a multiple send case, need to get
24733 				 * the next ire and make a copy of the packet.
24734 				 */
24735 				ASSERT(irb != NULL);
24736 				IRB_REFHOLD(irb);
24737 				for (ire1 = ire->ire_next;
24738 				    ire1 != NULL;
24739 				    ire1 = ire1->ire_next) {
24740 					if (!(ire1->ire_flags & RTF_MULTIRT))
24741 						continue;
24742 					if (ire1->ire_addr != ire->ire_addr)
24743 						continue;
24744 					if (ire1->ire_marks &
24745 					    (IRE_MARK_CONDEMNED |
24746 					    IRE_MARK_TESTHIDDEN))
24747 						continue;
24748 					/*
24749 					 * Ensure we do not exceed the MTU
24750 					 * of the next route.
24751 					 */
24752 					if (ire1->ire_max_frag < max_frag) {
24753 						ip_multirt_bad_mtu(ire1,
24754 						    max_frag);
24755 						continue;
24756 					}
24757 
24758 					/* Got one. */
24759 					IRE_REFHOLD(ire1);
24760 					break;
24761 				}
24762 				IRB_REFRELE(irb);
24763 
24764 				if (ire1 != NULL) {
24765 					next_mp = copyb(mp);
24766 					if ((next_mp == NULL) ||
24767 					    ((mp->b_cont != NULL) &&
24768 					    ((next_mp->b_cont =
24769 					    dupmsg(mp->b_cont)) == NULL))) {
24770 						freemsg(next_mp);
24771 						next_mp = NULL;
24772 						ire_refrele(ire1);
24773 						ire1 = NULL;
24774 					}
24775 				}
24776 
24777 				/* Last multiroute ire; don't loop anymore. */
24778 				if (ire1 == NULL) {
24779 					multirt_send = B_FALSE;
24780 				}
24781 			}
24782 
24783 			/* Update transmit header */
24784 			ll_hdr_len = 0;
24785 			LOCK_IRE_FP_MP(ire);
24786 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24787 			if (ll_hdr_mp != NULL) {
24788 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24789 				ll_hdr_len = MBLKL(ll_hdr_mp);
24790 			} else {
24791 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24792 			}
24793 
24794 			if (!ll_hdr_mp) {
24795 				xmit_mp = mp;
24796 
24797 			/*
24798 			 * We have link-layer header that can fit in
24799 			 * our mblk.
24800 			 */
24801 			} else if (mp->b_datap->db_ref == 1 &&
24802 			    ll_hdr_len != 0 &&
24803 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24804 				/* M_DATA fastpath */
24805 				mp->b_rptr -= ll_hdr_len;
24806 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24807 				    ll_hdr_len);
24808 				xmit_mp = mp;
24809 
24810 			/*
24811 			 * Case of res_mp OR the fastpath mp can't fit
24812 			 * in the mblk
24813 			 */
24814 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24815 				xmit_mp->b_cont = mp;
24816 				/* Get priority marking, if any. */
24817 				if (DB_TYPE(xmit_mp) == M_DATA)
24818 					xmit_mp->b_band = mp->b_band;
24819 
24820 			/* Corner case if copyb failed */
24821 			} else {
24822 				/*
24823 				 * Exit both the replication and
24824 				 * fragmentation loops.
24825 				 */
24826 				UNLOCK_IRE_FP_MP(ire);
24827 				goto drop_pkt;
24828 			}
24829 			UNLOCK_IRE_FP_MP(ire);
24830 
24831 			mp1 = mp;
24832 			out_ill = (ill_t *)q->q_ptr;
24833 
24834 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24835 
24836 			DTRACE_PROBE4(ip4__physical__out__start,
24837 			    ill_t *, NULL, ill_t *, out_ill,
24838 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24839 
24840 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24841 			    ipst->ips_ipv4firewall_physical_out,
24842 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24843 
24844 			DTRACE_PROBE1(ip4__physical__out__end,
24845 			    mblk_t *, xmit_mp);
24846 
24847 			if (mp != mp1 && hdr_mp == mp1)
24848 				hdr_mp = mp;
24849 			if (mp != mp1 && mp_orig == mp1)
24850 				mp_orig = mp;
24851 
24852 			if (xmit_mp != NULL) {
24853 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24854 				    NULL, void_ip_t *, ipha,
24855 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24856 				    ipha, ip6_t *, NULL, int, 0);
24857 
24858 				ILL_SEND_TX(out_ill, ire, connp,
24859 				    xmit_mp, 0, connp);
24860 
24861 				BUMP_MIB(out_ill->ill_ip_mib,
24862 				    ipIfStatsHCOutTransmits);
24863 				UPDATE_MIB(out_ill->ill_ip_mib,
24864 				    ipIfStatsHCOutOctets, ip_len);
24865 
24866 				if (pkt_type != OB_PKT) {
24867 					/*
24868 					 * Update the packet count of trailing
24869 					 * RTF_MULTIRT ires.
24870 					 */
24871 					UPDATE_OB_PKT_COUNT(ire);
24872 				}
24873 			}
24874 
24875 			/* All done if we just consumed the hdr_mp. */
24876 			if (mp == hdr_mp) {
24877 				last_frag = B_TRUE;
24878 				BUMP_MIB(out_ill->ill_ip_mib,
24879 				    ipIfStatsOutFragOKs);
24880 			}
24881 
24882 			if (multirt_send) {
24883 				/*
24884 				 * We are in a multiple send case; look for
24885 				 * the next ire and re-enter the loop.
24886 				 */
24887 				ASSERT(ire1);
24888 				ASSERT(next_mp);
24889 				/* REFRELE the current ire before looping */
24890 				ire_refrele(ire);
24891 				ire = ire1;
24892 				ire1 = NULL;
24893 				q = ire->ire_stq;
24894 				mp = next_mp;
24895 				next_mp = NULL;
24896 			}
24897 		} while (multirt_send);
24898 		/*
24899 		 * Restore the original ire; we need it for the
24900 		 * trailing frags
24901 		 */
24902 		if (save_ire != NULL) {
24903 			ASSERT(ire1 == NULL);
24904 			/* REFRELE the last iterated ire */
24905 			ire_refrele(ire);
24906 			/* save_ire has been REFHOLDed */
24907 			ire = save_ire;
24908 			q = ire->ire_stq;
24909 			save_ire = NULL;
24910 		}
24911 
24912 		if (last_frag) {
24913 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24914 			    "ip_wput_frag_end:(%S)",
24915 			    "consumed hdr_mp");
24916 
24917 			if (first_ire != NULL)
24918 				ire_refrele(first_ire);
24919 			return;
24920 		}
24921 		/* Otherwise, advance and loop. */
24922 		offset += len;
24923 	}
24924 
24925 drop_pkt:
24926 	/* Clean up following allocation failure. */
24927 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24928 	freemsg(mp);
24929 	if (mp != hdr_mp)
24930 		freeb(hdr_mp);
24931 	if (mp != mp_orig)
24932 		freemsg(mp_orig);
24933 
24934 	if (save_ire != NULL)
24935 		IRE_REFRELE(save_ire);
24936 	if (first_ire != NULL)
24937 		ire_refrele(first_ire);
24938 
24939 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24940 	    "ip_wput_frag_end:(%S)",
24941 	    "end--alloc failure");
24942 }
24943 
24944 /*
24945  * Copy the header plus those options which have the copy bit set
24946  * src is the template to make sure we preserve the cred for TX purposes.
24947  */
24948 static mblk_t *
24949 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24950     mblk_t *src)
24951 {
24952 	mblk_t	*mp;
24953 	uchar_t	*up;
24954 
24955 	/*
24956 	 * Quick check if we need to look for options without the copy bit
24957 	 * set
24958 	 */
24959 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24960 	if (!mp)
24961 		return (mp);
24962 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24963 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24964 		bcopy(rptr, mp->b_rptr, hdr_len);
24965 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24966 		return (mp);
24967 	}
24968 	up  = mp->b_rptr;
24969 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24970 	up += IP_SIMPLE_HDR_LENGTH;
24971 	rptr += IP_SIMPLE_HDR_LENGTH;
24972 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24973 	while (hdr_len > 0) {
24974 		uint32_t optval;
24975 		uint32_t optlen;
24976 
24977 		optval = *rptr;
24978 		if (optval == IPOPT_EOL)
24979 			break;
24980 		if (optval == IPOPT_NOP)
24981 			optlen = 1;
24982 		else
24983 			optlen = rptr[1];
24984 		if (optval & IPOPT_COPY) {
24985 			bcopy(rptr, up, optlen);
24986 			up += optlen;
24987 		}
24988 		rptr += optlen;
24989 		hdr_len -= optlen;
24990 	}
24991 	/*
24992 	 * Make sure that we drop an even number of words by filling
24993 	 * with EOL to the next word boundary.
24994 	 */
24995 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24996 	    hdr_len & 0x3; hdr_len++)
24997 		*up++ = IPOPT_EOL;
24998 	mp->b_wptr = up;
24999 	/* Update header length */
25000 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25001 	return (mp);
25002 }
25003 
25004 /*
25005  * Delivery to local recipients including fanout to multiple recipients.
25006  * Does not do checksumming of UDP/TCP.
25007  * Note: q should be the read side queue for either the ill or conn.
25008  * Note: rq should be the read side q for the lower (ill) stream.
25009  * We don't send packets to IPPF processing, thus the last argument
25010  * to all the fanout calls are B_FALSE.
25011  */
25012 void
25013 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25014     int fanout_flags, zoneid_t zoneid)
25015 {
25016 	uint32_t	protocol;
25017 	mblk_t		*first_mp;
25018 	boolean_t	mctl_present;
25019 	int		ire_type;
25020 #define	rptr	((uchar_t *)ipha)
25021 	ip_stack_t	*ipst = ill->ill_ipst;
25022 
25023 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25024 	    "ip_wput_local_start: q %p", q);
25025 
25026 	if (ire != NULL) {
25027 		ire_type = ire->ire_type;
25028 	} else {
25029 		/*
25030 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25031 		 * packet is not multicast, we can't tell the ire type.
25032 		 */
25033 		ASSERT(CLASSD(ipha->ipha_dst));
25034 		ire_type = IRE_BROADCAST;
25035 	}
25036 
25037 	first_mp = mp;
25038 	if (first_mp->b_datap->db_type == M_CTL) {
25039 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25040 		if (!io->ipsec_out_secure) {
25041 			/*
25042 			 * This ipsec_out_t was allocated in ip_wput
25043 			 * for multicast packets to store the ill_index.
25044 			 * As this is being delivered locally, we don't
25045 			 * need this anymore.
25046 			 */
25047 			mp = first_mp->b_cont;
25048 			freeb(first_mp);
25049 			first_mp = mp;
25050 			mctl_present = B_FALSE;
25051 		} else {
25052 			/*
25053 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25054 			 * security properties for the looped-back packet.
25055 			 */
25056 			mctl_present = B_TRUE;
25057 			mp = first_mp->b_cont;
25058 			ASSERT(mp != NULL);
25059 			ipsec_out_to_in(first_mp);
25060 		}
25061 	} else {
25062 		mctl_present = B_FALSE;
25063 	}
25064 
25065 	DTRACE_PROBE4(ip4__loopback__in__start,
25066 	    ill_t *, ill, ill_t *, NULL,
25067 	    ipha_t *, ipha, mblk_t *, first_mp);
25068 
25069 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25070 	    ipst->ips_ipv4firewall_loopback_in,
25071 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25072 
25073 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25074 
25075 	if (first_mp == NULL)
25076 		return;
25077 
25078 	if (ipst->ips_ipobs_enabled) {
25079 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25080 		zoneid_t stackzoneid = netstackid_to_zoneid(
25081 		    ipst->ips_netstack->netstack_stackid);
25082 
25083 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25084 		/*
25085 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25086 		 * address.  Restrict the lookup below to the destination zone.
25087 		 */
25088 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25089 			lookup_zoneid = zoneid;
25090 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25091 		    lookup_zoneid);
25092 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25093 		    IPV4_VERSION, 0, ipst);
25094 	}
25095 
25096 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25097 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25098 	    int, 1);
25099 
25100 	ipst->ips_loopback_packets++;
25101 
25102 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25103 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25104 	if (!IS_SIMPLE_IPH(ipha)) {
25105 		ip_wput_local_options(ipha, ipst);
25106 	}
25107 
25108 	protocol = ipha->ipha_protocol;
25109 	switch (protocol) {
25110 	case IPPROTO_ICMP: {
25111 		ire_t		*ire_zone;
25112 		ilm_t		*ilm;
25113 		mblk_t		*mp1;
25114 		zoneid_t	last_zoneid;
25115 		ilm_walker_t	ilw;
25116 
25117 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25118 			ASSERT(ire_type == IRE_BROADCAST);
25119 			/*
25120 			 * In the multicast case, applications may have joined
25121 			 * the group from different zones, so we need to deliver
25122 			 * the packet to each of them. Loop through the
25123 			 * multicast memberships structures (ilm) on the receive
25124 			 * ill and send a copy of the packet up each matching
25125 			 * one. However, we don't do this for multicasts sent on
25126 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25127 			 * they must stay in the sender's zone.
25128 			 *
25129 			 * ilm_add_v6() ensures that ilms in the same zone are
25130 			 * contiguous in the ill_ilm list. We use this property
25131 			 * to avoid sending duplicates needed when two
25132 			 * applications in the same zone join the same group on
25133 			 * different logical interfaces: we ignore the ilm if
25134 			 * it's zoneid is the same as the last matching one.
25135 			 * In addition, the sending of the packet for
25136 			 * ire_zoneid is delayed until all of the other ilms
25137 			 * have been exhausted.
25138 			 */
25139 			last_zoneid = -1;
25140 			ilm = ilm_walker_start(&ilw, ill);
25141 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25142 				if (ipha->ipha_dst != ilm->ilm_addr ||
25143 				    ilm->ilm_zoneid == last_zoneid ||
25144 				    ilm->ilm_zoneid == zoneid ||
25145 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25146 					continue;
25147 				mp1 = ip_copymsg(first_mp);
25148 				if (mp1 == NULL)
25149 					continue;
25150 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25151 				    0, 0, mctl_present, B_FALSE, ill,
25152 				    ilm->ilm_zoneid);
25153 				last_zoneid = ilm->ilm_zoneid;
25154 			}
25155 			ilm_walker_finish(&ilw);
25156 			/*
25157 			 * Loopback case: the sending endpoint has
25158 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25159 			 * dispatch the multicast packet to the sending zone.
25160 			 */
25161 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25162 				freemsg(first_mp);
25163 				return;
25164 			}
25165 		} else if (ire_type == IRE_BROADCAST) {
25166 			/*
25167 			 * In the broadcast case, there may be many zones
25168 			 * which need a copy of the packet delivered to them.
25169 			 * There is one IRE_BROADCAST per broadcast address
25170 			 * and per zone; we walk those using a helper function.
25171 			 * In addition, the sending of the packet for zoneid is
25172 			 * delayed until all of the other ires have been
25173 			 * processed.
25174 			 */
25175 			IRB_REFHOLD(ire->ire_bucket);
25176 			ire_zone = NULL;
25177 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25178 			    ire)) != NULL) {
25179 				mp1 = ip_copymsg(first_mp);
25180 				if (mp1 == NULL)
25181 					continue;
25182 
25183 				UPDATE_IB_PKT_COUNT(ire_zone);
25184 				ire_zone->ire_last_used_time = lbolt;
25185 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25186 				    mctl_present, B_FALSE, ill,
25187 				    ire_zone->ire_zoneid);
25188 			}
25189 			IRB_REFRELE(ire->ire_bucket);
25190 		}
25191 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25192 		    0, mctl_present, B_FALSE, ill, zoneid);
25193 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25194 		    "ip_wput_local_end: q %p (%S)",
25195 		    q, "icmp");
25196 		return;
25197 	}
25198 	case IPPROTO_IGMP:
25199 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25200 			/* Bad packet - discarded by igmp_input */
25201 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25202 			    "ip_wput_local_end: q %p (%S)",
25203 			    q, "igmp_input--bad packet");
25204 			if (mctl_present)
25205 				freeb(first_mp);
25206 			return;
25207 		}
25208 		/*
25209 		 * igmp_input() may have returned the pulled up message.
25210 		 * So first_mp and ipha need to be reinitialized.
25211 		 */
25212 		ipha = (ipha_t *)mp->b_rptr;
25213 		if (mctl_present)
25214 			first_mp->b_cont = mp;
25215 		else
25216 			first_mp = mp;
25217 		/* deliver to local raw users */
25218 		break;
25219 	case IPPROTO_ENCAP:
25220 		/*
25221 		 * This case is covered by either ip_fanout_proto, or by
25222 		 * the above security processing for self-tunneled packets.
25223 		 */
25224 		break;
25225 	case IPPROTO_UDP: {
25226 		uint16_t	*up;
25227 		uint32_t	ports;
25228 
25229 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25230 		    UDP_PORTS_OFFSET);
25231 		/* Force a 'valid' checksum. */
25232 		up[3] = 0;
25233 
25234 		ports = *(uint32_t *)up;
25235 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25236 		    (ire_type == IRE_BROADCAST),
25237 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25238 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25239 		    ill, zoneid);
25240 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25241 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25242 		return;
25243 	}
25244 	case IPPROTO_TCP: {
25245 
25246 		/*
25247 		 * For TCP, discard broadcast packets.
25248 		 */
25249 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25250 			freemsg(first_mp);
25251 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25252 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25253 			return;
25254 		}
25255 
25256 		if (mp->b_datap->db_type == M_DATA) {
25257 			/*
25258 			 * M_DATA mblk, so init mblk (chain) for no struio().
25259 			 */
25260 			mblk_t	*mp1 = mp;
25261 
25262 			do {
25263 				mp1->b_datap->db_struioflag = 0;
25264 			} while ((mp1 = mp1->b_cont) != NULL);
25265 		}
25266 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25267 		    <= mp->b_wptr);
25268 		ip_fanout_tcp(q, first_mp, ill, ipha,
25269 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25270 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25271 		    mctl_present, B_FALSE, zoneid);
25272 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25273 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25274 		return;
25275 	}
25276 	case IPPROTO_SCTP:
25277 	{
25278 		uint32_t	ports;
25279 
25280 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25281 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25282 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25283 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25284 		return;
25285 	}
25286 
25287 	default:
25288 		break;
25289 	}
25290 	/*
25291 	 * Find a client for some other protocol.  We give
25292 	 * copies to multiple clients, if more than one is
25293 	 * bound.
25294 	 */
25295 	ip_fanout_proto(q, first_mp, ill, ipha,
25296 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25297 	    mctl_present, B_FALSE, ill, zoneid);
25298 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25299 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25300 #undef	rptr
25301 }
25302 
25303 /*
25304  * Update any source route, record route, or timestamp options.
25305  * Check that we are at end of strict source route.
25306  * The options have been sanity checked by ip_wput_options().
25307  */
25308 static void
25309 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25310 {
25311 	ipoptp_t	opts;
25312 	uchar_t		*opt;
25313 	uint8_t		optval;
25314 	uint8_t		optlen;
25315 	ipaddr_t	dst;
25316 	uint32_t	ts;
25317 	ire_t		*ire;
25318 	timestruc_t	now;
25319 
25320 	ip2dbg(("ip_wput_local_options\n"));
25321 	for (optval = ipoptp_first(&opts, ipha);
25322 	    optval != IPOPT_EOL;
25323 	    optval = ipoptp_next(&opts)) {
25324 		opt = opts.ipoptp_cur;
25325 		optlen = opts.ipoptp_len;
25326 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25327 		switch (optval) {
25328 			uint32_t off;
25329 		case IPOPT_SSRR:
25330 		case IPOPT_LSRR:
25331 			off = opt[IPOPT_OFFSET];
25332 			off--;
25333 			if (optlen < IP_ADDR_LEN ||
25334 			    off > optlen - IP_ADDR_LEN) {
25335 				/* End of source route */
25336 				break;
25337 			}
25338 			/*
25339 			 * This will only happen if two consecutive entries
25340 			 * in the source route contains our address or if
25341 			 * it is a packet with a loose source route which
25342 			 * reaches us before consuming the whole source route
25343 			 */
25344 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25345 			if (optval == IPOPT_SSRR) {
25346 				return;
25347 			}
25348 			/*
25349 			 * Hack: instead of dropping the packet truncate the
25350 			 * source route to what has been used by filling the
25351 			 * rest with IPOPT_NOP.
25352 			 */
25353 			opt[IPOPT_OLEN] = (uint8_t)off;
25354 			while (off < optlen) {
25355 				opt[off++] = IPOPT_NOP;
25356 			}
25357 			break;
25358 		case IPOPT_RR:
25359 			off = opt[IPOPT_OFFSET];
25360 			off--;
25361 			if (optlen < IP_ADDR_LEN ||
25362 			    off > optlen - IP_ADDR_LEN) {
25363 				/* No more room - ignore */
25364 				ip1dbg((
25365 				    "ip_wput_forward_options: end of RR\n"));
25366 				break;
25367 			}
25368 			dst = htonl(INADDR_LOOPBACK);
25369 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25370 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25371 			break;
25372 		case IPOPT_TS:
25373 			/* Insert timestamp if there is romm */
25374 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25375 			case IPOPT_TS_TSONLY:
25376 				off = IPOPT_TS_TIMELEN;
25377 				break;
25378 			case IPOPT_TS_PRESPEC:
25379 			case IPOPT_TS_PRESPEC_RFC791:
25380 				/* Verify that the address matched */
25381 				off = opt[IPOPT_OFFSET] - 1;
25382 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25383 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25384 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25385 				    ipst);
25386 				if (ire == NULL) {
25387 					/* Not for us */
25388 					break;
25389 				}
25390 				ire_refrele(ire);
25391 				/* FALLTHRU */
25392 			case IPOPT_TS_TSANDADDR:
25393 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25394 				break;
25395 			default:
25396 				/*
25397 				 * ip_*put_options should have already
25398 				 * dropped this packet.
25399 				 */
25400 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25401 				    "unknown IT - bug in ip_wput_options?\n");
25402 				return;	/* Keep "lint" happy */
25403 			}
25404 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25405 				/* Increase overflow counter */
25406 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25407 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25408 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25409 				    (off << 4);
25410 				break;
25411 			}
25412 			off = opt[IPOPT_OFFSET] - 1;
25413 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25414 			case IPOPT_TS_PRESPEC:
25415 			case IPOPT_TS_PRESPEC_RFC791:
25416 			case IPOPT_TS_TSANDADDR:
25417 				dst = htonl(INADDR_LOOPBACK);
25418 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25419 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25420 				/* FALLTHRU */
25421 			case IPOPT_TS_TSONLY:
25422 				off = opt[IPOPT_OFFSET] - 1;
25423 				/* Compute # of milliseconds since midnight */
25424 				gethrestime(&now);
25425 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25426 				    now.tv_nsec / (NANOSEC / MILLISEC);
25427 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25428 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25429 				break;
25430 			}
25431 			break;
25432 		}
25433 	}
25434 }
25435 
25436 /*
25437  * Send out a multicast packet on interface ipif.
25438  * The sender does not have an conn.
25439  * Caller verifies that this isn't a PHYI_LOOPBACK.
25440  */
25441 void
25442 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25443 {
25444 	ipha_t	*ipha;
25445 	ire_t	*ire;
25446 	ipaddr_t	dst;
25447 	mblk_t		*first_mp;
25448 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25449 
25450 	/* igmp_sendpkt always allocates a ipsec_out_t */
25451 	ASSERT(mp->b_datap->db_type == M_CTL);
25452 	ASSERT(!ipif->ipif_isv6);
25453 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25454 
25455 	first_mp = mp;
25456 	mp = first_mp->b_cont;
25457 	ASSERT(mp->b_datap->db_type == M_DATA);
25458 	ipha = (ipha_t *)mp->b_rptr;
25459 
25460 	/*
25461 	 * Find an IRE which matches the destination and the outgoing
25462 	 * queue (i.e. the outgoing interface.)
25463 	 */
25464 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25465 		dst = ipif->ipif_pp_dst_addr;
25466 	else
25467 		dst = ipha->ipha_dst;
25468 	/*
25469 	 * The source address has already been initialized by the
25470 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25471 	 * be sufficient rather than MATCH_IRE_IPIF.
25472 	 *
25473 	 * This function is used for sending IGMP packets.  For IPMP,
25474 	 * we sidestep IGMP snooping issues by sending all multicast
25475 	 * traffic on a single interface in the IPMP group.
25476 	 */
25477 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25478 	    MATCH_IRE_ILL, ipst);
25479 	if (!ire) {
25480 		/*
25481 		 * Mark this packet to make it be delivered to
25482 		 * ip_wput_ire after the new ire has been
25483 		 * created.
25484 		 */
25485 		mp->b_prev = NULL;
25486 		mp->b_next = NULL;
25487 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25488 		    zoneid, &zero_info);
25489 		return;
25490 	}
25491 
25492 	/*
25493 	 * Honor the RTF_SETSRC flag; this is the only case
25494 	 * where we force this addr whatever the current src addr is,
25495 	 * because this address is set by igmp_sendpkt(), and
25496 	 * cannot be specified by any user.
25497 	 */
25498 	if (ire->ire_flags & RTF_SETSRC) {
25499 		ipha->ipha_src = ire->ire_src_addr;
25500 	}
25501 
25502 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25503 }
25504 
25505 /*
25506  * NOTE : This function does not ire_refrele the ire argument passed in.
25507  *
25508  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25509  * failure. The nce_fp_mp can vanish any time in the case of
25510  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25511  * the ire_lock to access the nce_fp_mp in this case.
25512  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25513  * prepending a fastpath message IPQoS processing must precede it, we also set
25514  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25515  * (IPQoS might have set the b_band for CoS marking).
25516  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25517  * must follow it so that IPQoS can mark the dl_priority field for CoS
25518  * marking, if needed.
25519  */
25520 static mblk_t *
25521 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25522     uint32_t ill_index, ipha_t **iphap)
25523 {
25524 	uint_t	hlen;
25525 	ipha_t *ipha;
25526 	mblk_t *mp1;
25527 	boolean_t qos_done = B_FALSE;
25528 	uchar_t	*ll_hdr;
25529 	ip_stack_t	*ipst = ire->ire_ipst;
25530 
25531 #define	rptr	((uchar_t *)ipha)
25532 
25533 	ipha = (ipha_t *)mp->b_rptr;
25534 	hlen = 0;
25535 	LOCK_IRE_FP_MP(ire);
25536 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25537 		ASSERT(DB_TYPE(mp1) == M_DATA);
25538 		/* Initiate IPPF processing */
25539 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25540 			UNLOCK_IRE_FP_MP(ire);
25541 			ip_process(proc, &mp, ill_index);
25542 			if (mp == NULL)
25543 				return (NULL);
25544 
25545 			ipha = (ipha_t *)mp->b_rptr;
25546 			LOCK_IRE_FP_MP(ire);
25547 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25548 				qos_done = B_TRUE;
25549 				goto no_fp_mp;
25550 			}
25551 			ASSERT(DB_TYPE(mp1) == M_DATA);
25552 		}
25553 		hlen = MBLKL(mp1);
25554 		/*
25555 		 * Check if we have enough room to prepend fastpath
25556 		 * header
25557 		 */
25558 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25559 			ll_hdr = rptr - hlen;
25560 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25561 			/*
25562 			 * Set the b_rptr to the start of the link layer
25563 			 * header
25564 			 */
25565 			mp->b_rptr = ll_hdr;
25566 			mp1 = mp;
25567 		} else {
25568 			mp1 = copyb(mp1);
25569 			if (mp1 == NULL)
25570 				goto unlock_err;
25571 			mp1->b_band = mp->b_band;
25572 			mp1->b_cont = mp;
25573 			/*
25574 			 * XXX disable ICK_VALID and compute checksum
25575 			 * here; can happen if nce_fp_mp changes and
25576 			 * it can't be copied now due to insufficient
25577 			 * space. (unlikely, fp mp can change, but it
25578 			 * does not increase in length)
25579 			 */
25580 		}
25581 		UNLOCK_IRE_FP_MP(ire);
25582 	} else {
25583 no_fp_mp:
25584 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25585 		if (mp1 == NULL) {
25586 unlock_err:
25587 			UNLOCK_IRE_FP_MP(ire);
25588 			freemsg(mp);
25589 			return (NULL);
25590 		}
25591 		UNLOCK_IRE_FP_MP(ire);
25592 		mp1->b_cont = mp;
25593 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25594 			ip_process(proc, &mp1, ill_index);
25595 			if (mp1 == NULL)
25596 				return (NULL);
25597 
25598 			if (mp1->b_cont == NULL)
25599 				ipha = NULL;
25600 			else
25601 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25602 		}
25603 	}
25604 
25605 	*iphap = ipha;
25606 	return (mp1);
25607 #undef rptr
25608 }
25609 
25610 /*
25611  * Finish the outbound IPsec processing for an IPv6 packet. This function
25612  * is called from ipsec_out_process() if the IPsec packet was processed
25613  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25614  * asynchronously.
25615  */
25616 void
25617 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25618     ire_t *ire_arg)
25619 {
25620 	in6_addr_t *v6dstp;
25621 	ire_t *ire;
25622 	mblk_t *mp;
25623 	ip6_t *ip6h1;
25624 	uint_t	ill_index;
25625 	ipsec_out_t *io;
25626 	boolean_t hwaccel;
25627 	uint32_t flags = IP6_NO_IPPOLICY;
25628 	int match_flags;
25629 	zoneid_t zoneid;
25630 	boolean_t ill_need_rele = B_FALSE;
25631 	boolean_t ire_need_rele = B_FALSE;
25632 	ip_stack_t	*ipst;
25633 
25634 	mp = ipsec_mp->b_cont;
25635 	ip6h1 = (ip6_t *)mp->b_rptr;
25636 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25637 	ASSERT(io->ipsec_out_ns != NULL);
25638 	ipst = io->ipsec_out_ns->netstack_ip;
25639 	ill_index = io->ipsec_out_ill_index;
25640 	if (io->ipsec_out_reachable) {
25641 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25642 	}
25643 	hwaccel = io->ipsec_out_accelerated;
25644 	zoneid = io->ipsec_out_zoneid;
25645 	ASSERT(zoneid != ALL_ZONES);
25646 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25647 	/* Multicast addresses should have non-zero ill_index. */
25648 	v6dstp = &ip6h->ip6_dst;
25649 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25650 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25651 
25652 	if (ill == NULL && ill_index != 0) {
25653 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25654 		/* Failure case frees things for us. */
25655 		if (ill == NULL)
25656 			return;
25657 
25658 		ill_need_rele = B_TRUE;
25659 	}
25660 	ASSERT(mp != NULL);
25661 
25662 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25663 		boolean_t unspec_src;
25664 		ipif_t	*ipif;
25665 
25666 		/*
25667 		 * Use the ill_index to get the right ill.
25668 		 */
25669 		unspec_src = io->ipsec_out_unspec_src;
25670 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25671 		if (ipif == NULL) {
25672 			if (ill_need_rele)
25673 				ill_refrele(ill);
25674 			freemsg(ipsec_mp);
25675 			return;
25676 		}
25677 
25678 		if (ire_arg != NULL) {
25679 			ire = ire_arg;
25680 		} else {
25681 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25682 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25683 			ire_need_rele = B_TRUE;
25684 		}
25685 		if (ire != NULL) {
25686 			ipif_refrele(ipif);
25687 			/*
25688 			 * XXX Do the multicast forwarding now, as the IPsec
25689 			 * processing has been done.
25690 			 */
25691 			goto send;
25692 		}
25693 
25694 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25695 		mp->b_prev = NULL;
25696 		mp->b_next = NULL;
25697 
25698 		/*
25699 		 * If the IPsec packet was processed asynchronously,
25700 		 * drop it now.
25701 		 */
25702 		if (q == NULL) {
25703 			if (ill_need_rele)
25704 				ill_refrele(ill);
25705 			freemsg(ipsec_mp);
25706 			return;
25707 		}
25708 
25709 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25710 		    unspec_src, zoneid);
25711 		ipif_refrele(ipif);
25712 	} else {
25713 		if (ire_arg != NULL) {
25714 			ire = ire_arg;
25715 		} else {
25716 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25717 			ire_need_rele = B_TRUE;
25718 		}
25719 		if (ire != NULL)
25720 			goto send;
25721 		/*
25722 		 * ire disappeared underneath.
25723 		 *
25724 		 * What we need to do here is the ip_newroute
25725 		 * logic to get the ire without doing the IPsec
25726 		 * processing. Follow the same old path. But this
25727 		 * time, ip_wput or ire_add_then_send will call us
25728 		 * directly as all the IPsec operations are done.
25729 		 */
25730 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25731 		mp->b_prev = NULL;
25732 		mp->b_next = NULL;
25733 
25734 		/*
25735 		 * If the IPsec packet was processed asynchronously,
25736 		 * drop it now.
25737 		 */
25738 		if (q == NULL) {
25739 			if (ill_need_rele)
25740 				ill_refrele(ill);
25741 			freemsg(ipsec_mp);
25742 			return;
25743 		}
25744 
25745 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25746 		    zoneid, ipst);
25747 	}
25748 	if (ill != NULL && ill_need_rele)
25749 		ill_refrele(ill);
25750 	return;
25751 send:
25752 	if (ill != NULL && ill_need_rele)
25753 		ill_refrele(ill);
25754 
25755 	/* Local delivery */
25756 	if (ire->ire_stq == NULL) {
25757 		ill_t	*out_ill;
25758 		ASSERT(q != NULL);
25759 
25760 		/* PFHooks: LOOPBACK_OUT */
25761 		out_ill = ire_to_ill(ire);
25762 
25763 		/*
25764 		 * DTrace this as ip:::send.  A blocked packet will fire the
25765 		 * send probe, but not the receive probe.
25766 		 */
25767 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25768 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25769 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25770 
25771 		DTRACE_PROBE4(ip6__loopback__out__start,
25772 		    ill_t *, NULL, ill_t *, out_ill,
25773 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25774 
25775 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25776 		    ipst->ips_ipv6firewall_loopback_out,
25777 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25778 
25779 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25780 
25781 		if (ipsec_mp != NULL) {
25782 			ip_wput_local_v6(RD(q), out_ill,
25783 			    ip6h, ipsec_mp, ire, 0, zoneid);
25784 		}
25785 		if (ire_need_rele)
25786 			ire_refrele(ire);
25787 		return;
25788 	}
25789 	/*
25790 	 * Everything is done. Send it out on the wire.
25791 	 * We force the insertion of a fragment header using the
25792 	 * IPH_FRAG_HDR flag in two cases:
25793 	 * - after reception of an ICMPv6 "packet too big" message
25794 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25795 	 * - for multirouted IPv6 packets, so that the receiver can
25796 	 *   discard duplicates according to their fragment identifier
25797 	 */
25798 	/* XXX fix flow control problems. */
25799 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25800 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25801 		if (hwaccel) {
25802 			/*
25803 			 * hardware acceleration does not handle these
25804 			 * "slow path" cases.
25805 			 */
25806 			/* IPsec KSTATS: should bump bean counter here. */
25807 			if (ire_need_rele)
25808 				ire_refrele(ire);
25809 			freemsg(ipsec_mp);
25810 			return;
25811 		}
25812 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25813 		    (mp->b_cont ? msgdsize(mp) :
25814 		    mp->b_wptr - (uchar_t *)ip6h)) {
25815 			/* IPsec KSTATS: should bump bean counter here. */
25816 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25817 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25818 			    msgdsize(mp)));
25819 			if (ire_need_rele)
25820 				ire_refrele(ire);
25821 			freemsg(ipsec_mp);
25822 			return;
25823 		}
25824 		ASSERT(mp->b_prev == NULL);
25825 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25826 		    ntohs(ip6h->ip6_plen) +
25827 		    IPV6_HDR_LEN, ire->ire_max_frag));
25828 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25829 		    ire->ire_max_frag);
25830 	} else {
25831 		UPDATE_OB_PKT_COUNT(ire);
25832 		ire->ire_last_used_time = lbolt;
25833 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25834 	}
25835 	if (ire_need_rele)
25836 		ire_refrele(ire);
25837 	freeb(ipsec_mp);
25838 }
25839 
25840 void
25841 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25842 {
25843 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25844 	da_ipsec_t *hada;	/* data attributes */
25845 	ill_t *ill = (ill_t *)q->q_ptr;
25846 
25847 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25848 
25849 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25850 		/* IPsec KSTATS: Bump lose counter here! */
25851 		freemsg(mp);
25852 		return;
25853 	}
25854 
25855 	/*
25856 	 * It's an IPsec packet that must be
25857 	 * accelerated by the Provider, and the
25858 	 * outbound ill is IPsec acceleration capable.
25859 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25860 	 * to the ill.
25861 	 * IPsec KSTATS: should bump packet counter here.
25862 	 */
25863 
25864 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25865 	if (hada_mp == NULL) {
25866 		/* IPsec KSTATS: should bump packet counter here. */
25867 		freemsg(mp);
25868 		return;
25869 	}
25870 
25871 	hada_mp->b_datap->db_type = M_CTL;
25872 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25873 	hada_mp->b_cont = mp;
25874 
25875 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25876 	bzero(hada, sizeof (da_ipsec_t));
25877 	hada->da_type = IPHADA_M_CTL;
25878 
25879 	putnext(q, hada_mp);
25880 }
25881 
25882 /*
25883  * Finish the outbound IPsec processing. This function is called from
25884  * ipsec_out_process() if the IPsec packet was processed
25885  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25886  * asynchronously.
25887  */
25888 void
25889 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25890     ire_t *ire_arg)
25891 {
25892 	uint32_t v_hlen_tos_len;
25893 	ipaddr_t	dst;
25894 	ipif_t	*ipif = NULL;
25895 	ire_t *ire;
25896 	ire_t *ire1 = NULL;
25897 	mblk_t *next_mp = NULL;
25898 	uint32_t max_frag;
25899 	boolean_t multirt_send = B_FALSE;
25900 	mblk_t *mp;
25901 	ipha_t *ipha1;
25902 	uint_t	ill_index;
25903 	ipsec_out_t *io;
25904 	int match_flags;
25905 	irb_t *irb = NULL;
25906 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25907 	zoneid_t zoneid;
25908 	ipxmit_state_t	pktxmit_state;
25909 	ip_stack_t	*ipst;
25910 
25911 #ifdef	_BIG_ENDIAN
25912 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25913 #else
25914 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25915 #endif
25916 
25917 	mp = ipsec_mp->b_cont;
25918 	ipha1 = (ipha_t *)mp->b_rptr;
25919 	ASSERT(mp != NULL);
25920 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25921 	dst = ipha->ipha_dst;
25922 
25923 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25924 	ill_index = io->ipsec_out_ill_index;
25925 	zoneid = io->ipsec_out_zoneid;
25926 	ASSERT(zoneid != ALL_ZONES);
25927 	ipst = io->ipsec_out_ns->netstack_ip;
25928 	ASSERT(io->ipsec_out_ns != NULL);
25929 
25930 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25931 	if (ill == NULL && ill_index != 0) {
25932 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25933 		/* Failure case frees things for us. */
25934 		if (ill == NULL)
25935 			return;
25936 
25937 		ill_need_rele = B_TRUE;
25938 	}
25939 
25940 	if (CLASSD(dst)) {
25941 		boolean_t conn_dontroute;
25942 		/*
25943 		 * Use the ill_index to get the right ipif.
25944 		 */
25945 		conn_dontroute = io->ipsec_out_dontroute;
25946 		if (ill_index == 0)
25947 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25948 		else
25949 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25950 		if (ipif == NULL) {
25951 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25952 			    " multicast\n"));
25953 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25954 			freemsg(ipsec_mp);
25955 			goto done;
25956 		}
25957 		/*
25958 		 * ipha_src has already been intialized with the
25959 		 * value of the ipif in ip_wput. All we need now is
25960 		 * an ire to send this downstream.
25961 		 */
25962 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25963 		    msg_getlabel(mp), match_flags, ipst);
25964 		if (ire != NULL) {
25965 			ill_t *ill1;
25966 			/*
25967 			 * Do the multicast forwarding now, as the IPsec
25968 			 * processing has been done.
25969 			 */
25970 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25971 			    (ill1 = ire_to_ill(ire))) {
25972 				if (ip_mforward(ill1, ipha, mp)) {
25973 					freemsg(ipsec_mp);
25974 					ip1dbg(("ip_wput_ipsec_out: mforward "
25975 					    "failed\n"));
25976 					ire_refrele(ire);
25977 					goto done;
25978 				}
25979 			}
25980 			goto send;
25981 		}
25982 
25983 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25984 		mp->b_prev = NULL;
25985 		mp->b_next = NULL;
25986 
25987 		/*
25988 		 * If the IPsec packet was processed asynchronously,
25989 		 * drop it now.
25990 		 */
25991 		if (q == NULL) {
25992 			freemsg(ipsec_mp);
25993 			goto done;
25994 		}
25995 
25996 		/*
25997 		 * We may be using a wrong ipif to create the ire.
25998 		 * But it is okay as the source address is assigned
25999 		 * for the packet already. Next outbound packet would
26000 		 * create the IRE with the right IPIF in ip_wput.
26001 		 *
26002 		 * Also handle RTF_MULTIRT routes.
26003 		 */
26004 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26005 		    zoneid, &zero_info);
26006 	} else {
26007 		if (ire_arg != NULL) {
26008 			ire = ire_arg;
26009 			ire_need_rele = B_FALSE;
26010 		} else {
26011 			ire = ire_cache_lookup(dst, zoneid,
26012 			    msg_getlabel(mp), ipst);
26013 		}
26014 		if (ire != NULL) {
26015 			goto send;
26016 		}
26017 
26018 		/*
26019 		 * ire disappeared underneath.
26020 		 *
26021 		 * What we need to do here is the ip_newroute
26022 		 * logic to get the ire without doing the IPsec
26023 		 * processing. Follow the same old path. But this
26024 		 * time, ip_wput or ire_add_then_put will call us
26025 		 * directly as all the IPsec operations are done.
26026 		 */
26027 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26028 		mp->b_prev = NULL;
26029 		mp->b_next = NULL;
26030 
26031 		/*
26032 		 * If the IPsec packet was processed asynchronously,
26033 		 * drop it now.
26034 		 */
26035 		if (q == NULL) {
26036 			freemsg(ipsec_mp);
26037 			goto done;
26038 		}
26039 
26040 		/*
26041 		 * Since we're going through ip_newroute() again, we
26042 		 * need to make sure we don't:
26043 		 *
26044 		 *	1.) Trigger the ASSERT() with the ipha_ident
26045 		 *	    overloading.
26046 		 *	2.) Redo transport-layer checksumming, since we've
26047 		 *	    already done all that to get this far.
26048 		 *
26049 		 * The easiest way not do either of the above is to set
26050 		 * the ipha_ident field to IP_HDR_INCLUDED.
26051 		 */
26052 		ipha->ipha_ident = IP_HDR_INCLUDED;
26053 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26054 		    zoneid, ipst);
26055 	}
26056 	goto done;
26057 send:
26058 	if (ire->ire_stq == NULL) {
26059 		ill_t	*out_ill;
26060 		/*
26061 		 * Loopbacks go through ip_wput_local except for one case.
26062 		 * We come here if we generate a icmp_frag_needed message
26063 		 * after IPsec processing is over. When this function calls
26064 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26065 		 * icmp_frag_needed. The message generated comes back here
26066 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26067 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26068 		 * source address as it is usually set in ip_wput_ire. As
26069 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26070 		 * and we end up here. We can't enter ip_wput_ire once the
26071 		 * IPsec processing is over and hence we need to do it here.
26072 		 */
26073 		ASSERT(q != NULL);
26074 		UPDATE_OB_PKT_COUNT(ire);
26075 		ire->ire_last_used_time = lbolt;
26076 		if (ipha->ipha_src == 0)
26077 			ipha->ipha_src = ire->ire_src_addr;
26078 
26079 		/* PFHooks: LOOPBACK_OUT */
26080 		out_ill = ire_to_ill(ire);
26081 
26082 		/*
26083 		 * DTrace this as ip:::send.  A blocked packet will fire the
26084 		 * send probe, but not the receive probe.
26085 		 */
26086 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26087 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26088 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26089 
26090 		DTRACE_PROBE4(ip4__loopback__out__start,
26091 		    ill_t *, NULL, ill_t *, out_ill,
26092 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26093 
26094 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26095 		    ipst->ips_ipv4firewall_loopback_out,
26096 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26097 
26098 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26099 
26100 		if (ipsec_mp != NULL)
26101 			ip_wput_local(RD(q), out_ill,
26102 			    ipha, ipsec_mp, ire, 0, zoneid);
26103 		if (ire_need_rele)
26104 			ire_refrele(ire);
26105 		goto done;
26106 	}
26107 
26108 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26109 		/*
26110 		 * We are through with IPsec processing.
26111 		 * Fragment this and send it on the wire.
26112 		 */
26113 		if (io->ipsec_out_accelerated) {
26114 			/*
26115 			 * The packet has been accelerated but must
26116 			 * be fragmented. This should not happen
26117 			 * since AH and ESP must not accelerate
26118 			 * packets that need fragmentation, however
26119 			 * the configuration could have changed
26120 			 * since the AH or ESP processing.
26121 			 * Drop packet.
26122 			 * IPsec KSTATS: bump bean counter here.
26123 			 */
26124 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26125 			    "fragmented accelerated packet!\n"));
26126 			freemsg(ipsec_mp);
26127 		} else {
26128 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26129 			    zoneid, ipst, NULL);
26130 		}
26131 		if (ire_need_rele)
26132 			ire_refrele(ire);
26133 		goto done;
26134 	}
26135 
26136 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26137 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26138 	    (void *)ire->ire_ipif, (void *)ipif));
26139 
26140 	/*
26141 	 * Multiroute the secured packet.
26142 	 */
26143 	if (ire->ire_flags & RTF_MULTIRT) {
26144 		ire_t *first_ire;
26145 		irb = ire->ire_bucket;
26146 		ASSERT(irb != NULL);
26147 		/*
26148 		 * This ire has been looked up as the one that
26149 		 * goes through the given ipif;
26150 		 * make sure we do not omit any other multiroute ire
26151 		 * that may be present in the bucket before this one.
26152 		 */
26153 		IRB_REFHOLD(irb);
26154 		for (first_ire = irb->irb_ire;
26155 		    first_ire != NULL;
26156 		    first_ire = first_ire->ire_next) {
26157 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26158 			    (first_ire->ire_addr == ire->ire_addr) &&
26159 			    !(first_ire->ire_marks &
26160 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26161 				break;
26162 		}
26163 
26164 		if ((first_ire != NULL) && (first_ire != ire)) {
26165 			/*
26166 			 * Don't change the ire if the packet must
26167 			 * be fragmented if sent via this new one.
26168 			 */
26169 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26170 				IRE_REFHOLD(first_ire);
26171 				if (ire_need_rele)
26172 					ire_refrele(ire);
26173 				else
26174 					ire_need_rele = B_TRUE;
26175 				ire = first_ire;
26176 			}
26177 		}
26178 		IRB_REFRELE(irb);
26179 
26180 		multirt_send = B_TRUE;
26181 		max_frag = ire->ire_max_frag;
26182 	}
26183 
26184 	/*
26185 	 * In most cases, the emission loop below is entered only once.
26186 	 * Only in the case where the ire holds the RTF_MULTIRT
26187 	 * flag, we loop to process all RTF_MULTIRT ires in the
26188 	 * bucket, and send the packet through all crossed
26189 	 * RTF_MULTIRT routes.
26190 	 */
26191 	do {
26192 		if (multirt_send) {
26193 			/*
26194 			 * ire1 holds here the next ire to process in the
26195 			 * bucket. If multirouting is expected,
26196 			 * any non-RTF_MULTIRT ire that has the
26197 			 * right destination address is ignored.
26198 			 */
26199 			ASSERT(irb != NULL);
26200 			IRB_REFHOLD(irb);
26201 			for (ire1 = ire->ire_next;
26202 			    ire1 != NULL;
26203 			    ire1 = ire1->ire_next) {
26204 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26205 					continue;
26206 				if (ire1->ire_addr != ire->ire_addr)
26207 					continue;
26208 				if (ire1->ire_marks &
26209 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26210 					continue;
26211 				/* No loopback here */
26212 				if (ire1->ire_stq == NULL)
26213 					continue;
26214 				/*
26215 				 * Ensure we do not exceed the MTU
26216 				 * of the next route.
26217 				 */
26218 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26219 					ip_multirt_bad_mtu(ire1, max_frag);
26220 					continue;
26221 				}
26222 
26223 				IRE_REFHOLD(ire1);
26224 				break;
26225 			}
26226 			IRB_REFRELE(irb);
26227 			if (ire1 != NULL) {
26228 				/*
26229 				 * We are in a multiple send case, need to
26230 				 * make a copy of the packet.
26231 				 */
26232 				next_mp = copymsg(ipsec_mp);
26233 				if (next_mp == NULL) {
26234 					ire_refrele(ire1);
26235 					ire1 = NULL;
26236 				}
26237 			}
26238 		}
26239 		/*
26240 		 * Everything is done. Send it out on the wire
26241 		 *
26242 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26243 		 * either send it on the wire or, in the case of
26244 		 * HW acceleration, call ipsec_hw_putnext.
26245 		 */
26246 		if (ire->ire_nce &&
26247 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26248 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26249 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26250 			/*
26251 			 * If ire's link-layer is unresolved (this
26252 			 * would only happen if the incomplete ire
26253 			 * was added to cachetable via forwarding path)
26254 			 * don't bother going to ip_xmit_v4. Just drop the
26255 			 * packet.
26256 			 * There is a slight risk here, in that, if we
26257 			 * have the forwarding path create an incomplete
26258 			 * IRE, then until the IRE is completed, any
26259 			 * transmitted IPsec packets will be dropped
26260 			 * instead of being queued waiting for resolution.
26261 			 *
26262 			 * But the likelihood of a forwarding packet and a wput
26263 			 * packet sending to the same dst at the same time
26264 			 * and there not yet be an ARP entry for it is small.
26265 			 * Furthermore, if this actually happens, it might
26266 			 * be likely that wput would generate multiple
26267 			 * packets (and forwarding would also have a train
26268 			 * of packets) for that destination. If this is
26269 			 * the case, some of them would have been dropped
26270 			 * anyway, since ARP only queues a few packets while
26271 			 * waiting for resolution
26272 			 *
26273 			 * NOTE: We should really call ip_xmit_v4,
26274 			 * and let it queue the packet and send the
26275 			 * ARP query and have ARP come back thus:
26276 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26277 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26278 			 * hw accel work. But it's too complex to get
26279 			 * the IPsec hw  acceleration approach to fit
26280 			 * well with ip_xmit_v4 doing ARP without
26281 			 * doing IPsec simplification. For now, we just
26282 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26283 			 * that we can continue with the send on the next
26284 			 * attempt.
26285 			 *
26286 			 * XXX THis should be revisited, when
26287 			 * the IPsec/IP interaction is cleaned up
26288 			 */
26289 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26290 			    " - dropping packet\n"));
26291 			freemsg(ipsec_mp);
26292 			/*
26293 			 * Call ip_xmit_v4() to trigger ARP query
26294 			 * in case the nce_state is ND_INITIAL
26295 			 */
26296 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26297 			goto drop_pkt;
26298 		}
26299 
26300 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26301 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26302 		    mblk_t *, ipsec_mp);
26303 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26304 		    ipst->ips_ipv4firewall_physical_out, NULL,
26305 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26306 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26307 		if (ipsec_mp == NULL)
26308 			goto drop_pkt;
26309 
26310 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26311 		pktxmit_state = ip_xmit_v4(mp, ire,
26312 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26313 
26314 		if ((pktxmit_state ==  SEND_FAILED) ||
26315 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26316 
26317 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26318 drop_pkt:
26319 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26320 			    ipIfStatsOutDiscards);
26321 			if (ire_need_rele)
26322 				ire_refrele(ire);
26323 			if (ire1 != NULL) {
26324 				ire_refrele(ire1);
26325 				freemsg(next_mp);
26326 			}
26327 			goto done;
26328 		}
26329 
26330 		freeb(ipsec_mp);
26331 		if (ire_need_rele)
26332 			ire_refrele(ire);
26333 
26334 		if (ire1 != NULL) {
26335 			ire = ire1;
26336 			ire_need_rele = B_TRUE;
26337 			ASSERT(next_mp);
26338 			ipsec_mp = next_mp;
26339 			mp = ipsec_mp->b_cont;
26340 			ire1 = NULL;
26341 			next_mp = NULL;
26342 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26343 		} else {
26344 			multirt_send = B_FALSE;
26345 		}
26346 	} while (multirt_send);
26347 done:
26348 	if (ill != NULL && ill_need_rele)
26349 		ill_refrele(ill);
26350 	if (ipif != NULL)
26351 		ipif_refrele(ipif);
26352 }
26353 
26354 /*
26355  * Get the ill corresponding to the specified ire, and compare its
26356  * capabilities with the protocol and algorithms specified by the
26357  * the SA obtained from ipsec_out. If they match, annotate the
26358  * ipsec_out structure to indicate that the packet needs acceleration.
26359  *
26360  *
26361  * A packet is eligible for outbound hardware acceleration if the
26362  * following conditions are satisfied:
26363  *
26364  * 1. the packet will not be fragmented
26365  * 2. the provider supports the algorithm
26366  * 3. there is no pending control message being exchanged
26367  * 4. snoop is not attached
26368  * 5. the destination address is not a broadcast or multicast address.
26369  *
26370  * Rationale:
26371  *	- Hardware drivers do not support fragmentation with
26372  *	  the current interface.
26373  *	- snoop, multicast, and broadcast may result in exposure of
26374  *	  a cleartext datagram.
26375  * We check all five of these conditions here.
26376  *
26377  * XXX would like to nuke "ire_t *" parameter here; problem is that
26378  * IRE is only way to figure out if a v4 address is a broadcast and
26379  * thus ineligible for acceleration...
26380  */
26381 static void
26382 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26383 {
26384 	ipsec_out_t *io;
26385 	mblk_t *data_mp;
26386 	uint_t plen, overhead;
26387 	ip_stack_t	*ipst;
26388 
26389 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26390 		return;
26391 
26392 	if (ill == NULL)
26393 		return;
26394 	ipst = ill->ill_ipst;
26395 	/*
26396 	 * Destination address is a broadcast or multicast.  Punt.
26397 	 */
26398 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26399 	    IRE_LOCAL)))
26400 		return;
26401 
26402 	data_mp = ipsec_mp->b_cont;
26403 
26404 	if (ill->ill_isv6) {
26405 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26406 
26407 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26408 			return;
26409 
26410 		plen = ip6h->ip6_plen;
26411 	} else {
26412 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26413 
26414 		if (CLASSD(ipha->ipha_dst))
26415 			return;
26416 
26417 		plen = ipha->ipha_length;
26418 	}
26419 	/*
26420 	 * Is there a pending DLPI control message being exchanged
26421 	 * between IP/IPsec and the DLS Provider? If there is, it
26422 	 * could be a SADB update, and the state of the DLS Provider
26423 	 * SADB might not be in sync with the SADB maintained by
26424 	 * IPsec. To avoid dropping packets or using the wrong keying
26425 	 * material, we do not accelerate this packet.
26426 	 */
26427 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26428 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26429 		    "ill_dlpi_pending! don't accelerate packet\n"));
26430 		return;
26431 	}
26432 
26433 	/*
26434 	 * Is the Provider in promiscous mode? If it does, we don't
26435 	 * accelerate the packet since it will bounce back up to the
26436 	 * listeners in the clear.
26437 	 */
26438 	if (ill->ill_promisc_on_phys) {
26439 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26440 		    "ill in promiscous mode, don't accelerate packet\n"));
26441 		return;
26442 	}
26443 
26444 	/*
26445 	 * Will the packet require fragmentation?
26446 	 */
26447 
26448 	/*
26449 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26450 	 * as is used elsewhere.
26451 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26452 	 *	+ 2-byte trailer
26453 	 */
26454 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26455 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26456 
26457 	if ((plen + overhead) > ill->ill_max_mtu)
26458 		return;
26459 
26460 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26461 
26462 	/*
26463 	 * Can the ill accelerate this IPsec protocol and algorithm
26464 	 * specified by the SA?
26465 	 */
26466 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26467 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26468 		return;
26469 	}
26470 
26471 	/*
26472 	 * Tell AH or ESP that the outbound ill is capable of
26473 	 * accelerating this packet.
26474 	 */
26475 	io->ipsec_out_is_capab_ill = B_TRUE;
26476 }
26477 
26478 /*
26479  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26480  *
26481  * If this function returns B_TRUE, the requested SA's have been filled
26482  * into the ipsec_out_*_sa pointers.
26483  *
26484  * If the function returns B_FALSE, the packet has been "consumed", most
26485  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26486  *
26487  * The SA references created by the protocol-specific "select"
26488  * function will be released when the ipsec_mp is freed, thanks to the
26489  * ipsec_out_free destructor -- see spd.c.
26490  */
26491 static boolean_t
26492 ipsec_out_select_sa(mblk_t *ipsec_mp)
26493 {
26494 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26495 	ipsec_out_t *io;
26496 	ipsec_policy_t *pp;
26497 	ipsec_action_t *ap;
26498 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26499 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26500 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26501 
26502 	if (!io->ipsec_out_secure) {
26503 		/*
26504 		 * We came here by mistake.
26505 		 * Don't bother with ipsec processing
26506 		 * We should "discourage" this path in the future.
26507 		 */
26508 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26509 		return (B_FALSE);
26510 	}
26511 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26512 	ASSERT((io->ipsec_out_policy != NULL) ||
26513 	    (io->ipsec_out_act != NULL));
26514 
26515 	ASSERT(io->ipsec_out_failed == B_FALSE);
26516 
26517 	/*
26518 	 * IPsec processing has started.
26519 	 */
26520 	io->ipsec_out_proc_begin = B_TRUE;
26521 	ap = io->ipsec_out_act;
26522 	if (ap == NULL) {
26523 		pp = io->ipsec_out_policy;
26524 		ASSERT(pp != NULL);
26525 		ap = pp->ipsp_act;
26526 		ASSERT(ap != NULL);
26527 	}
26528 
26529 	/*
26530 	 * We have an action.  now, let's select SA's.
26531 	 * (In the future, we can cache this in the conn_t..)
26532 	 */
26533 	if (ap->ipa_want_esp) {
26534 		if (io->ipsec_out_esp_sa == NULL) {
26535 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26536 			    IPPROTO_ESP);
26537 		}
26538 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26539 	}
26540 
26541 	if (ap->ipa_want_ah) {
26542 		if (io->ipsec_out_ah_sa == NULL) {
26543 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26544 			    IPPROTO_AH);
26545 		}
26546 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26547 		/*
26548 		 * The ESP and AH processing order needs to be preserved
26549 		 * when both protocols are required (ESP should be applied
26550 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26551 		 * when both ESP and AH are required, and an AH ACQUIRE
26552 		 * is needed.
26553 		 */
26554 		if (ap->ipa_want_esp && need_ah_acquire)
26555 			need_esp_acquire = B_TRUE;
26556 	}
26557 
26558 	/*
26559 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26560 	 * Release SAs that got referenced, but will not be used until we
26561 	 * acquire _all_ of the SAs we need.
26562 	 */
26563 	if (need_ah_acquire || need_esp_acquire) {
26564 		if (io->ipsec_out_ah_sa != NULL) {
26565 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26566 			io->ipsec_out_ah_sa = NULL;
26567 		}
26568 		if (io->ipsec_out_esp_sa != NULL) {
26569 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26570 			io->ipsec_out_esp_sa = NULL;
26571 		}
26572 
26573 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26574 		return (B_FALSE);
26575 	}
26576 
26577 	return (B_TRUE);
26578 }
26579 
26580 /*
26581  * Process an IPSEC_OUT message and see what you can
26582  * do with it.
26583  * IPQoS Notes:
26584  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26585  * IPsec.
26586  * XXX would like to nuke ire_t.
26587  * XXX ill_index better be "real"
26588  */
26589 void
26590 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26591 {
26592 	ipsec_out_t *io;
26593 	ipsec_policy_t *pp;
26594 	ipsec_action_t *ap;
26595 	ipha_t *ipha;
26596 	ip6_t *ip6h;
26597 	mblk_t *mp;
26598 	ill_t *ill;
26599 	zoneid_t zoneid;
26600 	ipsec_status_t ipsec_rc;
26601 	boolean_t ill_need_rele = B_FALSE;
26602 	ip_stack_t	*ipst;
26603 	ipsec_stack_t	*ipss;
26604 
26605 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26606 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26607 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26608 	ipst = io->ipsec_out_ns->netstack_ip;
26609 	mp = ipsec_mp->b_cont;
26610 
26611 	/*
26612 	 * Initiate IPPF processing. We do it here to account for packets
26613 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26614 	 * We can check for ipsec_out_proc_begin even for such packets, as
26615 	 * they will always be false (asserted below).
26616 	 */
26617 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26618 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26619 		    io->ipsec_out_ill_index : ill_index);
26620 		if (mp == NULL) {
26621 			ip2dbg(("ipsec_out_process: packet dropped "\
26622 			    "during IPPF processing\n"));
26623 			freeb(ipsec_mp);
26624 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26625 			return;
26626 		}
26627 	}
26628 
26629 	if (!io->ipsec_out_secure) {
26630 		/*
26631 		 * We came here by mistake.
26632 		 * Don't bother with ipsec processing
26633 		 * Should "discourage" this path in the future.
26634 		 */
26635 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26636 		goto done;
26637 	}
26638 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26639 	ASSERT((io->ipsec_out_policy != NULL) ||
26640 	    (io->ipsec_out_act != NULL));
26641 	ASSERT(io->ipsec_out_failed == B_FALSE);
26642 
26643 	ipss = ipst->ips_netstack->netstack_ipsec;
26644 	if (!ipsec_loaded(ipss)) {
26645 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26646 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26647 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26648 		} else {
26649 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26650 		}
26651 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26652 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26653 		    &ipss->ipsec_dropper);
26654 		return;
26655 	}
26656 
26657 	/*
26658 	 * IPsec processing has started.
26659 	 */
26660 	io->ipsec_out_proc_begin = B_TRUE;
26661 	ap = io->ipsec_out_act;
26662 	if (ap == NULL) {
26663 		pp = io->ipsec_out_policy;
26664 		ASSERT(pp != NULL);
26665 		ap = pp->ipsp_act;
26666 		ASSERT(ap != NULL);
26667 	}
26668 
26669 	/*
26670 	 * Save the outbound ill index. When the packet comes back
26671 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26672 	 * before sending it the accelerated packet.
26673 	 */
26674 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26675 		ill = ire_to_ill(ire);
26676 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26677 	}
26678 
26679 	/*
26680 	 * The order of processing is first insert a IP header if needed.
26681 	 * Then insert the ESP header and then the AH header.
26682 	 */
26683 	if ((io->ipsec_out_se_done == B_FALSE) &&
26684 	    (ap->ipa_want_se)) {
26685 		/*
26686 		 * First get the outer IP header before sending
26687 		 * it to ESP.
26688 		 */
26689 		ipha_t *oipha, *iipha;
26690 		mblk_t *outer_mp, *inner_mp;
26691 
26692 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26693 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26694 			    "ipsec_out_process: "
26695 			    "Self-Encapsulation failed: Out of memory\n");
26696 			freemsg(ipsec_mp);
26697 			if (ill != NULL) {
26698 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26699 			} else {
26700 				BUMP_MIB(&ipst->ips_ip_mib,
26701 				    ipIfStatsOutDiscards);
26702 			}
26703 			return;
26704 		}
26705 		inner_mp = ipsec_mp->b_cont;
26706 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26707 		oipha = (ipha_t *)outer_mp->b_rptr;
26708 		iipha = (ipha_t *)inner_mp->b_rptr;
26709 		*oipha = *iipha;
26710 		outer_mp->b_wptr += sizeof (ipha_t);
26711 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26712 		    sizeof (ipha_t));
26713 		oipha->ipha_protocol = IPPROTO_ENCAP;
26714 		oipha->ipha_version_and_hdr_length =
26715 		    IP_SIMPLE_HDR_VERSION;
26716 		oipha->ipha_hdr_checksum = 0;
26717 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26718 		outer_mp->b_cont = inner_mp;
26719 		ipsec_mp->b_cont = outer_mp;
26720 
26721 		io->ipsec_out_se_done = B_TRUE;
26722 		io->ipsec_out_tunnel = B_TRUE;
26723 	}
26724 
26725 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26726 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26727 	    !ipsec_out_select_sa(ipsec_mp))
26728 		return;
26729 
26730 	/*
26731 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26732 	 * to do the heavy lifting.
26733 	 */
26734 	zoneid = io->ipsec_out_zoneid;
26735 	ASSERT(zoneid != ALL_ZONES);
26736 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26737 		ASSERT(io->ipsec_out_esp_sa != NULL);
26738 		io->ipsec_out_esp_done = B_TRUE;
26739 		/*
26740 		 * Note that since hw accel can only apply one transform,
26741 		 * not two, we skip hw accel for ESP if we also have AH
26742 		 * This is an design limitation of the interface
26743 		 * which should be revisited.
26744 		 */
26745 		ASSERT(ire != NULL);
26746 		if (io->ipsec_out_ah_sa == NULL) {
26747 			ill = (ill_t *)ire->ire_stq->q_ptr;
26748 			ipsec_out_is_accelerated(ipsec_mp,
26749 			    io->ipsec_out_esp_sa, ill, ire);
26750 		}
26751 
26752 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26753 		switch (ipsec_rc) {
26754 		case IPSEC_STATUS_SUCCESS:
26755 			break;
26756 		case IPSEC_STATUS_FAILED:
26757 			if (ill != NULL) {
26758 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26759 			} else {
26760 				BUMP_MIB(&ipst->ips_ip_mib,
26761 				    ipIfStatsOutDiscards);
26762 			}
26763 			/* FALLTHRU */
26764 		case IPSEC_STATUS_PENDING:
26765 			return;
26766 		}
26767 	}
26768 
26769 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26770 		ASSERT(io->ipsec_out_ah_sa != NULL);
26771 		io->ipsec_out_ah_done = B_TRUE;
26772 		if (ire == NULL) {
26773 			int idx = io->ipsec_out_capab_ill_index;
26774 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26775 			    NULL, NULL, NULL, NULL, ipst);
26776 			ill_need_rele = B_TRUE;
26777 		} else {
26778 			ill = (ill_t *)ire->ire_stq->q_ptr;
26779 		}
26780 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26781 		    ire);
26782 
26783 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26784 		switch (ipsec_rc) {
26785 		case IPSEC_STATUS_SUCCESS:
26786 			break;
26787 		case IPSEC_STATUS_FAILED:
26788 			if (ill != NULL) {
26789 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26790 			} else {
26791 				BUMP_MIB(&ipst->ips_ip_mib,
26792 				    ipIfStatsOutDiscards);
26793 			}
26794 			/* FALLTHRU */
26795 		case IPSEC_STATUS_PENDING:
26796 			if (ill != NULL && ill_need_rele)
26797 				ill_refrele(ill);
26798 			return;
26799 		}
26800 	}
26801 	/*
26802 	 * We are done with IPsec processing. Send it over the wire.
26803 	 */
26804 done:
26805 	mp = ipsec_mp->b_cont;
26806 	ipha = (ipha_t *)mp->b_rptr;
26807 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26808 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26809 		    ire);
26810 	} else {
26811 		ip6h = (ip6_t *)ipha;
26812 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26813 		    ire);
26814 	}
26815 	if (ill != NULL && ill_need_rele)
26816 		ill_refrele(ill);
26817 }
26818 
26819 /* ARGSUSED */
26820 void
26821 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26822 {
26823 	opt_restart_t	*or;
26824 	int	err;
26825 	conn_t	*connp;
26826 	cred_t	*cr;
26827 
26828 	ASSERT(CONN_Q(q));
26829 	connp = Q_TO_CONN(q);
26830 
26831 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26832 	or = (opt_restart_t *)first_mp->b_rptr;
26833 	/*
26834 	 * We checked for a db_credp the first time svr4_optcom_req
26835 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26836 	 */
26837 	cr = msg_getcred(first_mp, NULL);
26838 	ASSERT(cr != NULL);
26839 
26840 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26841 		err = svr4_optcom_req(q, first_mp, cr,
26842 		    &ip_opt_obj, B_FALSE);
26843 	} else {
26844 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26845 		err = tpi_optcom_req(q, first_mp, cr,
26846 		    &ip_opt_obj, B_FALSE);
26847 	}
26848 	if (err != EINPROGRESS) {
26849 		/* operation is done */
26850 		CONN_OPER_PENDING_DONE(connp);
26851 	}
26852 }
26853 
26854 /*
26855  * ioctls that go through a down/up sequence may need to wait for the down
26856  * to complete. This involves waiting for the ire and ipif refcnts to go down
26857  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26858  */
26859 /* ARGSUSED */
26860 void
26861 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26862 {
26863 	struct iocblk *iocp;
26864 	mblk_t *mp1;
26865 	ip_ioctl_cmd_t *ipip;
26866 	int err;
26867 	sin_t	*sin;
26868 	struct lifreq *lifr;
26869 	struct ifreq *ifr;
26870 
26871 	iocp = (struct iocblk *)mp->b_rptr;
26872 	ASSERT(ipsq != NULL);
26873 	/* Existence of mp1 verified in ip_wput_nondata */
26874 	mp1 = mp->b_cont->b_cont;
26875 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26876 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26877 		/*
26878 		 * Special case where ipx_current_ipif is not set:
26879 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26880 		 * We are here as were not able to complete the operation in
26881 		 * ipif_set_values because we could not become exclusive on
26882 		 * the new ipsq.
26883 		 */
26884 		ill_t *ill = q->q_ptr;
26885 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26886 	}
26887 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26888 
26889 	if (ipip->ipi_cmd_type == IF_CMD) {
26890 		/* This a old style SIOC[GS]IF* command */
26891 		ifr = (struct ifreq *)mp1->b_rptr;
26892 		sin = (sin_t *)&ifr->ifr_addr;
26893 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26894 		/* This a new style SIOC[GS]LIF* command */
26895 		lifr = (struct lifreq *)mp1->b_rptr;
26896 		sin = (sin_t *)&lifr->lifr_addr;
26897 	} else {
26898 		sin = NULL;
26899 	}
26900 
26901 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26902 	    q, mp, ipip, mp1->b_rptr);
26903 
26904 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26905 }
26906 
26907 /*
26908  * ioctl processing
26909  *
26910  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26911  * the ioctl command in the ioctl tables, determines the copyin data size
26912  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26913  *
26914  * ioctl processing then continues when the M_IOCDATA makes its way down to
26915  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26916  * associated 'conn' is refheld till the end of the ioctl and the general
26917  * ioctl processing function ip_process_ioctl() is called to extract the
26918  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26919  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26920  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26921  * is used to extract the ioctl's arguments.
26922  *
26923  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26924  * so goes thru the serialization primitive ipsq_try_enter. Then the
26925  * appropriate function to handle the ioctl is called based on the entry in
26926  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26927  * which also refreleases the 'conn' that was refheld at the start of the
26928  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26929  *
26930  * Many exclusive ioctls go thru an internal down up sequence as part of
26931  * the operation. For example an attempt to change the IP address of an
26932  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26933  * does all the cleanup such as deleting all ires that use this address.
26934  * Then we need to wait till all references to the interface go away.
26935  */
26936 void
26937 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26938 {
26939 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26940 	ip_ioctl_cmd_t *ipip = arg;
26941 	ip_extract_func_t *extract_funcp;
26942 	cmd_info_t ci;
26943 	int err;
26944 	boolean_t entered_ipsq = B_FALSE;
26945 
26946 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26947 
26948 	if (ipip == NULL)
26949 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26950 
26951 	/*
26952 	 * SIOCLIFADDIF needs to go thru a special path since the
26953 	 * ill may not exist yet. This happens in the case of lo0
26954 	 * which is created using this ioctl.
26955 	 */
26956 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26957 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26958 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26959 		return;
26960 	}
26961 
26962 	ci.ci_ipif = NULL;
26963 	if (ipip->ipi_cmd_type == MISC_CMD) {
26964 		/*
26965 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26966 		 */
26967 		if (ipip->ipi_cmd == IF_UNITSEL) {
26968 			/* ioctl comes down the ill */
26969 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26970 			ipif_refhold(ci.ci_ipif);
26971 		}
26972 		err = 0;
26973 		ci.ci_sin = NULL;
26974 		ci.ci_sin6 = NULL;
26975 		ci.ci_lifr = NULL;
26976 	} else {
26977 		switch (ipip->ipi_cmd_type) {
26978 		case IF_CMD:
26979 		case LIF_CMD:
26980 			extract_funcp = ip_extract_lifreq;
26981 			break;
26982 
26983 		case ARP_CMD:
26984 		case XARP_CMD:
26985 			extract_funcp = ip_extract_arpreq;
26986 			break;
26987 
26988 		case TUN_CMD:
26989 			extract_funcp = ip_extract_tunreq;
26990 			break;
26991 
26992 		case MSFILT_CMD:
26993 			extract_funcp = ip_extract_msfilter;
26994 			break;
26995 
26996 		default:
26997 			ASSERT(0);
26998 		}
26999 
27000 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27001 		if (err != 0) {
27002 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27003 			return;
27004 		}
27005 
27006 		/*
27007 		 * All of the extraction functions return a refheld ipif.
27008 		 */
27009 		ASSERT(ci.ci_ipif != NULL);
27010 	}
27011 
27012 	if (!(ipip->ipi_flags & IPI_WR)) {
27013 		/*
27014 		 * A return value of EINPROGRESS means the ioctl is
27015 		 * either queued and waiting for some reason or has
27016 		 * already completed.
27017 		 */
27018 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27019 		    ci.ci_lifr);
27020 		if (ci.ci_ipif != NULL)
27021 			ipif_refrele(ci.ci_ipif);
27022 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27023 		return;
27024 	}
27025 
27026 	ASSERT(ci.ci_ipif != NULL);
27027 
27028 	/*
27029 	 * If ipsq is non-NULL, we are already being called exclusively.
27030 	 */
27031 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27032 	if (ipsq == NULL) {
27033 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27034 		    NEW_OP, B_TRUE);
27035 		if (ipsq == NULL) {
27036 			ipif_refrele(ci.ci_ipif);
27037 			return;
27038 		}
27039 		entered_ipsq = B_TRUE;
27040 	}
27041 
27042 	/*
27043 	 * Release the ipif so that ipif_down and friends that wait for
27044 	 * references to go away are not misled about the current ipif_refcnt
27045 	 * values. We are writer so we can access the ipif even after releasing
27046 	 * the ipif.
27047 	 */
27048 	ipif_refrele(ci.ci_ipif);
27049 
27050 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27051 
27052 	/*
27053 	 * A return value of EINPROGRESS means the ioctl is
27054 	 * either queued and waiting for some reason or has
27055 	 * already completed.
27056 	 */
27057 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27058 
27059 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27060 
27061 	if (entered_ipsq)
27062 		ipsq_exit(ipsq);
27063 }
27064 
27065 /*
27066  * Complete the ioctl. Typically ioctls use the mi package and need to
27067  * do mi_copyout/mi_copy_done.
27068  */
27069 void
27070 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27071 {
27072 	conn_t	*connp = NULL;
27073 
27074 	if (err == EINPROGRESS)
27075 		return;
27076 
27077 	if (CONN_Q(q)) {
27078 		connp = Q_TO_CONN(q);
27079 		ASSERT(connp->conn_ref >= 2);
27080 	}
27081 
27082 	switch (mode) {
27083 	case COPYOUT:
27084 		if (err == 0)
27085 			mi_copyout(q, mp);
27086 		else
27087 			mi_copy_done(q, mp, err);
27088 		break;
27089 
27090 	case NO_COPYOUT:
27091 		mi_copy_done(q, mp, err);
27092 		break;
27093 
27094 	default:
27095 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27096 		break;
27097 	}
27098 
27099 	/*
27100 	 * The refhold placed at the start of the ioctl is released here.
27101 	 */
27102 	if (connp != NULL)
27103 		CONN_OPER_PENDING_DONE(connp);
27104 
27105 	if (ipsq != NULL)
27106 		ipsq_current_finish(ipsq);
27107 }
27108 
27109 /* Called from ip_wput for all non data messages */
27110 /* ARGSUSED */
27111 void
27112 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27113 {
27114 	mblk_t		*mp1;
27115 	ire_t		*ire, *fake_ire;
27116 	ill_t		*ill;
27117 	struct iocblk	*iocp;
27118 	ip_ioctl_cmd_t	*ipip;
27119 	cred_t		*cr;
27120 	conn_t		*connp;
27121 	int		err;
27122 	nce_t		*nce;
27123 	ipif_t		*ipif;
27124 	ip_stack_t	*ipst;
27125 	char		*proto_str;
27126 
27127 	if (CONN_Q(q)) {
27128 		connp = Q_TO_CONN(q);
27129 		ipst = connp->conn_netstack->netstack_ip;
27130 	} else {
27131 		connp = NULL;
27132 		ipst = ILLQ_TO_IPST(q);
27133 	}
27134 
27135 	switch (DB_TYPE(mp)) {
27136 	case M_IOCTL:
27137 		/*
27138 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27139 		 * will arrange to copy in associated control structures.
27140 		 */
27141 		ip_sioctl_copyin_setup(q, mp);
27142 		return;
27143 	case M_IOCDATA:
27144 		/*
27145 		 * Ensure that this is associated with one of our trans-
27146 		 * parent ioctls.  If it's not ours, discard it if we're
27147 		 * running as a driver, or pass it on if we're a module.
27148 		 */
27149 		iocp = (struct iocblk *)mp->b_rptr;
27150 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27151 		if (ipip == NULL) {
27152 			if (q->q_next == NULL) {
27153 				goto nak;
27154 			} else {
27155 				putnext(q, mp);
27156 			}
27157 			return;
27158 		}
27159 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27160 			/*
27161 			 * the ioctl is one we recognise, but is not
27162 			 * consumed by IP as a module, pass M_IOCDATA
27163 			 * for processing downstream, but only for
27164 			 * common Streams ioctls.
27165 			 */
27166 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27167 				putnext(q, mp);
27168 				return;
27169 			} else {
27170 				goto nak;
27171 			}
27172 		}
27173 
27174 		/* IOCTL continuation following copyin or copyout. */
27175 		if (mi_copy_state(q, mp, NULL) == -1) {
27176 			/*
27177 			 * The copy operation failed.  mi_copy_state already
27178 			 * cleaned up, so we're out of here.
27179 			 */
27180 			return;
27181 		}
27182 		/*
27183 		 * If we just completed a copy in, we become writer and
27184 		 * continue processing in ip_sioctl_copyin_done.  If it
27185 		 * was a copy out, we call mi_copyout again.  If there is
27186 		 * nothing more to copy out, it will complete the IOCTL.
27187 		 */
27188 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27189 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27190 				mi_copy_done(q, mp, EPROTO);
27191 				return;
27192 			}
27193 			/*
27194 			 * Check for cases that need more copying.  A return
27195 			 * value of 0 means a second copyin has been started,
27196 			 * so we return; a return value of 1 means no more
27197 			 * copying is needed, so we continue.
27198 			 */
27199 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27200 			    MI_COPY_COUNT(mp) == 1) {
27201 				if (ip_copyin_msfilter(q, mp) == 0)
27202 					return;
27203 			}
27204 			/*
27205 			 * Refhold the conn, till the ioctl completes. This is
27206 			 * needed in case the ioctl ends up in the pending mp
27207 			 * list. Every mp in the ill_pending_mp list and
27208 			 * the ipx_pending_mp must have a refhold on the conn
27209 			 * to resume processing. The refhold is released when
27210 			 * the ioctl completes. (normally or abnormally)
27211 			 * In all cases ip_ioctl_finish is called to finish
27212 			 * the ioctl.
27213 			 */
27214 			if (connp != NULL) {
27215 				/* This is not a reentry */
27216 				ASSERT(ipsq == NULL);
27217 				CONN_INC_REF(connp);
27218 			} else {
27219 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27220 					mi_copy_done(q, mp, EINVAL);
27221 					return;
27222 				}
27223 			}
27224 
27225 			ip_process_ioctl(ipsq, q, mp, ipip);
27226 
27227 		} else {
27228 			mi_copyout(q, mp);
27229 		}
27230 		return;
27231 nak:
27232 		iocp->ioc_error = EINVAL;
27233 		mp->b_datap->db_type = M_IOCNAK;
27234 		iocp->ioc_count = 0;
27235 		qreply(q, mp);
27236 		return;
27237 
27238 	case M_IOCNAK:
27239 		/*
27240 		 * The only way we could get here is if a resolver didn't like
27241 		 * an IOCTL we sent it.	 This shouldn't happen.
27242 		 */
27243 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27244 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27245 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27246 		freemsg(mp);
27247 		return;
27248 	case M_IOCACK:
27249 		/* /dev/ip shouldn't see this */
27250 		if (CONN_Q(q))
27251 			goto nak;
27252 
27253 		/*
27254 		 * Finish socket ioctls passed through to ARP.  We use the
27255 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27256 		 * we need to become writer before calling ip_sioctl_iocack().
27257 		 * Note that qwriter_ip() will release the refhold, and that a
27258 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27259 		 * ill stream.
27260 		 */
27261 		iocp = (struct iocblk *)mp->b_rptr;
27262 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27263 			ip_sioctl_iocack(NULL, q, mp, NULL);
27264 			return;
27265 		}
27266 
27267 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27268 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27269 		ill = q->q_ptr;
27270 		ill_refhold(ill);
27271 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27272 		return;
27273 	case M_FLUSH:
27274 		if (*mp->b_rptr & FLUSHW)
27275 			flushq(q, FLUSHALL);
27276 		if (q->q_next) {
27277 			putnext(q, mp);
27278 			return;
27279 		}
27280 		if (*mp->b_rptr & FLUSHR) {
27281 			*mp->b_rptr &= ~FLUSHW;
27282 			qreply(q, mp);
27283 			return;
27284 		}
27285 		freemsg(mp);
27286 		return;
27287 	case IRE_DB_REQ_TYPE:
27288 		if (connp == NULL) {
27289 			proto_str = "IRE_DB_REQ_TYPE";
27290 			goto protonak;
27291 		}
27292 		/* An Upper Level Protocol wants a copy of an IRE. */
27293 		ip_ire_req(q, mp);
27294 		return;
27295 	case M_CTL:
27296 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27297 			break;
27298 
27299 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27300 		    TUN_HELLO) {
27301 			ASSERT(connp != NULL);
27302 			connp->conn_flags |= IPCL_IPTUN;
27303 			freeb(mp);
27304 			return;
27305 		}
27306 
27307 		/* M_CTL messages are used by ARP to tell us things. */
27308 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27309 			break;
27310 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27311 		case AR_ENTRY_SQUERY:
27312 			putnext(q, mp);
27313 			return;
27314 		case AR_CLIENT_NOTIFY:
27315 			ip_arp_news(q, mp);
27316 			return;
27317 		case AR_DLPIOP_DONE:
27318 			ASSERT(q->q_next != NULL);
27319 			ill = (ill_t *)q->q_ptr;
27320 			/* qwriter_ip releases the refhold */
27321 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27322 			ill_refhold(ill);
27323 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27324 			return;
27325 		case AR_ARP_CLOSING:
27326 			/*
27327 			 * ARP (above us) is closing. If no ARP bringup is
27328 			 * currently pending, ack the message so that ARP
27329 			 * can complete its close. Also mark ill_arp_closing
27330 			 * so that new ARP bringups will fail. If any
27331 			 * ARP bringup is currently in progress, we will
27332 			 * ack this when the current ARP bringup completes.
27333 			 */
27334 			ASSERT(q->q_next != NULL);
27335 			ill = (ill_t *)q->q_ptr;
27336 			mutex_enter(&ill->ill_lock);
27337 			ill->ill_arp_closing = 1;
27338 			if (!ill->ill_arp_bringup_pending) {
27339 				mutex_exit(&ill->ill_lock);
27340 				qreply(q, mp);
27341 			} else {
27342 				mutex_exit(&ill->ill_lock);
27343 				freemsg(mp);
27344 			}
27345 			return;
27346 		case AR_ARP_EXTEND:
27347 			/*
27348 			 * The ARP module above us is capable of duplicate
27349 			 * address detection.  Old ATM drivers will not send
27350 			 * this message.
27351 			 */
27352 			ASSERT(q->q_next != NULL);
27353 			ill = (ill_t *)q->q_ptr;
27354 			ill->ill_arp_extend = B_TRUE;
27355 			freemsg(mp);
27356 			return;
27357 		default:
27358 			break;
27359 		}
27360 		break;
27361 	case M_PROTO:
27362 	case M_PCPROTO:
27363 		/*
27364 		 * The only PROTO messages we expect are copies of option
27365 		 * negotiation acknowledgements, AH and ESP bind requests
27366 		 * are also expected.
27367 		 */
27368 		switch (((union T_primitives *)mp->b_rptr)->type) {
27369 		case O_T_BIND_REQ:
27370 		case T_BIND_REQ: {
27371 			/* Request can get queued in bind */
27372 			if (connp == NULL) {
27373 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27374 				goto protonak;
27375 			}
27376 			/*
27377 			 * The transports except SCTP call ip_bind_{v4,v6}()
27378 			 * directly instead of a a putnext. SCTP doesn't
27379 			 * generate any T_BIND_REQ since it has its own
27380 			 * fanout data structures. However, ESP and AH
27381 			 * come in for regular binds; all other cases are
27382 			 * bind retries.
27383 			 */
27384 			ASSERT(!IPCL_IS_SCTP(connp));
27385 
27386 			/* Don't increment refcnt if this is a re-entry */
27387 			if (ipsq == NULL)
27388 				CONN_INC_REF(connp);
27389 
27390 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27391 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27392 			ASSERT(mp != NULL);
27393 
27394 			ASSERT(!IPCL_IS_TCP(connp));
27395 			ASSERT(!IPCL_IS_UDP(connp));
27396 			ASSERT(!IPCL_IS_RAWIP(connp));
27397 
27398 			/* The case of AH and ESP */
27399 			qreply(q, mp);
27400 			CONN_OPER_PENDING_DONE(connp);
27401 			return;
27402 		}
27403 		case T_SVR4_OPTMGMT_REQ:
27404 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27405 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27406 
27407 			if (connp == NULL) {
27408 				proto_str = "T_SVR4_OPTMGMT_REQ";
27409 				goto protonak;
27410 			}
27411 
27412 			/*
27413 			 * All Solaris components should pass a db_credp
27414 			 * for this TPI message, hence we ASSERT.
27415 			 * But in case there is some other M_PROTO that looks
27416 			 * like a TPI message sent by some other kernel
27417 			 * component, we check and return an error.
27418 			 */
27419 			cr = msg_getcred(mp, NULL);
27420 			ASSERT(cr != NULL);
27421 			if (cr == NULL) {
27422 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27423 				if (mp != NULL)
27424 					qreply(q, mp);
27425 				return;
27426 			}
27427 
27428 			if (!snmpcom_req(q, mp, ip_snmp_set,
27429 			    ip_snmp_get, cr)) {
27430 				/*
27431 				 * Call svr4_optcom_req so that it can
27432 				 * generate the ack. We don't come here
27433 				 * if this operation is being restarted.
27434 				 * ip_restart_optmgmt will drop the conn ref.
27435 				 * In the case of ipsec option after the ipsec
27436 				 * load is complete conn_restart_ipsec_waiter
27437 				 * drops the conn ref.
27438 				 */
27439 				ASSERT(ipsq == NULL);
27440 				CONN_INC_REF(connp);
27441 				if (ip_check_for_ipsec_opt(q, mp))
27442 					return;
27443 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27444 				    B_FALSE);
27445 				if (err != EINPROGRESS) {
27446 					/* Operation is done */
27447 					CONN_OPER_PENDING_DONE(connp);
27448 				}
27449 			}
27450 			return;
27451 		case T_OPTMGMT_REQ:
27452 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27453 			/*
27454 			 * Note: No snmpcom_req support through new
27455 			 * T_OPTMGMT_REQ.
27456 			 * Call tpi_optcom_req so that it can
27457 			 * generate the ack.
27458 			 */
27459 			if (connp == NULL) {
27460 				proto_str = "T_OPTMGMT_REQ";
27461 				goto protonak;
27462 			}
27463 
27464 			/*
27465 			 * All Solaris components should pass a db_credp
27466 			 * for this TPI message, hence we ASSERT.
27467 			 * But in case there is some other M_PROTO that looks
27468 			 * like a TPI message sent by some other kernel
27469 			 * component, we check and return an error.
27470 			 */
27471 			cr = msg_getcred(mp, NULL);
27472 			ASSERT(cr != NULL);
27473 			if (cr == NULL) {
27474 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27475 				if (mp != NULL)
27476 					qreply(q, mp);
27477 				return;
27478 			}
27479 			ASSERT(ipsq == NULL);
27480 			/*
27481 			 * We don't come here for restart. ip_restart_optmgmt
27482 			 * will drop the conn ref. In the case of ipsec option
27483 			 * after the ipsec load is complete
27484 			 * conn_restart_ipsec_waiter drops the conn ref.
27485 			 */
27486 			CONN_INC_REF(connp);
27487 			if (ip_check_for_ipsec_opt(q, mp))
27488 				return;
27489 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27490 			if (err != EINPROGRESS) {
27491 				/* Operation is done */
27492 				CONN_OPER_PENDING_DONE(connp);
27493 			}
27494 			return;
27495 		case T_UNBIND_REQ:
27496 			if (connp == NULL) {
27497 				proto_str = "T_UNBIND_REQ";
27498 				goto protonak;
27499 			}
27500 			ip_unbind(Q_TO_CONN(q));
27501 			mp = mi_tpi_ok_ack_alloc(mp);
27502 			qreply(q, mp);
27503 			return;
27504 		default:
27505 			/*
27506 			 * Have to drop any DLPI messages coming down from
27507 			 * arp (such as an info_req which would cause ip
27508 			 * to receive an extra info_ack if it was passed
27509 			 * through.
27510 			 */
27511 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27512 			    (int)*(uint_t *)mp->b_rptr));
27513 			freemsg(mp);
27514 			return;
27515 		}
27516 		/* NOTREACHED */
27517 	case IRE_DB_TYPE: {
27518 		nce_t		*nce;
27519 		ill_t		*ill;
27520 		in6_addr_t	gw_addr_v6;
27521 
27522 		/*
27523 		 * This is a response back from a resolver.  It
27524 		 * consists of a message chain containing:
27525 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27526 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27527 		 * The LL_HDR_MBLK is the DLPI header to use to get
27528 		 * the attached packet, and subsequent ones for the
27529 		 * same destination, transmitted.
27530 		 */
27531 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27532 			break;
27533 		/*
27534 		 * First, check to make sure the resolution succeeded.
27535 		 * If it failed, the second mblk will be empty.
27536 		 * If it is, free the chain, dropping the packet.
27537 		 * (We must ire_delete the ire; that frees the ire mblk)
27538 		 * We're doing this now to support PVCs for ATM; it's
27539 		 * a partial xresolv implementation. When we fully implement
27540 		 * xresolv interfaces, instead of freeing everything here
27541 		 * we'll initiate neighbor discovery.
27542 		 *
27543 		 * For v4 (ARP and other external resolvers) the resolver
27544 		 * frees the message, so no check is needed. This check
27545 		 * is required, though, for a full xresolve implementation.
27546 		 * Including this code here now both shows how external
27547 		 * resolvers can NACK a resolution request using an
27548 		 * existing design that has no specific provisions for NACKs,
27549 		 * and also takes into account that the current non-ARP
27550 		 * external resolver has been coded to use this method of
27551 		 * NACKing for all IPv6 (xresolv) cases,
27552 		 * whether our xresolv implementation is complete or not.
27553 		 *
27554 		 */
27555 		ire = (ire_t *)mp->b_rptr;
27556 		ill = ire_to_ill(ire);
27557 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27558 		if (mp1->b_rptr == mp1->b_wptr) {
27559 			if (ire->ire_ipversion == IPV6_VERSION) {
27560 				/*
27561 				 * XRESOLV interface.
27562 				 */
27563 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27564 				mutex_enter(&ire->ire_lock);
27565 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27566 				mutex_exit(&ire->ire_lock);
27567 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27568 					nce = ndp_lookup_v6(ill, B_FALSE,
27569 					    &ire->ire_addr_v6, B_FALSE);
27570 				} else {
27571 					nce = ndp_lookup_v6(ill, B_FALSE,
27572 					    &gw_addr_v6, B_FALSE);
27573 				}
27574 				if (nce != NULL) {
27575 					nce_resolv_failed(nce);
27576 					ndp_delete(nce);
27577 					NCE_REFRELE(nce);
27578 				}
27579 			}
27580 			mp->b_cont = NULL;
27581 			freemsg(mp1);		/* frees the pkt as well */
27582 			ASSERT(ire->ire_nce == NULL);
27583 			ire_delete((ire_t *)mp->b_rptr);
27584 			return;
27585 		}
27586 
27587 		/*
27588 		 * Split them into IRE_MBLK and pkt and feed it into
27589 		 * ire_add_then_send. Then in ire_add_then_send
27590 		 * the IRE will be added, and then the packet will be
27591 		 * run back through ip_wput. This time it will make
27592 		 * it to the wire.
27593 		 */
27594 		mp->b_cont = NULL;
27595 		mp = mp1->b_cont;		/* now, mp points to pkt */
27596 		mp1->b_cont = NULL;
27597 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27598 		if (ire->ire_ipversion == IPV6_VERSION) {
27599 			/*
27600 			 * XRESOLV interface. Find the nce and put a copy
27601 			 * of the dl_unitdata_req in nce_res_mp
27602 			 */
27603 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27604 			mutex_enter(&ire->ire_lock);
27605 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27606 			mutex_exit(&ire->ire_lock);
27607 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27608 				nce = ndp_lookup_v6(ill, B_FALSE,
27609 				    &ire->ire_addr_v6, B_FALSE);
27610 			} else {
27611 				nce = ndp_lookup_v6(ill, B_FALSE,
27612 				    &gw_addr_v6, B_FALSE);
27613 			}
27614 			if (nce != NULL) {
27615 				/*
27616 				 * We have to protect nce_res_mp here
27617 				 * from being accessed by other threads
27618 				 * while we change the mblk pointer.
27619 				 * Other functions will also lock the nce when
27620 				 * accessing nce_res_mp.
27621 				 *
27622 				 * The reason we change the mblk pointer
27623 				 * here rather than copying the resolved address
27624 				 * into the template is that, unlike with
27625 				 * ethernet, we have no guarantee that the
27626 				 * resolved address length will be
27627 				 * smaller than or equal to the lla length
27628 				 * with which the template was allocated,
27629 				 * (for ethernet, they're equal)
27630 				 * so we have to use the actual resolved
27631 				 * address mblk - which holds the real
27632 				 * dl_unitdata_req with the resolved address.
27633 				 *
27634 				 * Doing this is the same behavior as was
27635 				 * previously used in the v4 ARP case.
27636 				 */
27637 				mutex_enter(&nce->nce_lock);
27638 				if (nce->nce_res_mp != NULL)
27639 					freemsg(nce->nce_res_mp);
27640 				nce->nce_res_mp = mp1;
27641 				mutex_exit(&nce->nce_lock);
27642 				/*
27643 				 * We do a fastpath probe here because
27644 				 * we have resolved the address without
27645 				 * using Neighbor Discovery.
27646 				 * In the non-XRESOLV v6 case, the fastpath
27647 				 * probe is done right after neighbor
27648 				 * discovery completes.
27649 				 */
27650 				if (nce->nce_res_mp != NULL) {
27651 					int res;
27652 					nce_fastpath_list_add(nce);
27653 					res = ill_fastpath_probe(ill,
27654 					    nce->nce_res_mp);
27655 					if (res != 0 && res != EAGAIN)
27656 						nce_fastpath_list_delete(nce);
27657 				}
27658 
27659 				ire_add_then_send(q, ire, mp);
27660 				/*
27661 				 * Now we have to clean out any packets
27662 				 * that may have been queued on the nce
27663 				 * while it was waiting for address resolution
27664 				 * to complete.
27665 				 */
27666 				mutex_enter(&nce->nce_lock);
27667 				mp1 = nce->nce_qd_mp;
27668 				nce->nce_qd_mp = NULL;
27669 				mutex_exit(&nce->nce_lock);
27670 				while (mp1 != NULL) {
27671 					mblk_t *nxt_mp;
27672 					queue_t *fwdq = NULL;
27673 					ill_t   *inbound_ill;
27674 					uint_t ifindex;
27675 
27676 					nxt_mp = mp1->b_next;
27677 					mp1->b_next = NULL;
27678 					/*
27679 					 * Retrieve ifindex stored in
27680 					 * ip_rput_data_v6()
27681 					 */
27682 					ifindex =
27683 					    (uint_t)(uintptr_t)mp1->b_prev;
27684 					inbound_ill =
27685 					    ill_lookup_on_ifindex(ifindex,
27686 					    B_TRUE, NULL, NULL, NULL,
27687 					    NULL, ipst);
27688 					mp1->b_prev = NULL;
27689 					if (inbound_ill != NULL)
27690 						fwdq = inbound_ill->ill_rq;
27691 
27692 					if (fwdq != NULL) {
27693 						put(fwdq, mp1);
27694 						ill_refrele(inbound_ill);
27695 					} else
27696 						put(WR(ill->ill_rq), mp1);
27697 					mp1 = nxt_mp;
27698 				}
27699 				NCE_REFRELE(nce);
27700 			} else {	/* nce is NULL; clean up */
27701 				ire_delete(ire);
27702 				freemsg(mp);
27703 				freemsg(mp1);
27704 				return;
27705 			}
27706 		} else {
27707 			nce_t *arpce;
27708 			/*
27709 			 * Link layer resolution succeeded. Recompute the
27710 			 * ire_nce.
27711 			 */
27712 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27713 			if ((arpce = ndp_lookup_v4(ill,
27714 			    (ire->ire_gateway_addr != INADDR_ANY ?
27715 			    &ire->ire_gateway_addr : &ire->ire_addr),
27716 			    B_FALSE)) == NULL) {
27717 				freeb(ire->ire_mp);
27718 				freeb(mp1);
27719 				freemsg(mp);
27720 				return;
27721 			}
27722 			mutex_enter(&arpce->nce_lock);
27723 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27724 			if (arpce->nce_state == ND_REACHABLE) {
27725 				/*
27726 				 * Someone resolved this before us;
27727 				 * cleanup the res_mp. Since ire has
27728 				 * not been added yet, the call to ire_add_v4
27729 				 * from ire_add_then_send (when a dup is
27730 				 * detected) will clean up the ire.
27731 				 */
27732 				freeb(mp1);
27733 			} else {
27734 				ASSERT(arpce->nce_res_mp == NULL);
27735 				arpce->nce_res_mp = mp1;
27736 				arpce->nce_state = ND_REACHABLE;
27737 			}
27738 			mutex_exit(&arpce->nce_lock);
27739 			if (ire->ire_marks & IRE_MARK_NOADD) {
27740 				/*
27741 				 * this ire will not be added to the ire
27742 				 * cache table, so we can set the ire_nce
27743 				 * here, as there are no atomicity constraints.
27744 				 */
27745 				ire->ire_nce = arpce;
27746 				/*
27747 				 * We are associating this nce with the ire
27748 				 * so change the nce ref taken in
27749 				 * ndp_lookup_v4() from
27750 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27751 				 */
27752 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27753 			} else {
27754 				NCE_REFRELE(arpce);
27755 			}
27756 			ire_add_then_send(q, ire, mp);
27757 		}
27758 		return;	/* All is well, the packet has been sent. */
27759 	}
27760 	case IRE_ARPRESOLVE_TYPE: {
27761 
27762 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27763 			break;
27764 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27765 		mp->b_cont = NULL;
27766 		/*
27767 		 * First, check to make sure the resolution succeeded.
27768 		 * If it failed, the second mblk will be empty.
27769 		 */
27770 		if (mp1->b_rptr == mp1->b_wptr) {
27771 			/* cleanup  the incomplete ire, free queued packets */
27772 			freemsg(mp); /* fake ire */
27773 			freeb(mp1);  /* dl_unitdata response */
27774 			return;
27775 		}
27776 
27777 		/*
27778 		 * Update any incomplete nce_t found. We search the ctable
27779 		 * and find the nce from the ire->ire_nce because we need
27780 		 * to pass the ire to ip_xmit_v4 later, and can find both
27781 		 * ire and nce in one lookup.
27782 		 */
27783 		fake_ire = (ire_t *)mp->b_rptr;
27784 
27785 		/*
27786 		 * By the time we come back here from ARP the logical outgoing
27787 		 * interface of the incomplete ire we added in ire_forward()
27788 		 * could have disappeared, causing the incomplete ire to also
27789 		 * disappear.  So we need to retreive the proper ipif for the
27790 		 * ire before looking in ctable.  In the case of IPMP, the
27791 		 * ipif may be on the IPMP ill, so look it up based on the
27792 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27793 		 * Then, we can verify that ire_ipif_seqid still exists.
27794 		 */
27795 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27796 		    NULL, NULL, NULL, NULL, ipst);
27797 		if (ill == NULL) {
27798 			ip1dbg(("ill for incomplete ire vanished\n"));
27799 			freemsg(mp); /* fake ire */
27800 			freeb(mp1);  /* dl_unitdata response */
27801 			return;
27802 		}
27803 
27804 		/* Get the outgoing ipif */
27805 		mutex_enter(&ill->ill_lock);
27806 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27807 		if (ipif == NULL) {
27808 			mutex_exit(&ill->ill_lock);
27809 			ill_refrele(ill);
27810 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27811 			freemsg(mp); /* fake_ire */
27812 			freeb(mp1);  /* dl_unitdata response */
27813 			return;
27814 		}
27815 
27816 		ipif_refhold_locked(ipif);
27817 		mutex_exit(&ill->ill_lock);
27818 		ill_refrele(ill);
27819 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27820 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27821 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27822 		ipif_refrele(ipif);
27823 		if (ire == NULL) {
27824 			/*
27825 			 * no ire was found; check if there is an nce
27826 			 * for this lookup; if it has no ire's pointing at it
27827 			 * cleanup.
27828 			 */
27829 			if ((nce = ndp_lookup_v4(q->q_ptr,
27830 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27831 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27832 			    B_FALSE)) != NULL) {
27833 				/*
27834 				 * cleanup:
27835 				 * We check for refcnt 2 (one for the nce
27836 				 * hash list + 1 for the ref taken by
27837 				 * ndp_lookup_v4) to check that there are
27838 				 * no ire's pointing at the nce.
27839 				 */
27840 				if (nce->nce_refcnt == 2)
27841 					ndp_delete(nce);
27842 				NCE_REFRELE(nce);
27843 			}
27844 			freeb(mp1);  /* dl_unitdata response */
27845 			freemsg(mp); /* fake ire */
27846 			return;
27847 		}
27848 
27849 		nce = ire->ire_nce;
27850 		DTRACE_PROBE2(ire__arpresolve__type,
27851 		    ire_t *, ire, nce_t *, nce);
27852 		mutex_enter(&nce->nce_lock);
27853 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27854 		if (nce->nce_state == ND_REACHABLE) {
27855 			/*
27856 			 * Someone resolved this before us;
27857 			 * our response is not needed any more.
27858 			 */
27859 			mutex_exit(&nce->nce_lock);
27860 			freeb(mp1);  /* dl_unitdata response */
27861 		} else {
27862 			ASSERT(nce->nce_res_mp == NULL);
27863 			nce->nce_res_mp = mp1;
27864 			nce->nce_state = ND_REACHABLE;
27865 			mutex_exit(&nce->nce_lock);
27866 			nce_fastpath(nce);
27867 		}
27868 		/*
27869 		 * The cached nce_t has been updated to be reachable;
27870 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27871 		 */
27872 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27873 		freemsg(mp);
27874 		/*
27875 		 * send out queued packets.
27876 		 */
27877 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27878 
27879 		IRE_REFRELE(ire);
27880 		return;
27881 	}
27882 	default:
27883 		break;
27884 	}
27885 	if (q->q_next) {
27886 		putnext(q, mp);
27887 	} else
27888 		freemsg(mp);
27889 	return;
27890 
27891 protonak:
27892 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27893 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27894 		qreply(q, mp);
27895 }
27896 
27897 /*
27898  * Process IP options in an outbound packet.  Modify the destination if there
27899  * is a source route option.
27900  * Returns non-zero if something fails in which case an ICMP error has been
27901  * sent and mp freed.
27902  */
27903 static int
27904 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27905     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27906 {
27907 	ipoptp_t	opts;
27908 	uchar_t		*opt;
27909 	uint8_t		optval;
27910 	uint8_t		optlen;
27911 	ipaddr_t	dst;
27912 	intptr_t	code = 0;
27913 	mblk_t		*mp;
27914 	ire_t		*ire = NULL;
27915 
27916 	ip2dbg(("ip_wput_options\n"));
27917 	mp = ipsec_mp;
27918 	if (mctl_present) {
27919 		mp = ipsec_mp->b_cont;
27920 	}
27921 
27922 	dst = ipha->ipha_dst;
27923 	for (optval = ipoptp_first(&opts, ipha);
27924 	    optval != IPOPT_EOL;
27925 	    optval = ipoptp_next(&opts)) {
27926 		opt = opts.ipoptp_cur;
27927 		optlen = opts.ipoptp_len;
27928 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27929 		    optval, optlen));
27930 		switch (optval) {
27931 			uint32_t off;
27932 		case IPOPT_SSRR:
27933 		case IPOPT_LSRR:
27934 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27935 				ip1dbg((
27936 				    "ip_wput_options: bad option offset\n"));
27937 				code = (char *)&opt[IPOPT_OLEN] -
27938 				    (char *)ipha;
27939 				goto param_prob;
27940 			}
27941 			off = opt[IPOPT_OFFSET];
27942 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27943 			    ntohl(dst)));
27944 			/*
27945 			 * For strict: verify that dst is directly
27946 			 * reachable.
27947 			 */
27948 			if (optval == IPOPT_SSRR) {
27949 				ire = ire_ftable_lookup(dst, 0, 0,
27950 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27951 				    msg_getlabel(mp),
27952 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27953 				if (ire == NULL) {
27954 					ip1dbg(("ip_wput_options: SSRR not"
27955 					    " directly reachable: 0x%x\n",
27956 					    ntohl(dst)));
27957 					goto bad_src_route;
27958 				}
27959 				ire_refrele(ire);
27960 			}
27961 			break;
27962 		case IPOPT_RR:
27963 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27964 				ip1dbg((
27965 				    "ip_wput_options: bad option offset\n"));
27966 				code = (char *)&opt[IPOPT_OLEN] -
27967 				    (char *)ipha;
27968 				goto param_prob;
27969 			}
27970 			break;
27971 		case IPOPT_TS:
27972 			/*
27973 			 * Verify that length >=5 and that there is either
27974 			 * room for another timestamp or that the overflow
27975 			 * counter is not maxed out.
27976 			 */
27977 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27978 			if (optlen < IPOPT_MINLEN_IT) {
27979 				goto param_prob;
27980 			}
27981 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27982 				ip1dbg((
27983 				    "ip_wput_options: bad option offset\n"));
27984 				code = (char *)&opt[IPOPT_OFFSET] -
27985 				    (char *)ipha;
27986 				goto param_prob;
27987 			}
27988 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27989 			case IPOPT_TS_TSONLY:
27990 				off = IPOPT_TS_TIMELEN;
27991 				break;
27992 			case IPOPT_TS_TSANDADDR:
27993 			case IPOPT_TS_PRESPEC:
27994 			case IPOPT_TS_PRESPEC_RFC791:
27995 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27996 				break;
27997 			default:
27998 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27999 				    (char *)ipha;
28000 				goto param_prob;
28001 			}
28002 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28003 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28004 				/*
28005 				 * No room and the overflow counter is 15
28006 				 * already.
28007 				 */
28008 				goto param_prob;
28009 			}
28010 			break;
28011 		}
28012 	}
28013 
28014 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28015 		return (0);
28016 
28017 	ip1dbg(("ip_wput_options: error processing IP options."));
28018 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28019 
28020 param_prob:
28021 	/*
28022 	 * Since ip_wput() isn't close to finished, we fill
28023 	 * in enough of the header for credible error reporting.
28024 	 */
28025 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28026 		/* Failed */
28027 		freemsg(ipsec_mp);
28028 		return (-1);
28029 	}
28030 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28031 	return (-1);
28032 
28033 bad_src_route:
28034 	/*
28035 	 * Since ip_wput() isn't close to finished, we fill
28036 	 * in enough of the header for credible error reporting.
28037 	 */
28038 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28039 		/* Failed */
28040 		freemsg(ipsec_mp);
28041 		return (-1);
28042 	}
28043 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28044 	return (-1);
28045 }
28046 
28047 /*
28048  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28049  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28050  * thru /etc/system.
28051  */
28052 #define	CONN_MAXDRAINCNT	64
28053 
28054 static void
28055 conn_drain_init(ip_stack_t *ipst)
28056 {
28057 	int i, j;
28058 	idl_tx_list_t *itl_tx;
28059 
28060 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28061 
28062 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28063 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28064 		/*
28065 		 * Default value of the number of drainers is the
28066 		 * number of cpus, subject to maximum of 8 drainers.
28067 		 */
28068 		if (boot_max_ncpus != -1)
28069 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28070 		else
28071 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28072 	}
28073 
28074 	ipst->ips_idl_tx_list =
28075 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
28076 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28077 		itl_tx =  &ipst->ips_idl_tx_list[i];
28078 		itl_tx->txl_drain_list =
28079 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28080 		    sizeof (idl_t), KM_SLEEP);
28081 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
28082 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
28083 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
28084 			    MUTEX_DEFAULT, NULL);
28085 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
28086 		}
28087 	}
28088 }
28089 
28090 static void
28091 conn_drain_fini(ip_stack_t *ipst)
28092 {
28093 	int i;
28094 	idl_tx_list_t *itl_tx;
28095 
28096 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28097 		itl_tx =  &ipst->ips_idl_tx_list[i];
28098 		kmem_free(itl_tx->txl_drain_list,
28099 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28100 	}
28101 	kmem_free(ipst->ips_idl_tx_list,
28102 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28103 	ipst->ips_idl_tx_list = NULL;
28104 }
28105 
28106 /*
28107  * Note: For an overview of how flowcontrol is handled in IP please see the
28108  * IP Flowcontrol notes at the top of this file.
28109  *
28110  * Flow control has blocked us from proceeding. Insert the given conn in one
28111  * of the conn drain lists. These conn wq's will be qenabled later on when
28112  * STREAMS flow control does a backenable. conn_walk_drain will enable
28113  * the first conn in each of these drain lists. Each of these qenabled conns
28114  * in turn enables the next in the list, after it runs, or when it closes,
28115  * thus sustaining the drain process.
28116  */
28117 void
28118 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28119 {
28120 	idl_t	*idl = tx_list->txl_drain_list;
28121 	uint_t	index;
28122 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28123 
28124 	mutex_enter(&connp->conn_lock);
28125 	if (connp->conn_state_flags & CONN_CLOSING) {
28126 		/*
28127 		 * The conn is closing as a result of which CONN_CLOSING
28128 		 * is set. Return.
28129 		 */
28130 		mutex_exit(&connp->conn_lock);
28131 		return;
28132 	} else if (connp->conn_idl == NULL) {
28133 		/*
28134 		 * Assign the next drain list round robin. We dont' use
28135 		 * a lock, and thus it may not be strictly round robin.
28136 		 * Atomicity of load/stores is enough to make sure that
28137 		 * conn_drain_list_index is always within bounds.
28138 		 */
28139 		index = tx_list->txl_drain_index;
28140 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28141 		connp->conn_idl = &tx_list->txl_drain_list[index];
28142 		index++;
28143 		if (index == ipst->ips_conn_drain_list_cnt)
28144 			index = 0;
28145 		tx_list->txl_drain_index = index;
28146 	}
28147 	mutex_exit(&connp->conn_lock);
28148 
28149 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28150 	if ((connp->conn_drain_prev != NULL) ||
28151 	    (connp->conn_state_flags & CONN_CLOSING)) {
28152 		/*
28153 		 * The conn is already in the drain list, OR
28154 		 * the conn is closing. We need to check again for
28155 		 * the closing case again since close can happen
28156 		 * after we drop the conn_lock, and before we
28157 		 * acquire the CONN_DRAIN_LIST_LOCK.
28158 		 */
28159 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28160 		return;
28161 	} else {
28162 		idl = connp->conn_idl;
28163 	}
28164 
28165 	/*
28166 	 * The conn is not in the drain list. Insert it at the
28167 	 * tail of the drain list. The drain list is circular
28168 	 * and doubly linked. idl_conn points to the 1st element
28169 	 * in the list.
28170 	 */
28171 	if (idl->idl_conn == NULL) {
28172 		idl->idl_conn = connp;
28173 		connp->conn_drain_next = connp;
28174 		connp->conn_drain_prev = connp;
28175 	} else {
28176 		conn_t *head = idl->idl_conn;
28177 
28178 		connp->conn_drain_next = head;
28179 		connp->conn_drain_prev = head->conn_drain_prev;
28180 		head->conn_drain_prev->conn_drain_next = connp;
28181 		head->conn_drain_prev = connp;
28182 	}
28183 	/*
28184 	 * For non streams based sockets assert flow control.
28185 	 */
28186 	if (IPCL_IS_NONSTR(connp)) {
28187 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28188 		(*connp->conn_upcalls->su_txq_full)
28189 		    (connp->conn_upper_handle, B_TRUE);
28190 	} else {
28191 		conn_setqfull(connp);
28192 		noenable(connp->conn_wq);
28193 	}
28194 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28195 }
28196 
28197 /*
28198  * This conn is closing, and we are called from ip_close. OR
28199  * This conn has been serviced by ip_wsrv, and we need to do the tail
28200  * processing.
28201  * If this conn is part of the drain list, we may need to sustain the drain
28202  * process by qenabling the next conn in the drain list. We may also need to
28203  * remove this conn from the list, if it is done.
28204  */
28205 static void
28206 conn_drain_tail(conn_t *connp, boolean_t closing)
28207 {
28208 	idl_t *idl;
28209 
28210 	/*
28211 	 * connp->conn_idl is stable at this point, and no lock is needed
28212 	 * to check it. If we are called from ip_close, close has already
28213 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28214 	 * called us only because conn_idl is non-null. If we are called thru
28215 	 * service, conn_idl could be null, but it cannot change because
28216 	 * service is single-threaded per queue, and there cannot be another
28217 	 * instance of service trying to call conn_drain_insert on this conn
28218 	 * now.
28219 	 */
28220 	ASSERT(!closing || (connp->conn_idl != NULL));
28221 
28222 	/*
28223 	 * If connp->conn_idl is null, the conn has not been inserted into any
28224 	 * drain list even once since creation of the conn. Just return.
28225 	 */
28226 	if (connp->conn_idl == NULL)
28227 		return;
28228 
28229 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28230 
28231 	if (connp->conn_drain_prev == NULL) {
28232 		/* This conn is currently not in the drain list.  */
28233 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28234 		return;
28235 	}
28236 	idl = connp->conn_idl;
28237 	if (idl->idl_conn_draining == connp) {
28238 		/*
28239 		 * This conn is the current drainer. If this is the last conn
28240 		 * in the drain list, we need to do more checks, in the 'if'
28241 		 * below. Otherwwise we need to just qenable the next conn,
28242 		 * to sustain the draining, and is handled in the 'else'
28243 		 * below.
28244 		 */
28245 		if (connp->conn_drain_next == idl->idl_conn) {
28246 			/*
28247 			 * This conn is the last in this list. This round
28248 			 * of draining is complete. If idl_repeat is set,
28249 			 * it means another flow enabling has happened from
28250 			 * the driver/streams and we need to another round
28251 			 * of draining.
28252 			 * If there are more than 2 conns in the drain list,
28253 			 * do a left rotate by 1, so that all conns except the
28254 			 * conn at the head move towards the head by 1, and the
28255 			 * the conn at the head goes to the tail. This attempts
28256 			 * a more even share for all queues that are being
28257 			 * drained.
28258 			 */
28259 			if ((connp->conn_drain_next != connp) &&
28260 			    (idl->idl_conn->conn_drain_next != connp)) {
28261 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28262 			}
28263 			if (idl->idl_repeat) {
28264 				qenable(idl->idl_conn->conn_wq);
28265 				idl->idl_conn_draining = idl->idl_conn;
28266 				idl->idl_repeat = 0;
28267 			} else {
28268 				idl->idl_conn_draining = NULL;
28269 			}
28270 		} else {
28271 			/*
28272 			 * If the next queue that we are now qenable'ing,
28273 			 * is closing, it will remove itself from this list
28274 			 * and qenable the subsequent queue in ip_close().
28275 			 * Serialization is acheived thru idl_lock.
28276 			 */
28277 			qenable(connp->conn_drain_next->conn_wq);
28278 			idl->idl_conn_draining = connp->conn_drain_next;
28279 		}
28280 	}
28281 	if (!connp->conn_did_putbq || closing) {
28282 		/*
28283 		 * Remove ourself from the drain list, if we did not do
28284 		 * a putbq, or if the conn is closing.
28285 		 * Note: It is possible that q->q_first is non-null. It means
28286 		 * that these messages landed after we did a enableok() in
28287 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28288 		 * service them.
28289 		 */
28290 		if (connp->conn_drain_next == connp) {
28291 			/* Singleton in the list */
28292 			ASSERT(connp->conn_drain_prev == connp);
28293 			idl->idl_conn = NULL;
28294 			idl->idl_conn_draining = NULL;
28295 		} else {
28296 			connp->conn_drain_prev->conn_drain_next =
28297 			    connp->conn_drain_next;
28298 			connp->conn_drain_next->conn_drain_prev =
28299 			    connp->conn_drain_prev;
28300 			if (idl->idl_conn == connp)
28301 				idl->idl_conn = connp->conn_drain_next;
28302 			ASSERT(idl->idl_conn_draining != connp);
28303 
28304 		}
28305 		connp->conn_drain_next = NULL;
28306 		connp->conn_drain_prev = NULL;
28307 
28308 		/*
28309 		 * For non streams based sockets open up flow control.
28310 		 */
28311 		if (IPCL_IS_NONSTR(connp)) {
28312 			(*connp->conn_upcalls->su_txq_full)
28313 			    (connp->conn_upper_handle, B_FALSE);
28314 		} else {
28315 			conn_clrqfull(connp);
28316 			enableok(connp->conn_wq);
28317 		}
28318 	}
28319 
28320 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28321 }
28322 
28323 /*
28324  * Write service routine. Shared perimeter entry point.
28325  * ip_wsrv can be called in any of the following ways.
28326  * 1. The device queue's messages has fallen below the low water mark
28327  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28328  *    the drain lists and backenable the first conn in each list.
28329  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28330  *    qenabled non-tcp upper layers. We start dequeing messages and call
28331  *    ip_wput for each message.
28332  */
28333 
28334 void
28335 ip_wsrv(queue_t *q)
28336 {
28337 	conn_t	*connp;
28338 	ill_t	*ill;
28339 	mblk_t	*mp;
28340 
28341 	if (q->q_next) {
28342 		ill = (ill_t *)q->q_ptr;
28343 		if (ill->ill_state_flags == 0) {
28344 			ip_stack_t *ipst = ill->ill_ipst;
28345 
28346 			/*
28347 			 * The device flow control has opened up.
28348 			 * Walk through conn drain lists and qenable the
28349 			 * first conn in each list. This makes sense only
28350 			 * if the stream is fully plumbed and setup.
28351 			 * Hence the if check above.
28352 			 */
28353 			ip1dbg(("ip_wsrv: walking\n"));
28354 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28355 		}
28356 		return;
28357 	}
28358 
28359 	connp = Q_TO_CONN(q);
28360 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28361 
28362 	/*
28363 	 * 1. Set conn_draining flag to signal that service is active.
28364 	 *
28365 	 * 2. ip_output determines whether it has been called from service,
28366 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28367 	 *    has been called from service.
28368 	 *
28369 	 * 3. Message ordering is preserved by the following logic.
28370 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28371 	 *    the message at the tail, if conn_draining is set (i.e. service
28372 	 *    is running) or if q->q_first is non-null.
28373 	 *
28374 	 *    ii. If ip_output is called from service, and if ip_output cannot
28375 	 *    putnext due to flow control, it does a putbq.
28376 	 *
28377 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28378 	 *    (causing an infinite loop).
28379 	 */
28380 	ASSERT(!connp->conn_did_putbq);
28381 
28382 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28383 		connp->conn_draining = 1;
28384 		noenable(q);
28385 		while ((mp = getq(q)) != NULL) {
28386 			ASSERT(CONN_Q(q));
28387 
28388 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28389 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28390 			if (connp->conn_did_putbq) {
28391 				/* ip_wput did a putbq */
28392 				break;
28393 			}
28394 		}
28395 		/*
28396 		 * At this point, a thread coming down from top, calling
28397 		 * ip_wput, may end up queueing the message. We have not yet
28398 		 * enabled the queue, so ip_wsrv won't be called again.
28399 		 * To avoid this race, check q->q_first again (in the loop)
28400 		 * If the other thread queued the message before we call
28401 		 * enableok(), we will catch it in the q->q_first check.
28402 		 * If the other thread queues the message after we call
28403 		 * enableok(), ip_wsrv will be called again by STREAMS.
28404 		 */
28405 		connp->conn_draining = 0;
28406 		enableok(q);
28407 	}
28408 
28409 	/* Enable the next conn for draining */
28410 	conn_drain_tail(connp, B_FALSE);
28411 
28412 	/*
28413 	 * conn_direct_blocked is used to indicate blocked
28414 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28415 	 * This is the only place where it is set without
28416 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28417 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28418 	 */
28419 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28420 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28421 		connp->conn_direct_blocked = B_FALSE;
28422 	}
28423 
28424 	connp->conn_did_putbq = 0;
28425 }
28426 
28427 /*
28428  * Callback to disable flow control in IP.
28429  *
28430  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28431  * is enabled.
28432  *
28433  * When MAC_TX() is not able to send any more packets, dld sets its queue
28434  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28435  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28436  * function and wakes up corresponding mac worker threads, which in turn
28437  * calls this callback function, and disables flow control.
28438  */
28439 void
28440 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28441 {
28442 	ill_t *ill = (ill_t *)arg;
28443 	ip_stack_t *ipst = ill->ill_ipst;
28444 	idl_tx_list_t *idl_txl;
28445 
28446 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28447 	mutex_enter(&idl_txl->txl_lock);
28448 	/* add code to to set a flag to indicate idl_txl is enabled */
28449 	conn_walk_drain(ipst, idl_txl);
28450 	mutex_exit(&idl_txl->txl_lock);
28451 }
28452 
28453 /*
28454  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28455  * of conns that need to be drained, check if drain is already in progress.
28456  * If so set the idl_repeat bit, indicating that the last conn in the list
28457  * needs to reinitiate the drain once again, for the list. If drain is not
28458  * in progress for the list, initiate the draining, by qenabling the 1st
28459  * conn in the list. The drain is self-sustaining, each qenabled conn will
28460  * in turn qenable the next conn, when it is done/blocked/closing.
28461  */
28462 static void
28463 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28464 {
28465 	int i;
28466 	idl_t *idl;
28467 
28468 	IP_STAT(ipst, ip_conn_walk_drain);
28469 
28470 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28471 		idl = &tx_list->txl_drain_list[i];
28472 		mutex_enter(&idl->idl_lock);
28473 		if (idl->idl_conn == NULL) {
28474 			mutex_exit(&idl->idl_lock);
28475 			continue;
28476 		}
28477 		/*
28478 		 * If this list is not being drained currently by
28479 		 * an ip_wsrv thread, start the process.
28480 		 */
28481 		if (idl->idl_conn_draining == NULL) {
28482 			ASSERT(idl->idl_repeat == 0);
28483 			qenable(idl->idl_conn->conn_wq);
28484 			idl->idl_conn_draining = idl->idl_conn;
28485 		} else {
28486 			idl->idl_repeat = 1;
28487 		}
28488 		mutex_exit(&idl->idl_lock);
28489 	}
28490 }
28491 
28492 /*
28493  * Determine if the ill and multicast aspects of that packets
28494  * "matches" the conn.
28495  */
28496 boolean_t
28497 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28498     zoneid_t zoneid)
28499 {
28500 	ill_t *bound_ill;
28501 	boolean_t found;
28502 	ipif_t *ipif;
28503 	ire_t *ire;
28504 	ipaddr_t dst, src;
28505 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28506 
28507 	dst = ipha->ipha_dst;
28508 	src = ipha->ipha_src;
28509 
28510 	/*
28511 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28512 	 * unicast, broadcast and multicast reception to
28513 	 * conn_incoming_ill. conn_wantpacket itself is called
28514 	 * only for BROADCAST and multicast.
28515 	 */
28516 	bound_ill = connp->conn_incoming_ill;
28517 	if (bound_ill != NULL) {
28518 		if (IS_IPMP(bound_ill)) {
28519 			if (bound_ill->ill_grp != ill->ill_grp)
28520 				return (B_FALSE);
28521 		} else {
28522 			if (bound_ill != ill)
28523 				return (B_FALSE);
28524 		}
28525 	}
28526 
28527 	if (!CLASSD(dst)) {
28528 		if (IPCL_ZONE_MATCH(connp, zoneid))
28529 			return (B_TRUE);
28530 		/*
28531 		 * The conn is in a different zone; we need to check that this
28532 		 * broadcast address is configured in the application's zone.
28533 		 */
28534 		ipif = ipif_get_next_ipif(NULL, ill);
28535 		if (ipif == NULL)
28536 			return (B_FALSE);
28537 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28538 		    connp->conn_zoneid, NULL,
28539 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28540 		ipif_refrele(ipif);
28541 		if (ire != NULL) {
28542 			ire_refrele(ire);
28543 			return (B_TRUE);
28544 		} else {
28545 			return (B_FALSE);
28546 		}
28547 	}
28548 
28549 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28550 	    connp->conn_zoneid == zoneid) {
28551 		/*
28552 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28553 		 * disabled, therefore we don't dispatch the multicast packet to
28554 		 * the sending zone.
28555 		 */
28556 		return (B_FALSE);
28557 	}
28558 
28559 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28560 		/*
28561 		 * Multicast packet on the loopback interface: we only match
28562 		 * conns who joined the group in the specified zone.
28563 		 */
28564 		return (B_FALSE);
28565 	}
28566 
28567 	if (connp->conn_multi_router) {
28568 		/* multicast packet and multicast router socket: send up */
28569 		return (B_TRUE);
28570 	}
28571 
28572 	mutex_enter(&connp->conn_lock);
28573 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28574 	mutex_exit(&connp->conn_lock);
28575 	return (found);
28576 }
28577 
28578 static void
28579 conn_setqfull(conn_t *connp)
28580 {
28581 	queue_t *q = connp->conn_wq;
28582 
28583 	if (!(q->q_flag & QFULL)) {
28584 		mutex_enter(QLOCK(q));
28585 		if (!(q->q_flag & QFULL)) {
28586 			/* still need to set QFULL */
28587 			q->q_flag |= QFULL;
28588 			mutex_exit(QLOCK(q));
28589 		} else {
28590 			mutex_exit(QLOCK(q));
28591 		}
28592 	}
28593 }
28594 
28595 static void
28596 conn_clrqfull(conn_t *connp)
28597 {
28598 	queue_t *q = connp->conn_wq;
28599 
28600 	if (q->q_flag & QFULL) {
28601 		mutex_enter(QLOCK(q));
28602 		if (q->q_flag & QFULL) {
28603 			q->q_flag &= ~QFULL;
28604 			mutex_exit(QLOCK(q));
28605 			if (q->q_flag & QWANTW)
28606 				qbackenable(q, 0);
28607 		} else {
28608 			mutex_exit(QLOCK(q));
28609 		}
28610 	}
28611 }
28612 
28613 /*
28614  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28615  */
28616 /* ARGSUSED */
28617 static void
28618 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28619 {
28620 	ill_t *ill = (ill_t *)q->q_ptr;
28621 	mblk_t	*mp1, *mp2;
28622 	ipif_t  *ipif;
28623 	int err = 0;
28624 	conn_t *connp = NULL;
28625 	ipsq_t	*ipsq;
28626 	arc_t	*arc;
28627 
28628 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28629 
28630 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28631 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28632 
28633 	ASSERT(IAM_WRITER_ILL(ill));
28634 	mp2 = mp->b_cont;
28635 	mp->b_cont = NULL;
28636 
28637 	/*
28638 	 * We have now received the arp bringup completion message
28639 	 * from ARP. Mark the arp bringup as done. Also if the arp
28640 	 * stream has already started closing, send up the AR_ARP_CLOSING
28641 	 * ack now since ARP is waiting in close for this ack.
28642 	 */
28643 	mutex_enter(&ill->ill_lock);
28644 	ill->ill_arp_bringup_pending = 0;
28645 	if (ill->ill_arp_closing) {
28646 		mutex_exit(&ill->ill_lock);
28647 		/* Let's reuse the mp for sending the ack */
28648 		arc = (arc_t *)mp->b_rptr;
28649 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28650 		arc->arc_cmd = AR_ARP_CLOSING;
28651 		qreply(q, mp);
28652 	} else {
28653 		mutex_exit(&ill->ill_lock);
28654 		freeb(mp);
28655 	}
28656 
28657 	ipsq = ill->ill_phyint->phyint_ipsq;
28658 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28659 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28660 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28661 	if (mp1 == NULL) {
28662 		/* bringup was aborted by the user */
28663 		freemsg(mp2);
28664 		return;
28665 	}
28666 
28667 	/*
28668 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28669 	 * must have an associated conn_t.  Otherwise, we're bringing this
28670 	 * interface back up as part of handling an asynchronous event (e.g.,
28671 	 * physical address change).
28672 	 */
28673 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28674 		ASSERT(connp != NULL);
28675 		q = CONNP_TO_WQ(connp);
28676 	} else {
28677 		ASSERT(connp == NULL);
28678 		q = ill->ill_rq;
28679 	}
28680 
28681 	/*
28682 	 * If the DL_BIND_REQ fails, it is noted
28683 	 * in arc_name_offset.
28684 	 */
28685 	err = *((int *)mp2->b_rptr);
28686 	if (err == 0) {
28687 		if (ipif->ipif_isv6) {
28688 			if ((err = ipif_up_done_v6(ipif)) != 0)
28689 				ip0dbg(("ip_arp_done: init failed\n"));
28690 		} else {
28691 			if ((err = ipif_up_done(ipif)) != 0)
28692 				ip0dbg(("ip_arp_done: init failed\n"));
28693 		}
28694 	} else {
28695 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28696 	}
28697 
28698 	freemsg(mp2);
28699 
28700 	if ((err == 0) && (ill->ill_up_ipifs)) {
28701 		err = ill_up_ipifs(ill, q, mp1);
28702 		if (err == EINPROGRESS)
28703 			return;
28704 	}
28705 
28706 	/*
28707 	 * If we have a moved ipif to bring up, and everything has succeeded
28708 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28709 	 * down -- the admin can try to bring it up by hand if need be.
28710 	 */
28711 	if (ill->ill_move_ipif != NULL) {
28712 		ipif = ill->ill_move_ipif;
28713 		ill->ill_move_ipif = NULL;
28714 		if (err == 0) {
28715 			err = ipif_up(ipif, q, mp1);
28716 			if (err == EINPROGRESS)
28717 				return;
28718 		}
28719 	}
28720 
28721 	/*
28722 	 * The operation must complete without EINPROGRESS since
28723 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28724 	 * operation will be stuck forever in the ipsq.
28725 	 */
28726 	ASSERT(err != EINPROGRESS);
28727 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28728 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28729 	else
28730 		ipsq_current_finish(ipsq);
28731 }
28732 
28733 /* Allocate the private structure */
28734 static int
28735 ip_priv_alloc(void **bufp)
28736 {
28737 	void	*buf;
28738 
28739 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28740 		return (ENOMEM);
28741 
28742 	*bufp = buf;
28743 	return (0);
28744 }
28745 
28746 /* Function to delete the private structure */
28747 void
28748 ip_priv_free(void *buf)
28749 {
28750 	ASSERT(buf != NULL);
28751 	kmem_free(buf, sizeof (ip_priv_t));
28752 }
28753 
28754 /*
28755  * The entry point for IPPF processing.
28756  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28757  * routine just returns.
28758  *
28759  * When called, ip_process generates an ipp_packet_t structure
28760  * which holds the state information for this packet and invokes the
28761  * the classifier (via ipp_packet_process). The classification, depending on
28762  * configured filters, results in a list of actions for this packet. Invoking
28763  * an action may cause the packet to be dropped, in which case the resulting
28764  * mblk (*mpp) is NULL. proc indicates the callout position for
28765  * this packet and ill_index is the interface this packet on or will leave
28766  * on (inbound and outbound resp.).
28767  */
28768 void
28769 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28770 {
28771 	mblk_t		*mp;
28772 	ip_priv_t	*priv;
28773 	ipp_action_id_t	aid;
28774 	int		rc = 0;
28775 	ipp_packet_t	*pp;
28776 #define	IP_CLASS	"ip"
28777 
28778 	/* If the classifier is not loaded, return  */
28779 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28780 		return;
28781 	}
28782 
28783 	mp = *mpp;
28784 	ASSERT(mp != NULL);
28785 
28786 	/* Allocate the packet structure */
28787 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28788 	if (rc != 0) {
28789 		*mpp = NULL;
28790 		freemsg(mp);
28791 		return;
28792 	}
28793 
28794 	/* Allocate the private structure */
28795 	rc = ip_priv_alloc((void **)&priv);
28796 	if (rc != 0) {
28797 		*mpp = NULL;
28798 		freemsg(mp);
28799 		ipp_packet_free(pp);
28800 		return;
28801 	}
28802 	priv->proc = proc;
28803 	priv->ill_index = ill_index;
28804 	ipp_packet_set_private(pp, priv, ip_priv_free);
28805 	ipp_packet_set_data(pp, mp);
28806 
28807 	/* Invoke the classifier */
28808 	rc = ipp_packet_process(&pp);
28809 	if (pp != NULL) {
28810 		mp = ipp_packet_get_data(pp);
28811 		ipp_packet_free(pp);
28812 		if (rc != 0) {
28813 			freemsg(mp);
28814 			*mpp = NULL;
28815 		}
28816 	} else {
28817 		*mpp = NULL;
28818 	}
28819 #undef	IP_CLASS
28820 }
28821 
28822 /*
28823  * Propagate a multicast group membership operation (add/drop) on
28824  * all the interfaces crossed by the related multirt routes.
28825  * The call is considered successful if the operation succeeds
28826  * on at least one interface.
28827  */
28828 static int
28829 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28830     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28831     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28832     mblk_t *first_mp)
28833 {
28834 	ire_t		*ire_gw;
28835 	irb_t		*irb;
28836 	int		error = 0;
28837 	opt_restart_t	*or;
28838 	ip_stack_t	*ipst = ire->ire_ipst;
28839 
28840 	irb = ire->ire_bucket;
28841 	ASSERT(irb != NULL);
28842 
28843 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28844 
28845 	or = (opt_restart_t *)first_mp->b_rptr;
28846 	IRB_REFHOLD(irb);
28847 	for (; ire != NULL; ire = ire->ire_next) {
28848 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28849 			continue;
28850 		if (ire->ire_addr != group)
28851 			continue;
28852 
28853 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28854 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28855 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28856 		/* No resolver exists for the gateway; skip this ire. */
28857 		if (ire_gw == NULL)
28858 			continue;
28859 
28860 		/*
28861 		 * This function can return EINPROGRESS. If so the operation
28862 		 * will be restarted from ip_restart_optmgmt which will
28863 		 * call ip_opt_set and option processing will restart for
28864 		 * this option. So we may end up calling 'fn' more than once.
28865 		 * This requires that 'fn' is idempotent except for the
28866 		 * return value. The operation is considered a success if
28867 		 * it succeeds at least once on any one interface.
28868 		 */
28869 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28870 		    NULL, fmode, src, first_mp);
28871 		if (error == 0)
28872 			or->or_private = CGTP_MCAST_SUCCESS;
28873 
28874 		if (ip_debug > 0) {
28875 			ulong_t	off;
28876 			char	*ksym;
28877 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28878 			ip2dbg(("ip_multirt_apply_membership: "
28879 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28880 			    "error %d [success %u]\n",
28881 			    ksym ? ksym : "?",
28882 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28883 			    error, or->or_private));
28884 		}
28885 
28886 		ire_refrele(ire_gw);
28887 		if (error == EINPROGRESS) {
28888 			IRB_REFRELE(irb);
28889 			return (error);
28890 		}
28891 	}
28892 	IRB_REFRELE(irb);
28893 	/*
28894 	 * Consider the call as successful if we succeeded on at least
28895 	 * one interface. Otherwise, return the last encountered error.
28896 	 */
28897 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28898 }
28899 
28900 /*
28901  * Issue a warning regarding a route crossing an interface with an
28902  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28903  * amount of time is logged.
28904  */
28905 static void
28906 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28907 {
28908 	hrtime_t	current = gethrtime();
28909 	char		buf[INET_ADDRSTRLEN];
28910 	ip_stack_t	*ipst = ire->ire_ipst;
28911 
28912 	/* Convert interval in ms to hrtime in ns */
28913 	if (ipst->ips_multirt_bad_mtu_last_time +
28914 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28915 	    current) {
28916 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28917 		    "to %s, incorrect MTU %u (expected %u)\n",
28918 		    ip_dot_addr(ire->ire_addr, buf),
28919 		    ire->ire_max_frag, max_frag);
28920 
28921 		ipst->ips_multirt_bad_mtu_last_time = current;
28922 	}
28923 }
28924 
28925 /*
28926  * Get the CGTP (multirouting) filtering status.
28927  * If 0, the CGTP hooks are transparent.
28928  */
28929 /* ARGSUSED */
28930 static int
28931 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28932 {
28933 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28934 
28935 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28936 	return (0);
28937 }
28938 
28939 /*
28940  * Set the CGTP (multirouting) filtering status.
28941  * If the status is changed from active to transparent
28942  * or from transparent to active, forward the new status
28943  * to the filtering module (if loaded).
28944  */
28945 /* ARGSUSED */
28946 static int
28947 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28948     cred_t *ioc_cr)
28949 {
28950 	long		new_value;
28951 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28952 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28953 
28954 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28955 		return (EPERM);
28956 
28957 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28958 	    new_value < 0 || new_value > 1) {
28959 		return (EINVAL);
28960 	}
28961 
28962 	if ((!*ip_cgtp_filter_value) && new_value) {
28963 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28964 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28965 		    " (module not loaded)" : "");
28966 	}
28967 	if (*ip_cgtp_filter_value && (!new_value)) {
28968 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28969 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28970 		    " (module not loaded)" : "");
28971 	}
28972 
28973 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28974 		int	res;
28975 		netstackid_t stackid;
28976 
28977 		stackid = ipst->ips_netstack->netstack_stackid;
28978 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28979 		    new_value);
28980 		if (res)
28981 			return (res);
28982 	}
28983 
28984 	*ip_cgtp_filter_value = (boolean_t)new_value;
28985 
28986 	return (0);
28987 }
28988 
28989 /*
28990  * Return the expected CGTP hooks version number.
28991  */
28992 int
28993 ip_cgtp_filter_supported(void)
28994 {
28995 	return (ip_cgtp_filter_rev);
28996 }
28997 
28998 /*
28999  * CGTP hooks can be registered by invoking this function.
29000  * Checks that the version number matches.
29001  */
29002 int
29003 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29004 {
29005 	netstack_t *ns;
29006 	ip_stack_t *ipst;
29007 
29008 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29009 		return (ENOTSUP);
29010 
29011 	ns = netstack_find_by_stackid(stackid);
29012 	if (ns == NULL)
29013 		return (EINVAL);
29014 	ipst = ns->netstack_ip;
29015 	ASSERT(ipst != NULL);
29016 
29017 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29018 		netstack_rele(ns);
29019 		return (EALREADY);
29020 	}
29021 
29022 	ipst->ips_ip_cgtp_filter_ops = ops;
29023 	netstack_rele(ns);
29024 	return (0);
29025 }
29026 
29027 /*
29028  * CGTP hooks can be unregistered by invoking this function.
29029  * Returns ENXIO if there was no registration.
29030  * Returns EBUSY if the ndd variable has not been turned off.
29031  */
29032 int
29033 ip_cgtp_filter_unregister(netstackid_t stackid)
29034 {
29035 	netstack_t *ns;
29036 	ip_stack_t *ipst;
29037 
29038 	ns = netstack_find_by_stackid(stackid);
29039 	if (ns == NULL)
29040 		return (EINVAL);
29041 	ipst = ns->netstack_ip;
29042 	ASSERT(ipst != NULL);
29043 
29044 	if (ipst->ips_ip_cgtp_filter) {
29045 		netstack_rele(ns);
29046 		return (EBUSY);
29047 	}
29048 
29049 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29050 		netstack_rele(ns);
29051 		return (ENXIO);
29052 	}
29053 	ipst->ips_ip_cgtp_filter_ops = NULL;
29054 	netstack_rele(ns);
29055 	return (0);
29056 }
29057 
29058 /*
29059  * Check whether there is a CGTP filter registration.
29060  * Returns non-zero if there is a registration, otherwise returns zero.
29061  * Note: returns zero if bad stackid.
29062  */
29063 int
29064 ip_cgtp_filter_is_registered(netstackid_t stackid)
29065 {
29066 	netstack_t *ns;
29067 	ip_stack_t *ipst;
29068 	int ret;
29069 
29070 	ns = netstack_find_by_stackid(stackid);
29071 	if (ns == NULL)
29072 		return (0);
29073 	ipst = ns->netstack_ip;
29074 	ASSERT(ipst != NULL);
29075 
29076 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29077 		ret = 1;
29078 	else
29079 		ret = 0;
29080 
29081 	netstack_rele(ns);
29082 	return (ret);
29083 }
29084 
29085 static int
29086 ip_squeue_switch(int val)
29087 {
29088 	int rval = SQ_FILL;
29089 
29090 	switch (val) {
29091 	case IP_SQUEUE_ENTER_NODRAIN:
29092 		rval = SQ_NODRAIN;
29093 		break;
29094 	case IP_SQUEUE_ENTER:
29095 		rval = SQ_PROCESS;
29096 		break;
29097 	default:
29098 		break;
29099 	}
29100 	return (rval);
29101 }
29102 
29103 /* ARGSUSED */
29104 static int
29105 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29106     caddr_t addr, cred_t *cr)
29107 {
29108 	int *v = (int *)addr;
29109 	long new_value;
29110 
29111 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29112 		return (EPERM);
29113 
29114 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29115 		return (EINVAL);
29116 
29117 	ip_squeue_flag = ip_squeue_switch(new_value);
29118 	*v = new_value;
29119 	return (0);
29120 }
29121 
29122 /*
29123  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29124  * ip_debug.
29125  */
29126 /* ARGSUSED */
29127 static int
29128 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29129     caddr_t addr, cred_t *cr)
29130 {
29131 	int *v = (int *)addr;
29132 	long new_value;
29133 
29134 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29135 		return (EPERM);
29136 
29137 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29138 		return (EINVAL);
29139 
29140 	*v = new_value;
29141 	return (0);
29142 }
29143 
29144 static void *
29145 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29146 {
29147 	kstat_t *ksp;
29148 
29149 	ip_stat_t template = {
29150 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29151 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29152 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29153 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29154 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29155 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29156 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29157 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29158 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29159 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29160 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29161 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29162 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29163 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29164 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29165 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29166 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29167 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29168 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29169 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29170 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29171 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29172 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29173 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29174 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29175 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29176 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29177 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29178 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29179 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29180 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29181 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29182 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29183 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29184 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29185 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29186 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29187 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29188 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29189 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29190 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29191 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29192 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29193 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29194 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29195 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29196 	};
29197 
29198 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29199 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29200 	    KSTAT_FLAG_VIRTUAL, stackid);
29201 
29202 	if (ksp == NULL)
29203 		return (NULL);
29204 
29205 	bcopy(&template, ip_statisticsp, sizeof (template));
29206 	ksp->ks_data = (void *)ip_statisticsp;
29207 	ksp->ks_private = (void *)(uintptr_t)stackid;
29208 
29209 	kstat_install(ksp);
29210 	return (ksp);
29211 }
29212 
29213 static void
29214 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29215 {
29216 	if (ksp != NULL) {
29217 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29218 		kstat_delete_netstack(ksp, stackid);
29219 	}
29220 }
29221 
29222 static void *
29223 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29224 {
29225 	kstat_t	*ksp;
29226 
29227 	ip_named_kstat_t template = {
29228 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29229 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29230 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29231 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29232 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29233 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29234 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29235 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29236 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29237 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29238 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29239 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29240 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29241 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29242 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29243 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29244 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29245 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29246 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29247 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29248 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29249 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29250 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29251 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29252 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29253 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29254 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29255 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29256 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29257 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29258 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29259 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29260 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29261 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29262 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29263 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29264 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29265 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29266 	};
29267 
29268 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29269 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29270 	if (ksp == NULL || ksp->ks_data == NULL)
29271 		return (NULL);
29272 
29273 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29274 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29275 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29276 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29277 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29278 
29279 	template.netToMediaEntrySize.value.i32 =
29280 	    sizeof (mib2_ipNetToMediaEntry_t);
29281 
29282 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29283 
29284 	bcopy(&template, ksp->ks_data, sizeof (template));
29285 	ksp->ks_update = ip_kstat_update;
29286 	ksp->ks_private = (void *)(uintptr_t)stackid;
29287 
29288 	kstat_install(ksp);
29289 	return (ksp);
29290 }
29291 
29292 static void
29293 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29294 {
29295 	if (ksp != NULL) {
29296 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29297 		kstat_delete_netstack(ksp, stackid);
29298 	}
29299 }
29300 
29301 static int
29302 ip_kstat_update(kstat_t *kp, int rw)
29303 {
29304 	ip_named_kstat_t *ipkp;
29305 	mib2_ipIfStatsEntry_t ipmib;
29306 	ill_walk_context_t ctx;
29307 	ill_t *ill;
29308 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29309 	netstack_t	*ns;
29310 	ip_stack_t	*ipst;
29311 
29312 	if (kp == NULL || kp->ks_data == NULL)
29313 		return (EIO);
29314 
29315 	if (rw == KSTAT_WRITE)
29316 		return (EACCES);
29317 
29318 	ns = netstack_find_by_stackid(stackid);
29319 	if (ns == NULL)
29320 		return (-1);
29321 	ipst = ns->netstack_ip;
29322 	if (ipst == NULL) {
29323 		netstack_rele(ns);
29324 		return (-1);
29325 	}
29326 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29327 
29328 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29329 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29330 	ill = ILL_START_WALK_V4(&ctx, ipst);
29331 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29332 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29333 	rw_exit(&ipst->ips_ill_g_lock);
29334 
29335 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29336 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29337 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29338 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29339 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29340 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29341 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29342 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29343 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29344 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29345 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29346 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29347 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29348 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29349 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29350 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29351 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29352 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29353 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29354 
29355 	ipkp->routingDiscards.value.ui32 =	0;
29356 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29357 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29358 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29359 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29360 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29361 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29362 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29363 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29364 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29365 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29366 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29367 
29368 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29369 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29370 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29371 
29372 	netstack_rele(ns);
29373 
29374 	return (0);
29375 }
29376 
29377 static void *
29378 icmp_kstat_init(netstackid_t stackid)
29379 {
29380 	kstat_t	*ksp;
29381 
29382 	icmp_named_kstat_t template = {
29383 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29384 		{ "inErrors",		KSTAT_DATA_UINT32 },
29385 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29386 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29387 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29388 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29389 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29390 		{ "inEchos",		KSTAT_DATA_UINT32 },
29391 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29392 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29393 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29394 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29395 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29396 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29397 		{ "outErrors",		KSTAT_DATA_UINT32 },
29398 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29399 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29400 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29401 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29402 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29403 		{ "outEchos",		KSTAT_DATA_UINT32 },
29404 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29405 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29406 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29407 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29408 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29409 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29410 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29411 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29412 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29413 		{ "outDrops",		KSTAT_DATA_UINT32 },
29414 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29415 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29416 	};
29417 
29418 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29419 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29420 	if (ksp == NULL || ksp->ks_data == NULL)
29421 		return (NULL);
29422 
29423 	bcopy(&template, ksp->ks_data, sizeof (template));
29424 
29425 	ksp->ks_update = icmp_kstat_update;
29426 	ksp->ks_private = (void *)(uintptr_t)stackid;
29427 
29428 	kstat_install(ksp);
29429 	return (ksp);
29430 }
29431 
29432 static void
29433 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29434 {
29435 	if (ksp != NULL) {
29436 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29437 		kstat_delete_netstack(ksp, stackid);
29438 	}
29439 }
29440 
29441 static int
29442 icmp_kstat_update(kstat_t *kp, int rw)
29443 {
29444 	icmp_named_kstat_t *icmpkp;
29445 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29446 	netstack_t	*ns;
29447 	ip_stack_t	*ipst;
29448 
29449 	if ((kp == NULL) || (kp->ks_data == NULL))
29450 		return (EIO);
29451 
29452 	if (rw == KSTAT_WRITE)
29453 		return (EACCES);
29454 
29455 	ns = netstack_find_by_stackid(stackid);
29456 	if (ns == NULL)
29457 		return (-1);
29458 	ipst = ns->netstack_ip;
29459 	if (ipst == NULL) {
29460 		netstack_rele(ns);
29461 		return (-1);
29462 	}
29463 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29464 
29465 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29466 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29467 	icmpkp->inDestUnreachs.value.ui32 =
29468 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29469 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29470 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29471 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29472 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29473 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29474 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29475 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29476 	icmpkp->inTimestampReps.value.ui32 =
29477 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29478 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29479 	icmpkp->inAddrMaskReps.value.ui32 =
29480 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29481 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29482 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29483 	icmpkp->outDestUnreachs.value.ui32 =
29484 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29485 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29486 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29487 	icmpkp->outSrcQuenchs.value.ui32 =
29488 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29489 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29490 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29491 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29492 	icmpkp->outTimestamps.value.ui32 =
29493 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29494 	icmpkp->outTimestampReps.value.ui32 =
29495 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29496 	icmpkp->outAddrMasks.value.ui32 =
29497 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29498 	icmpkp->outAddrMaskReps.value.ui32 =
29499 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29500 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29501 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29502 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29503 	icmpkp->outFragNeeded.value.ui32 =
29504 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29505 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29506 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29507 	icmpkp->inBadRedirects.value.ui32 =
29508 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29509 
29510 	netstack_rele(ns);
29511 	return (0);
29512 }
29513 
29514 /*
29515  * This is the fanout function for raw socket opened for SCTP.  Note
29516  * that it is called after SCTP checks that there is no socket which
29517  * wants a packet.  Then before SCTP handles this out of the blue packet,
29518  * this function is called to see if there is any raw socket for SCTP.
29519  * If there is and it is bound to the correct address, the packet will
29520  * be sent to that socket.  Note that only one raw socket can be bound to
29521  * a port.  This is assured in ipcl_sctp_hash_insert();
29522  */
29523 void
29524 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29525     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29526     zoneid_t zoneid)
29527 {
29528 	conn_t		*connp;
29529 	queue_t		*rq;
29530 	mblk_t		*first_mp;
29531 	boolean_t	secure;
29532 	ip6_t		*ip6h;
29533 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29534 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29535 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29536 	boolean_t	sctp_csum_err = B_FALSE;
29537 
29538 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29539 		sctp_csum_err = B_TRUE;
29540 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29541 	}
29542 
29543 	first_mp = mp;
29544 	if (mctl_present) {
29545 		mp = first_mp->b_cont;
29546 		secure = ipsec_in_is_secure(first_mp);
29547 		ASSERT(mp != NULL);
29548 	} else {
29549 		secure = B_FALSE;
29550 	}
29551 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29552 
29553 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29554 	if (connp == NULL) {
29555 		/*
29556 		 * Although raw sctp is not summed, OOB chunks must be.
29557 		 * Drop the packet here if the sctp checksum failed.
29558 		 */
29559 		if (sctp_csum_err) {
29560 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29561 			freemsg(first_mp);
29562 			return;
29563 		}
29564 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29565 		return;
29566 	}
29567 	rq = connp->conn_rq;
29568 	if (!canputnext(rq)) {
29569 		CONN_DEC_REF(connp);
29570 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29571 		freemsg(first_mp);
29572 		return;
29573 	}
29574 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29575 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29576 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29577 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29578 		if (first_mp == NULL) {
29579 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29580 			CONN_DEC_REF(connp);
29581 			return;
29582 		}
29583 	}
29584 	/*
29585 	 * We probably should not send M_CTL message up to
29586 	 * raw socket.
29587 	 */
29588 	if (mctl_present)
29589 		freeb(first_mp);
29590 
29591 	/* Initiate IPPF processing here if needed. */
29592 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29593 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29594 		ip_process(IPP_LOCAL_IN, &mp,
29595 		    recv_ill->ill_phyint->phyint_ifindex);
29596 		if (mp == NULL) {
29597 			CONN_DEC_REF(connp);
29598 			return;
29599 		}
29600 	}
29601 
29602 	if (connp->conn_recvif || connp->conn_recvslla ||
29603 	    ((connp->conn_ip_recvpktinfo ||
29604 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29605 	    (flags & IP_FF_IPINFO))) {
29606 		int in_flags = 0;
29607 
29608 		/*
29609 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29610 		 * IPF_RECVIF.
29611 		 */
29612 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29613 			in_flags = IPF_RECVIF;
29614 		}
29615 		if (connp->conn_recvslla) {
29616 			in_flags |= IPF_RECVSLLA;
29617 		}
29618 		if (isv4) {
29619 			mp = ip_add_info(mp, recv_ill, in_flags,
29620 			    IPCL_ZONEID(connp), ipst);
29621 		} else {
29622 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29623 			if (mp == NULL) {
29624 				BUMP_MIB(recv_ill->ill_ip_mib,
29625 				    ipIfStatsInDiscards);
29626 				CONN_DEC_REF(connp);
29627 				return;
29628 			}
29629 		}
29630 	}
29631 
29632 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29633 	/*
29634 	 * We are sending the IPSEC_IN message also up. Refer
29635 	 * to comments above this function.
29636 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29637 	 */
29638 	(connp->conn_recv)(connp, mp, NULL);
29639 	CONN_DEC_REF(connp);
29640 }
29641 
29642 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29643 {									\
29644 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29645 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29646 }
29647 /*
29648  * This function should be called only if all packet processing
29649  * including fragmentation is complete. Callers of this function
29650  * must set mp->b_prev to one of these values:
29651  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29652  * prior to handing over the mp as first argument to this function.
29653  *
29654  * If the ire passed by caller is incomplete, this function
29655  * queues the packet and if necessary, sends ARP request and bails.
29656  * If the ire passed is fully resolved, we simply prepend
29657  * the link-layer header to the packet, do ipsec hw acceleration
29658  * work if necessary, and send the packet out on the wire.
29659  *
29660  * NOTE: IPsec will only call this function with fully resolved
29661  * ires if hw acceleration is involved.
29662  * TODO list :
29663  * 	a Handle M_MULTIDATA so that
29664  *	  tcp_multisend->tcp_multisend_data can
29665  *	  call ip_xmit_v4 directly
29666  *	b Handle post-ARP work for fragments so that
29667  *	  ip_wput_frag can call this function.
29668  */
29669 ipxmit_state_t
29670 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29671     boolean_t flow_ctl_enabled, conn_t *connp)
29672 {
29673 	nce_t		*arpce;
29674 	ipha_t		*ipha;
29675 	queue_t		*q;
29676 	int		ill_index;
29677 	mblk_t		*nxt_mp, *first_mp;
29678 	boolean_t	xmit_drop = B_FALSE;
29679 	ip_proc_t	proc;
29680 	ill_t		*out_ill;
29681 	int		pkt_len;
29682 
29683 	arpce = ire->ire_nce;
29684 	ASSERT(arpce != NULL);
29685 
29686 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29687 
29688 	mutex_enter(&arpce->nce_lock);
29689 	switch (arpce->nce_state) {
29690 	case ND_REACHABLE:
29691 		/* If there are other queued packets, queue this packet */
29692 		if (arpce->nce_qd_mp != NULL) {
29693 			if (mp != NULL)
29694 				nce_queue_mp_common(arpce, mp, B_FALSE);
29695 			mp = arpce->nce_qd_mp;
29696 		}
29697 		arpce->nce_qd_mp = NULL;
29698 		mutex_exit(&arpce->nce_lock);
29699 
29700 		/*
29701 		 * Flush the queue.  In the common case, where the
29702 		 * ARP is already resolved,  it will go through the
29703 		 * while loop only once.
29704 		 */
29705 		while (mp != NULL) {
29706 
29707 			nxt_mp = mp->b_next;
29708 			mp->b_next = NULL;
29709 			ASSERT(mp->b_datap->db_type != M_CTL);
29710 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29711 			/*
29712 			 * This info is needed for IPQOS to do COS marking
29713 			 * in ip_wput_attach_llhdr->ip_process.
29714 			 */
29715 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29716 			mp->b_prev = NULL;
29717 
29718 			/* set up ill index for outbound qos processing */
29719 			out_ill = ire_to_ill(ire);
29720 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29721 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29722 			    ill_index, &ipha);
29723 			if (first_mp == NULL) {
29724 				xmit_drop = B_TRUE;
29725 				BUMP_MIB(out_ill->ill_ip_mib,
29726 				    ipIfStatsOutDiscards);
29727 				goto next_mp;
29728 			}
29729 
29730 			/* non-ipsec hw accel case */
29731 			if (io == NULL || !io->ipsec_out_accelerated) {
29732 				/* send it */
29733 				q = ire->ire_stq;
29734 				if (proc == IPP_FWD_OUT) {
29735 					UPDATE_IB_PKT_COUNT(ire);
29736 				} else {
29737 					UPDATE_OB_PKT_COUNT(ire);
29738 				}
29739 				ire->ire_last_used_time = lbolt;
29740 
29741 				if (flow_ctl_enabled || canputnext(q)) {
29742 					if (proc == IPP_FWD_OUT) {
29743 
29744 					BUMP_MIB(out_ill->ill_ip_mib,
29745 					    ipIfStatsHCOutForwDatagrams);
29746 
29747 					}
29748 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29749 					    pkt_len);
29750 
29751 					DTRACE_IP7(send, mblk_t *, first_mp,
29752 					    conn_t *, NULL, void_ip_t *, ipha,
29753 					    __dtrace_ipsr_ill_t *, out_ill,
29754 					    ipha_t *, ipha, ip6_t *, NULL, int,
29755 					    0);
29756 
29757 					ILL_SEND_TX(out_ill,
29758 					    ire, connp, first_mp, 0, connp);
29759 				} else {
29760 					BUMP_MIB(out_ill->ill_ip_mib,
29761 					    ipIfStatsOutDiscards);
29762 					xmit_drop = B_TRUE;
29763 					freemsg(first_mp);
29764 				}
29765 			} else {
29766 				/*
29767 				 * Safety Pup says: make sure this
29768 				 *  is going to the right interface!
29769 				 */
29770 				ill_t *ill1 =
29771 				    (ill_t *)ire->ire_stq->q_ptr;
29772 				int ifindex =
29773 				    ill1->ill_phyint->phyint_ifindex;
29774 				if (ifindex !=
29775 				    io->ipsec_out_capab_ill_index) {
29776 					xmit_drop = B_TRUE;
29777 					freemsg(mp);
29778 				} else {
29779 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29780 					    pkt_len);
29781 
29782 					DTRACE_IP7(send, mblk_t *, first_mp,
29783 					    conn_t *, NULL, void_ip_t *, ipha,
29784 					    __dtrace_ipsr_ill_t *, ill1,
29785 					    ipha_t *, ipha, ip6_t *, NULL,
29786 					    int, 0);
29787 
29788 					ipsec_hw_putnext(ire->ire_stq, mp);
29789 				}
29790 			}
29791 next_mp:
29792 			mp = nxt_mp;
29793 		} /* while (mp != NULL) */
29794 		if (xmit_drop)
29795 			return (SEND_FAILED);
29796 		else
29797 			return (SEND_PASSED);
29798 
29799 	case ND_INITIAL:
29800 	case ND_INCOMPLETE:
29801 
29802 		/*
29803 		 * While we do send off packets to dests that
29804 		 * use fully-resolved CGTP routes, we do not
29805 		 * handle unresolved CGTP routes.
29806 		 */
29807 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29808 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29809 
29810 		if (mp != NULL) {
29811 			/* queue the packet */
29812 			nce_queue_mp_common(arpce, mp, B_FALSE);
29813 		}
29814 
29815 		if (arpce->nce_state == ND_INCOMPLETE) {
29816 			mutex_exit(&arpce->nce_lock);
29817 			DTRACE_PROBE3(ip__xmit__incomplete,
29818 			    (ire_t *), ire, (mblk_t *), mp,
29819 			    (ipsec_out_t *), io);
29820 			return (LOOKUP_IN_PROGRESS);
29821 		}
29822 
29823 		arpce->nce_state = ND_INCOMPLETE;
29824 		mutex_exit(&arpce->nce_lock);
29825 
29826 		/*
29827 		 * Note that ire_add() (called from ire_forward())
29828 		 * holds a ref on the ire until ARP is completed.
29829 		 */
29830 		ire_arpresolve(ire);
29831 		return (LOOKUP_IN_PROGRESS);
29832 	default:
29833 		ASSERT(0);
29834 		mutex_exit(&arpce->nce_lock);
29835 		return (LLHDR_RESLV_FAILED);
29836 	}
29837 }
29838 
29839 #undef	UPDATE_IP_MIB_OB_COUNTERS
29840 
29841 /*
29842  * Return B_TRUE if the buffers differ in length or content.
29843  * This is used for comparing extension header buffers.
29844  * Note that an extension header would be declared different
29845  * even if all that changed was the next header value in that header i.e.
29846  * what really changed is the next extension header.
29847  */
29848 boolean_t
29849 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29850     uint_t blen)
29851 {
29852 	if (!b_valid)
29853 		blen = 0;
29854 
29855 	if (alen != blen)
29856 		return (B_TRUE);
29857 	if (alen == 0)
29858 		return (B_FALSE);	/* Both zero length */
29859 	return (bcmp(abuf, bbuf, alen));
29860 }
29861 
29862 /*
29863  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29864  * Return B_FALSE if memory allocation fails - don't change any state!
29865  */
29866 boolean_t
29867 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29868     const void *src, uint_t srclen)
29869 {
29870 	void *dst;
29871 
29872 	if (!src_valid)
29873 		srclen = 0;
29874 
29875 	ASSERT(*dstlenp == 0);
29876 	if (src != NULL && srclen != 0) {
29877 		dst = mi_alloc(srclen, BPRI_MED);
29878 		if (dst == NULL)
29879 			return (B_FALSE);
29880 	} else {
29881 		dst = NULL;
29882 	}
29883 	if (*dstp != NULL)
29884 		mi_free(*dstp);
29885 	*dstp = dst;
29886 	*dstlenp = dst == NULL ? 0 : srclen;
29887 	return (B_TRUE);
29888 }
29889 
29890 /*
29891  * Replace what is in *dst, *dstlen with the source.
29892  * Assumes ip_allocbuf has already been called.
29893  */
29894 void
29895 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29896     const void *src, uint_t srclen)
29897 {
29898 	if (!src_valid)
29899 		srclen = 0;
29900 
29901 	ASSERT(*dstlenp == srclen);
29902 	if (src != NULL && srclen != 0)
29903 		bcopy(src, *dstp, srclen);
29904 }
29905 
29906 /*
29907  * Free the storage pointed to by the members of an ip6_pkt_t.
29908  */
29909 void
29910 ip6_pkt_free(ip6_pkt_t *ipp)
29911 {
29912 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29913 
29914 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29915 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29916 		ipp->ipp_hopopts = NULL;
29917 		ipp->ipp_hopoptslen = 0;
29918 	}
29919 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29920 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29921 		ipp->ipp_rtdstopts = NULL;
29922 		ipp->ipp_rtdstoptslen = 0;
29923 	}
29924 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29925 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29926 		ipp->ipp_dstopts = NULL;
29927 		ipp->ipp_dstoptslen = 0;
29928 	}
29929 	if (ipp->ipp_fields & IPPF_RTHDR) {
29930 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29931 		ipp->ipp_rthdr = NULL;
29932 		ipp->ipp_rthdrlen = 0;
29933 	}
29934 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29935 	    IPPF_RTHDR);
29936 }
29937 
29938 zoneid_t
29939 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29940     zoneid_t lookup_zoneid)
29941 {
29942 	ire_t		*ire;
29943 	int		ire_flags = MATCH_IRE_TYPE;
29944 	zoneid_t	zoneid = ALL_ZONES;
29945 
29946 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29947 		return (ALL_ZONES);
29948 
29949 	if (lookup_zoneid != ALL_ZONES)
29950 		ire_flags |= MATCH_IRE_ZONEONLY;
29951 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29952 	    lookup_zoneid, NULL, ire_flags, ipst);
29953 	if (ire != NULL) {
29954 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29955 		ire_refrele(ire);
29956 	}
29957 	return (zoneid);
29958 }
29959 
29960 zoneid_t
29961 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29962     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29963 {
29964 	ire_t		*ire;
29965 	int		ire_flags = MATCH_IRE_TYPE;
29966 	zoneid_t	zoneid = ALL_ZONES;
29967 	ipif_t		*ipif_arg = NULL;
29968 
29969 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29970 		return (ALL_ZONES);
29971 
29972 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29973 		ire_flags |= MATCH_IRE_ILL;
29974 		ipif_arg = ill->ill_ipif;
29975 	}
29976 	if (lookup_zoneid != ALL_ZONES)
29977 		ire_flags |= MATCH_IRE_ZONEONLY;
29978 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29979 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29980 	if (ire != NULL) {
29981 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29982 		ire_refrele(ire);
29983 	}
29984 	return (zoneid);
29985 }
29986 
29987 /*
29988  * IP obserability hook support functions.
29989  */
29990 
29991 static void
29992 ipobs_init(ip_stack_t *ipst)
29993 {
29994 	ipst->ips_ipobs_enabled = B_FALSE;
29995 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
29996 	    offsetof(ipobs_cb_t, ipobs_cbnext));
29997 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
29998 	ipst->ips_ipobs_cb_nwalkers = 0;
29999 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30000 }
30001 
30002 static void
30003 ipobs_fini(ip_stack_t *ipst)
30004 {
30005 	ipobs_cb_t *cb;
30006 
30007 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30008 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30009 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30010 
30011 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30012 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30013 		kmem_free(cb, sizeof (*cb));
30014 	}
30015 	list_destroy(&ipst->ips_ipobs_cb_list);
30016 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30017 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30018 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30019 }
30020 
30021 void
30022 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30023     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30024 {
30025 	mblk_t *mp2;
30026 	ipobs_cb_t *ipobs_cb;
30027 	ipobs_hook_data_t *ihd;
30028 	uint64_t grifindex = 0;
30029 
30030 	ASSERT(DB_TYPE(mp) == M_DATA);
30031 
30032 	if (IS_UNDER_IPMP(ill))
30033 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
30034 
30035 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30036 	ipst->ips_ipobs_cb_nwalkers++;
30037 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30038 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30039 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30040 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
30041 		if (mp2 != NULL) {
30042 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
30043 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30044 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30045 				freemsg(mp2);
30046 				continue;
30047 			}
30048 			ihd->ihd_mp->b_rptr += hlen;
30049 			ihd->ihd_htype = htype;
30050 			ihd->ihd_ipver = ipver;
30051 			ihd->ihd_zsrc = zsrc;
30052 			ihd->ihd_zdst = zdst;
30053 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30054 			ihd->ihd_grifindex = grifindex;
30055 			ihd->ihd_stack = ipst->ips_netstack;
30056 			mp2->b_wptr += sizeof (*ihd);
30057 			ipobs_cb->ipobs_cbfunc(mp2);
30058 		}
30059 	}
30060 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30061 	ipst->ips_ipobs_cb_nwalkers--;
30062 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30063 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30064 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30065 }
30066 
30067 void
30068 ipobs_register_hook(netstack_t *ns, pfv_t func)
30069 {
30070 	ipobs_cb_t   *cb;
30071 	ip_stack_t *ipst = ns->netstack_ip;
30072 
30073 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30074 
30075 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30076 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30077 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30078 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30079 
30080 	cb->ipobs_cbfunc = func;
30081 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30082 	ipst->ips_ipobs_enabled = B_TRUE;
30083 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30084 }
30085 
30086 void
30087 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30088 {
30089 	ipobs_cb_t	*curcb;
30090 	ip_stack_t	*ipst = ns->netstack_ip;
30091 
30092 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30093 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30094 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30095 
30096 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30097 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30098 		if (func == curcb->ipobs_cbfunc) {
30099 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30100 			kmem_free(curcb, sizeof (*curcb));
30101 			break;
30102 		}
30103 	}
30104 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30105 		ipst->ips_ipobs_enabled = B_FALSE;
30106 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30107 }
30108