xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 581cede61ac9c14d8d4ea452562a567189eead78)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 #include <sys/squeue_impl.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	uint_t		ird_flags;	/* see below */
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 #define	IRD_REPORT_TESTHIDDEN	0x01	/* include IRE_MARK_TESTHIDDEN routes */
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, certain multicast operations, most set ioctls,
236  * igmp/mld timers etc.
237  *
238  * Plumbing is a long sequence of operations involving message
239  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
240  * involved in plumbing operations. A natural model is to serialize these
241  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
242  * parallel without any interference. But various set ioctls on hme0 are best
243  * serialized, along with multicast join/leave operations, igmp/mld timer
244  * operations, and processing of DLPI control messages received from drivers
245  * on a per phyint basis.  This serialization is provided by the ipsq_t and
246  * primitives operating on this. Details can be found in ip_if.c above the
247  * core primitives operating on ipsq_t.
248  *
249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
251  * In addition ipif's and ill's referenced by the ire are also indirectly
252  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
253  * the ipif's address or netmask change as long as an ipif is refheld
254  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
255  * address of an ipif has to go through the ipsq_t. This ensures that only
256  * 1 such exclusive operation proceeds at any time on the ipif. It then
257  * deletes all ires associated with this ipif, and waits for all refcnts
258  * associated with this ipif to come down to zero. The address is changed
259  * only after the ipif has been quiesced. Then the ipif is brought up again.
260  * More details are described above the comment in ip_sioctl_flags.
261  *
262  * Packet processing is based mostly on IREs and are fully multi-threaded
263  * using standard Solaris MT techniques.
264  *
265  * There are explicit locks in IP to handle:
266  * - The ip_g_head list maintained by mi_open_link() and friends.
267  *
268  * - The reassembly data structures (one lock per hash bucket)
269  *
270  * - conn_lock is meant to protect conn_t fields. The fields actually
271  *   protected by conn_lock are documented in the conn_t definition.
272  *
273  * - ire_lock to protect some of the fields of the ire, IRE tables
274  *   (one lock per hash bucket). Refer to ip_ire.c for details.
275  *
276  * - ndp_g_lock and nce_lock for protecting NCEs.
277  *
278  * - ill_lock protects fields of the ill and ipif. Details in ip.h
279  *
280  * - ill_g_lock: This is a global reader/writer lock. Protects the following
281  *	* The AVL tree based global multi list of all ills.
282  *	* The linked list of all ipifs of an ill
283  *	* The <ipsq-xop> mapping
284  *	* <ill-phyint> association
285  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
286  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
287  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
288  *   writer for the actual duration of the insertion/deletion/change.
289  *
290  * - ill_lock:  This is a per ill mutex.
291  *   It protects some members of the ill_t struct; see ip.h for details.
292  *   It also protects the <ill-phyint> assoc.
293  *   It also protects the list of ipifs hanging off the ill.
294  *
295  * - ipsq_lock: This is a per ipsq_t mutex lock.
296  *   This protects some members of the ipsq_t struct; see ip.h for details.
297  *   It also protects the <ipsq-ipxop> mapping
298  *
299  * - ipx_lock: This is a per ipxop_t mutex lock.
300  *   This protects some members of the ipxop_t struct; see ip.h for details.
301  *
302  * - phyint_lock: This is a per phyint mutex lock. Protects just the
303  *   phyint_flags
304  *
305  * - ip_g_nd_lock: This is a global reader/writer lock.
306  *   Any call to nd_load to load a new parameter to the ND table must hold the
307  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
308  *   as reader.
309  *
310  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
311  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
312  *   uniqueness check also done atomically.
313  *
314  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
315  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
316  *   as a writer when adding or deleting elements from these lists, and
317  *   as a reader when walking these lists to send a SADB update to the
318  *   IPsec capable ills.
319  *
320  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
321  *   group list linked by ill_usesrc_grp_next. It also protects the
322  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
323  *   group is being added or deleted.  This lock is taken as a reader when
324  *   walking the list/group(eg: to get the number of members in a usesrc group).
325  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
326  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
327  *   example, it is not necessary to take this lock in the initial portion
328  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
329  *   operations are executed exclusively and that ensures that the "usesrc
330  *   group state" cannot change. The "usesrc group state" change can happen
331  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
332  *
333  * Changing <ill-phyint>, <ipsq-xop> assocications:
334  *
335  * To change the <ill-phyint> association, the ill_g_lock must be held
336  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
337  * must be held.
338  *
339  * To change the <ipsq-xop> association, the ill_g_lock must be held as
340  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
341  * This is only done when ills are added or removed from IPMP groups.
342  *
343  * To add or delete an ipif from the list of ipifs hanging off the ill,
344  * ill_g_lock (writer) and ill_lock must be held and the thread must be
345  * a writer on the associated ipsq.
346  *
347  * To add or delete an ill to the system, the ill_g_lock must be held as
348  * writer and the thread must be a writer on the associated ipsq.
349  *
350  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
351  * must be a writer on the associated ipsq.
352  *
353  * Lock hierarchy
354  *
355  * Some lock hierarchy scenarios are listed below.
356  *
357  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
358  * ill_g_lock -> ill_lock(s) -> phyint_lock
359  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
360  * ill_g_lock -> ip_addr_avail_lock
361  * conn_lock -> irb_lock -> ill_lock -> ire_lock
362  * ill_g_lock -> ip_g_nd_lock
363  *
364  * When more than 1 ill lock is needed to be held, all ill lock addresses
365  * are sorted on address and locked starting from highest addressed lock
366  * downward.
367  *
368  * IPsec scenarios
369  *
370  * ipsa_lock -> ill_g_lock -> ill_lock
371  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
372  * ipsec_capab_ills_lock -> ipsa_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IPsec notes :
417  *
418  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
419  * in front of the actual packet. For outbound datagrams, the M_CTL
420  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
421  * information used by the IPsec code for applying the right level of
422  * protection. The information initialized by IP in the ipsec_out_t
423  * is determined by the per-socket policy or global policy in the system.
424  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
425  * ipsec_info.h) which starts out with nothing in it. It gets filled
426  * with the right information if it goes through the AH/ESP code, which
427  * happens if the incoming packet is secure. The information initialized
428  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
429  * the policy requirements needed by per-socket policy or global policy
430  * is met or not.
431  *
432  * If there is both per-socket policy (set using setsockopt) and there
433  * is also global policy match for the 5 tuples of the socket,
434  * ipsec_override_policy() makes the decision of which one to use.
435  *
436  * For fully connected sockets i.e dst, src [addr, port] is known,
437  * conn_policy_cached is set indicating that policy has been cached.
438  * conn_in_enforce_policy may or may not be set depending on whether
439  * there is a global policy match or per-socket policy match.
440  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
441  * Once the right policy is set on the conn_t, policy cannot change for
442  * this socket. This makes life simpler for TCP (UDP ?) where
443  * re-transmissions go out with the same policy. For symmetry, policy
444  * is cached for fully connected UDP sockets also. Thus if policy is cached,
445  * it also implies that policy is latched i.e policy cannot change
446  * on these sockets. As we have the right policy on the conn, we don't
447  * have to lookup global policy for every outbound and inbound datagram
448  * and thus serving as an optimization. Note that a global policy change
449  * does not affect fully connected sockets if they have policy. If fully
450  * connected sockets did not have any policy associated with it, global
451  * policy change may affect them.
452  *
453  * IP Flow control notes:
454  * ---------------------
455  * Non-TCP streams are flow controlled by IP. The way this is accomplished
456  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
457  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
458  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
459  * functions.
460  *
461  * Per Tx ring udp flow control:
462  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
463  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
464  *
465  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
466  * To achieve best performance, outgoing traffic need to be fanned out among
467  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
468  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
469  * the address of connp as fanout hint to mac_tx(). Under flow controlled
470  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
471  * cookie points to a specific Tx ring that is blocked. The cookie is used to
472  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
473  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
474  * connp's. The drain list is not a single list but a configurable number of
475  * lists.
476  *
477  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
478  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
479  * which is equal to 128. This array in turn contains a pointer to idl_t[],
480  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
481  * list will point to the list of connp's that are flow controlled.
482  *
483  *                      ---------------   -------   -------   -------
484  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   |  ---------------   -------   -------   -------
487  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
488  * ----------------  |  ---------------   -------   -------   -------
489  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
490  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
491  *                   |  ---------------   -------   -------   -------
492  *                   .        .              .         .         .
493  *                   |  ---------------   -------   -------   -------
494  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
495  *                      ---------------   -------   -------   -------
496  *                      ---------------   -------   -------   -------
497  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
498  *                   |  ---------------   -------   -------   -------
499  *                   |  ---------------   -------   -------   -------
500  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
501  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
502  * ----------------  |        .              .         .         .
503  *                   |  ---------------   -------   -------   -------
504  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
505  *                      ---------------   -------   -------   -------
506  *     .....
507  * ----------------
508  * |idl_tx_list[n]|-> ...
509  * ----------------
510  *
511  * When mac_tx() returns a cookie, the cookie is used to hash into a
512  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
513  * called passing idl_tx_list. The connp gets inserted in a drain list
514  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
515  * the sockets (non stream based) and sets QFULL condition for conn_wq.
516  * connp->conn_direct_blocked will be set to indicate the blocked
517  * condition.
518  *
519  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
520  * A cookie is passed in the call to ill_flow_enable() that identifies the
521  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
522  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
523  * and goes through each of the drain list (q)enabling the conn_wq of the
524  * first conn in each of the drain list. This causes ip_wsrv to run for the
525  * conn. ip_wsrv drains the queued messages, and removes the conn from the
526  * drain list, if all messages were drained. It also qenables the next conn
527  * in the drain list to continue the drain process.
528  *
529  * In reality the drain list is not a single list, but a configurable number
530  * of lists. conn_drain_walk() in the IP module, qenables the first conn in
531  * each list. If the ip_wsrv of the next qenabled conn does not run, because
532  * the stream closes, ip_close takes responsibility to qenable the next conn
533  * in the drain list. conn_drain_insert and conn_drain_tail are the only
534  * functions that manipulate this drain list. conn_drain_insert is called in
535  * ip_wput context itself (as opposed to from ip_wsrv context for STREAMS
536  * case -- see below). The synchronization between drain insertion and flow
537  * control wakeup is handled by using idl_txl->txl_lock.
538  *
539  * Flow control using STREAMS:
540  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
541  * is used. On the send side, if the packet cannot be sent down to the
542  * driver by IP, because of a canput failure, IP does a putq on the conn_wq.
543  * This will cause ip_wsrv to run on the conn_wq. ip_wsrv in turn, inserts
544  * the conn in a list of conn's that need to be drained when the flow
545  * control condition subsides. The blocked connps are put in first member
546  * of ips_idl_tx_list[] array. Ultimately STREAMS backenables the ip_wsrv
547  * on the IP module. It calls conn_walk_drain() passing ips_idl_tx_list[0].
548  * ips_idl_tx_list[0] contains the drain lists of blocked conns. The
549  * conn_wq of the first conn in the drain lists is (q)enabled to run.
550  * ip_wsrv on this conn drains the queued messages, and removes the conn
551  * from the drain list, if all messages were drained. It also qenables the
552  * next conn in the drain list to continue the drain process.
553  *
554  * If the ip_wsrv of the next qenabled conn does not run, because the
555  * stream closes, ip_close takes responsibility to qenable the next conn in
556  * the drain list. The directly called ip_wput path always does a putq, if
557  * it cannot putnext. Thus synchronization problems are handled between
558  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
559  * functions that manipulate this drain list. Furthermore conn_drain_insert
560  * is called only from ip_wsrv for the STREAMS case, and there can be only 1
561  * instance of ip_wsrv running on a queue at any time. conn_drain_tail can
562  * be simultaneously called from both ip_wsrv and ip_close.
563  *
564  * IPQOS notes:
565  *
566  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
567  * and IPQoS modules. IPPF includes hooks in IP at different control points
568  * (callout positions) which direct packets to IPQoS modules for policy
569  * processing. Policies, if present, are global.
570  *
571  * The callout positions are located in the following paths:
572  *		o local_in (packets destined for this host)
573  *		o local_out (packets orginating from this host )
574  *		o fwd_in  (packets forwarded by this m/c - inbound)
575  *		o fwd_out (packets forwarded by this m/c - outbound)
576  * Hooks at these callout points can be enabled/disabled using the ndd variable
577  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
578  * By default all the callout positions are enabled.
579  *
580  * Outbound (local_out)
581  * Hooks are placed in ip_wput_ire and ipsec_out_process.
582  *
583  * Inbound (local_in)
584  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
585  * TCP and UDP fanout routines.
586  *
587  * Forwarding (in and out)
588  * Hooks are placed in ip_rput_forward.
589  *
590  * IP Policy Framework processing (IPPF processing)
591  * Policy processing for a packet is initiated by ip_process, which ascertains
592  * that the classifier (ipgpc) is loaded and configured, failing which the
593  * packet resumes normal processing in IP. If the clasifier is present, the
594  * packet is acted upon by one or more IPQoS modules (action instances), per
595  * filters configured in ipgpc and resumes normal IP processing thereafter.
596  * An action instance can drop a packet in course of its processing.
597  *
598  * A boolean variable, ip_policy, is used in all the fanout routines that can
599  * invoke ip_process for a packet. This variable indicates if the packet should
600  * to be sent for policy processing. The variable is set to B_TRUE by default,
601  * i.e. when the routines are invoked in the normal ip procesing path for a
602  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
603  * ip_policy is set to B_FALSE for all the routines called in these two
604  * functions because, in the former case,  we don't process loopback traffic
605  * currently while in the latter, the packets have already been processed in
606  * icmp_inbound.
607  *
608  * Zones notes:
609  *
610  * The partitioning rules for networking are as follows:
611  * 1) Packets coming from a zone must have a source address belonging to that
612  * zone.
613  * 2) Packets coming from a zone can only be sent on a physical interface on
614  * which the zone has an IP address.
615  * 3) Between two zones on the same machine, packet delivery is only allowed if
616  * there's a matching route for the destination and zone in the forwarding
617  * table.
618  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
619  * different zones can bind to the same port with the wildcard address
620  * (INADDR_ANY).
621  *
622  * The granularity of interface partitioning is at the logical interface level.
623  * Therefore, every zone has its own IP addresses, and incoming packets can be
624  * attributed to a zone unambiguously. A logical interface is placed into a zone
625  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
626  * structure. Rule (1) is implemented by modifying the source address selection
627  * algorithm so that the list of eligible addresses is filtered based on the
628  * sending process zone.
629  *
630  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
631  * across all zones, depending on their type. Here is the break-up:
632  *
633  * IRE type				Shared/exclusive
634  * --------				----------------
635  * IRE_BROADCAST			Exclusive
636  * IRE_DEFAULT (default routes)		Shared (*)
637  * IRE_LOCAL				Exclusive (x)
638  * IRE_LOOPBACK				Exclusive
639  * IRE_PREFIX (net routes)		Shared (*)
640  * IRE_CACHE				Exclusive
641  * IRE_IF_NORESOLVER (interface routes)	Exclusive
642  * IRE_IF_RESOLVER (interface routes)	Exclusive
643  * IRE_HOST (host routes)		Shared (*)
644  *
645  * (*) A zone can only use a default or off-subnet route if the gateway is
646  * directly reachable from the zone, that is, if the gateway's address matches
647  * one of the zone's logical interfaces.
648  *
649  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
650  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
651  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
652  * address of the zone itself (the destination). Since IRE_LOCAL is used
653  * for communication between zones, ip_wput_ire has special logic to set
654  * the right source address when sending using an IRE_LOCAL.
655  *
656  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
657  * ire_cache_lookup restricts loopback using an IRE_LOCAL
658  * between zone to the case when L2 would have conceptually looped the packet
659  * back, i.e. the loopback which is required since neither Ethernet drivers
660  * nor Ethernet hardware loops them back. This is the case when the normal
661  * routes (ignoring IREs with different zoneids) would send out the packet on
662  * the same ill as the ill with which is IRE_LOCAL is associated.
663  *
664  * Multiple zones can share a common broadcast address; typically all zones
665  * share the 255.255.255.255 address. Incoming as well as locally originated
666  * broadcast packets must be dispatched to all the zones on the broadcast
667  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
668  * since some zones may not be on the 10.16.72/24 network. To handle this, each
669  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
670  * sent to every zone that has an IRE_BROADCAST entry for the destination
671  * address on the input ill, see conn_wantpacket().
672  *
673  * Applications in different zones can join the same multicast group address.
674  * For IPv4, group memberships are per-logical interface, so they're already
675  * inherently part of a zone. For IPv6, group memberships are per-physical
676  * interface, so we distinguish IPv6 group memberships based on group address,
677  * interface and zoneid. In both cases, received multicast packets are sent to
678  * every zone for which a group membership entry exists. On IPv6 we need to
679  * check that the target zone still has an address on the receiving physical
680  * interface; it could have been removed since the application issued the
681  * IPV6_JOIN_GROUP.
682  */
683 
684 /*
685  * Squeue Fanout flags:
686  *	0: No fanout.
687  *	1: Fanout across all squeues
688  */
689 boolean_t	ip_squeue_fanout = 0;
690 
691 /*
692  * Maximum dups allowed per packet.
693  */
694 uint_t ip_max_frag_dups = 10;
695 
696 #define	IS_SIMPLE_IPH(ipha)						\
697 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
698 
699 /* RFC 1122 Conformance */
700 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
701 
702 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
703 
704 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
705 
706 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
707 		    cred_t *credp, boolean_t isv6);
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
709 		    ipha_t **);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
712 		    ip_stack_t *);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int, ip_stack_t *);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
723 		    ip_stack_t *);
724 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
725 		    zoneid_t zoneid, ip_stack_t *);
726 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
727 static void	icmp_redirect(ill_t *, mblk_t *);
728 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
729 		    ip_stack_t *);
730 
731 static void	ip_arp_news(queue_t *, mblk_t *);
732 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
733 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
734 char		*ip_dot_addr(ipaddr_t, char *);
735 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
736 int		ip_close(queue_t *, int);
737 static char	*ip_dot_saddr(uchar_t *, char *);
738 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, ill_t *, zoneid_t);
740 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
741 		    boolean_t, boolean_t, zoneid_t);
742 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
743 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
744 static void	ip_lrput(queue_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
747 		    ip_stack_t *);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
755     ipndp_t *, size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
762     ip_stack_t *);
763 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
764 			    ire_t *, ip_stack_t *);
765 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
766 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
767 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
768     ip_stack_t *);
769 static boolean_t ip_rput_fragment(ill_t *, ill_t *, mblk_t **, ipha_t *,
770     uint32_t *, uint16_t *);
771 int		ip_snmp_get(queue_t *, mblk_t *, int);
772 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
773 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
775 		    ip_stack_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
777 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
778 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
779 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
780 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
781 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
782 		    ip_stack_t *ipst);
783 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
784 		    ip_stack_t *ipst);
785 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
786 		    ip_stack_t *ipst);
787 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
788 		    ip_stack_t *ipst);
789 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
790 		    ip_stack_t *ipst);
791 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
792 		    ip_stack_t *ipst);
793 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
794 		    ip_stack_t *ipst);
795 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
796 		    ip_stack_t *ipst);
797 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
798 		    ip_stack_t *ipst);
799 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
800 		    ip_stack_t *ipst);
801 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
802 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
803 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
804 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
805 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
806 static boolean_t	ip_source_route_included(ipha_t *);
807 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
808 
809 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
810 		    zoneid_t, ip_stack_t *, conn_t *);
811 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *,
812 		    mblk_t *);
813 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
814 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
815 		    zoneid_t, ip_stack_t *);
816 
817 static void	conn_drain_init(ip_stack_t *);
818 static void	conn_drain_fini(ip_stack_t *);
819 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
820 
821 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
822 static void	conn_setqfull(conn_t *);
823 static void	conn_clrqfull(conn_t *);
824 
825 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
826 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
827 static void	ip_stack_fini(netstackid_t stackid, void *arg);
828 
829 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
830     zoneid_t);
831 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
832     void *dummy_arg);
833 
834 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
835 
836 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
837     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
838     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
839 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
840 
841 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
842 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
843     caddr_t, cred_t *);
844 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
845     cred_t *, boolean_t);
846 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
847     caddr_t cp, cred_t *cr);
848 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
849     cred_t *);
850 static int	ip_squeue_switch(int);
851 
852 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
853 static void	ip_kstat_fini(netstackid_t, kstat_t *);
854 static int	ip_kstat_update(kstat_t *kp, int rw);
855 static void	*icmp_kstat_init(netstackid_t);
856 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
857 static int	icmp_kstat_update(kstat_t *kp, int rw);
858 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
859 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
860 
861 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
862     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
863 
864 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
865     ipha_t *, ill_t *, boolean_t, boolean_t);
866 
867 static void ipobs_init(ip_stack_t *);
868 static void ipobs_fini(ip_stack_t *);
869 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
870 
871 /* How long, in seconds, we allow frags to hang around. */
872 #define	IP_FRAG_TIMEOUT		15
873 #define	IPV6_FRAG_TIMEOUT	60
874 
875 /*
876  * Threshold which determines whether MDT should be used when
877  * generating IP fragments; payload size must be greater than
878  * this threshold for MDT to take place.
879  */
880 #define	IP_WPUT_FRAG_MDT_MIN	32768
881 
882 /* Setable in /etc/system only */
883 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
884 
885 static long ip_rput_pullups;
886 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
887 
888 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
889 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
890 
891 int	ip_debug;
892 
893 #ifdef DEBUG
894 uint32_t ipsechw_debug = 0;
895 #endif
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
901 
902 /*
903  * XXX following really should only be in a header. Would need more
904  * header and .c clean up first.
905  */
906 extern optdb_obj_t	ip_opt_obj;
907 
908 ulong_t ip_squeue_enter_unbound = 0;
909 
910 /*
911  * Named Dispatch Parameter Table.
912  * All of these are alterable, within the min/max values given, at run time.
913  */
914 static ipparam_t	lcl_param_arr[] = {
915 	/* min	max	value	name */
916 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
917 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
918 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
919 	{  0,	1,	0,	"ip_respond_to_timestamp"},
920 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
921 	{  0,	1,	1,	"ip_send_redirects"},
922 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
923 	{  0,	10,	0,	"ip_mrtdebug"},
924 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
925 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
926 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
927 	{  1,	255,	255,	"ip_def_ttl" },
928 	{  0,	1,	0,	"ip_forward_src_routed"},
929 	{  0,	256,	32,	"ip_wroff_extra" },
930 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
931 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
932 	{  0,	1,	1,	"ip_path_mtu_discovery" },
933 	{  0,	240,	30,	"ip_ignore_delete_time" },
934 	{  0,	1,	0,	"ip_ignore_redirect" },
935 	{  0,	1,	1,	"ip_output_queue" },
936 	{  1,	254,	1,	"ip_broadcast_ttl" },
937 	{  0,	99999,	100,	"ip_icmp_err_interval" },
938 	{  1,	99999,	10,	"ip_icmp_err_burst" },
939 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
940 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
941 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
942 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
943 	{  0,	1,	1,	"icmp_accept_clear_messages" },
944 	{  0,	1,	1,	"igmp_accept_clear_messages" },
945 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
946 				"ip_ndp_delay_first_probe_time"},
947 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
948 				"ip_ndp_max_unicast_solicit"},
949 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
950 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
951 	{  0,	1,	0,	"ip6_forward_src_routed"},
952 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
953 	{  0,	1,	1,	"ip6_send_redirects"},
954 	{  0,	1,	0,	"ip6_ignore_redirect" },
955 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
956 
957 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
958 
959 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
960 
961 	{  0,	1,	1,	"pim_accept_clear_messages" },
962 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
963 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
964 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
965 	{  0,	15,	0,	"ip_policy_mask" },
966 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
967 	{  0,	255,	1,	"ip_multirt_ttl" },
968 	{  0,	1,	1,	"ip_multidata_outbound" },
969 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
970 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
971 	{  0,	1000,	1,	"ip_max_temp_defend" },
972 	{  0,	1000,	3,	"ip_max_defend" },
973 	{  0,	999999,	30,	"ip_defend_interval" },
974 	{  0,	3600000, 300000, "ip_dup_recovery" },
975 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
976 	{  0,	1,	1,	"ip_lso_outbound" },
977 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
978 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
979 	{ 68,	65535,	576,	"ip_pmtu_min" },
980 #ifdef DEBUG
981 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
982 #else
983 	{  0,	0,	0,	"" },
984 #endif
985 };
986 
987 /*
988  * Extended NDP table
989  * The addresses for the first two are filled in to be ips_ip_g_forward
990  * and ips_ipv6_forward at init time.
991  */
992 static ipndp_t	lcl_ndp_arr[] = {
993 	/* getf			setf		data			name */
994 #define	IPNDP_IP_FORWARDING_OFFSET	0
995 	{  ip_param_generic_get,	ip_forward_set,	NULL,
996 	    "ip_forwarding" },
997 #define	IPNDP_IP6_FORWARDING_OFFSET	1
998 	{  ip_param_generic_get,	ip_forward_set,	NULL,
999 	    "ip6_forwarding" },
1000 	{ ip_param_generic_get, ip_input_proc_set,
1001 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1002 	{ ip_param_generic_get, ip_int_set,
1003 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1004 #define	IPNDP_CGTP_FILTER_OFFSET	4
1005 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1006 	    "ip_cgtp_filter" },
1007 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1008 	    "ip_debug" },
1009 };
1010 
1011 /*
1012  * Table of IP ioctls encoding the various properties of the ioctl and
1013  * indexed based on the last byte of the ioctl command. Occasionally there
1014  * is a clash, and there is more than 1 ioctl with the same last byte.
1015  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1016  * ioctls are encoded in the misc table. An entry in the ndx table is
1017  * retrieved by indexing on the last byte of the ioctl command and comparing
1018  * the ioctl command with the value in the ndx table. In the event of a
1019  * mismatch the misc table is then searched sequentially for the desired
1020  * ioctl command.
1021  *
1022  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1023  */
1024 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1025 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1037 			MISC_CMD, ip_siocaddrt, NULL },
1038 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1039 			MISC_CMD, ip_siocdelrt, NULL },
1040 
1041 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1042 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1043 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1044 			IF_CMD, ip_sioctl_get_addr, NULL },
1045 
1046 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1047 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1048 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1049 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1050 
1051 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1052 			IPI_PRIV | IPI_WR,
1053 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1054 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1055 			IPI_MODOK | IPI_GET_CMD,
1056 			IF_CMD, ip_sioctl_get_flags, NULL },
1057 
1058 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 
1061 	/* copyin size cannot be coded for SIOCGIFCONF */
1062 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1063 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1064 
1065 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1066 			IF_CMD, ip_sioctl_mtu, NULL },
1067 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1068 			IF_CMD, ip_sioctl_get_mtu, NULL },
1069 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1070 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1071 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1072 			IF_CMD, ip_sioctl_brdaddr, NULL },
1073 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1074 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1075 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1076 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1077 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1078 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1079 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1080 			IF_CMD, ip_sioctl_metric, NULL },
1081 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 
1083 	/* See 166-168 below for extended SIOC*XARP ioctls */
1084 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1085 			ARP_CMD, ip_sioctl_arp, NULL },
1086 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1087 			ARP_CMD, ip_sioctl_arp, NULL },
1088 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1089 			ARP_CMD, ip_sioctl_arp, NULL },
1090 
1091 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1114 			MISC_CMD, if_unitsel, if_unitsel_restart },
1115 
1116 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 
1135 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1136 			IPI_PRIV | IPI_WR | IPI_MODOK,
1137 			IF_CMD, ip_sioctl_sifname, NULL },
1138 
1139 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 
1153 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1154 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1155 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1156 			IF_CMD, ip_sioctl_get_muxid, NULL },
1157 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1158 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1159 
1160 	/* Both if and lif variants share same func */
1161 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1162 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1163 	/* Both if and lif variants share same func */
1164 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1165 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1166 
1167 	/* copyin size cannot be coded for SIOCGIFCONF */
1168 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1169 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1170 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 
1188 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1189 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1190 			ip_sioctl_removeif_restart },
1191 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1192 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_addif, NULL },
1194 #define	SIOCLIFADDR_NDX 112
1195 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1197 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1198 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1199 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1200 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1201 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1202 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1203 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1204 			IPI_PRIV | IPI_WR,
1205 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1206 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1207 			IPI_GET_CMD | IPI_MODOK,
1208 			LIF_CMD, ip_sioctl_get_flags, NULL },
1209 
1210 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1212 
1213 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1214 			ip_sioctl_get_lifconf, NULL },
1215 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1216 			LIF_CMD, ip_sioctl_mtu, NULL },
1217 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1218 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1219 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1220 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1221 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1222 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1223 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1224 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1225 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1226 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1227 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1228 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1229 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1230 			LIF_CMD, ip_sioctl_metric, NULL },
1231 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1232 			IPI_PRIV | IPI_WR | IPI_MODOK,
1233 			LIF_CMD, ip_sioctl_slifname,
1234 			ip_sioctl_slifname_restart },
1235 
1236 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1237 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1238 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1239 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1240 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1241 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1242 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1243 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1244 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1245 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1246 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1247 			LIF_CMD, ip_sioctl_token, NULL },
1248 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1249 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1250 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1251 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1252 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1253 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1254 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1255 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1256 
1257 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1258 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1259 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1260 			LIF_CMD, ip_siocdelndp_v6, NULL },
1261 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1262 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1263 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1264 			LIF_CMD, ip_siocsetndp_v6, NULL },
1265 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1266 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1267 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1268 			MISC_CMD, ip_sioctl_tonlink, NULL },
1269 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1270 			MISC_CMD, ip_sioctl_tmysite, NULL },
1271 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1272 			TUN_CMD, ip_sioctl_tunparam, NULL },
1273 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1274 		    IPI_PRIV | IPI_WR,
1275 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1276 
1277 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1278 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1279 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1280 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1281 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1282 
1283 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1284 
1285 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1286 			LIF_CMD, ip_sioctl_get_binding, NULL },
1287 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1288 			IPI_PRIV | IPI_WR,
1289 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1290 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1291 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1292 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1293 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1294 
1295 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1296 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1298 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1299 
1300 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1301 
1302 	/* These are handled in ip_sioctl_copyin_setup itself */
1303 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1304 			MISC_CMD, NULL, NULL },
1305 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1306 			MISC_CMD, NULL, NULL },
1307 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1308 
1309 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1310 			ip_sioctl_get_lifconf, NULL },
1311 
1312 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1313 			XARP_CMD, ip_sioctl_arp, NULL },
1314 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1315 			XARP_CMD, ip_sioctl_arp, NULL },
1316 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1317 			XARP_CMD, ip_sioctl_arp, NULL },
1318 
1319 	/* SIOCPOPSOCKFS is not handled by IP */
1320 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1321 
1322 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1323 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1324 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1325 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1326 			ip_sioctl_slifzone_restart },
1327 	/* 172-174 are SCTP ioctls and not handled by IP */
1328 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1329 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1330 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1331 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1332 			IPI_GET_CMD, LIF_CMD,
1333 			ip_sioctl_get_lifusesrc, 0 },
1334 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1335 			IPI_PRIV | IPI_WR,
1336 			LIF_CMD, ip_sioctl_slifusesrc,
1337 			NULL },
1338 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1339 			ip_sioctl_get_lifsrcof, NULL },
1340 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1341 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1342 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1343 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1344 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1345 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1346 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1347 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1348 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1349 	/* SIOCSENABLESDP is handled by SDP */
1350 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1351 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1352 };
1353 
1354 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1355 
1356 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1357 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1358 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1359 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1360 		TUN_CMD, ip_sioctl_tunparam, NULL },
1361 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1362 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1363 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1364 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1365 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1366 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1367 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1368 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1369 		MISC_CMD, mrt_ioctl},
1370 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1371 		MISC_CMD, mrt_ioctl},
1372 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1373 		MISC_CMD, mrt_ioctl}
1374 };
1375 
1376 int ip_misc_ioctl_count =
1377     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1378 
1379 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1380 					/* Settable in /etc/system */
1381 /* Defined in ip_ire.c */
1382 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1383 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1384 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1385 
1386 static nv_t	ire_nv_arr[] = {
1387 	{ IRE_BROADCAST, "BROADCAST" },
1388 	{ IRE_LOCAL, "LOCAL" },
1389 	{ IRE_LOOPBACK, "LOOPBACK" },
1390 	{ IRE_CACHE, "CACHE" },
1391 	{ IRE_DEFAULT, "DEFAULT" },
1392 	{ IRE_PREFIX, "PREFIX" },
1393 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1394 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1395 	{ IRE_HOST, "HOST" },
1396 	{ 0 }
1397 };
1398 
1399 nv_t	*ire_nv_tbl = ire_nv_arr;
1400 
1401 /* Simple ICMP IP Header Template */
1402 static ipha_t icmp_ipha = {
1403 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1404 };
1405 
1406 struct module_info ip_mod_info = {
1407 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1408 	IP_MOD_LOWAT
1409 };
1410 
1411 /*
1412  * Duplicate static symbols within a module confuses mdb; so we avoid the
1413  * problem by making the symbols here distinct from those in udp.c.
1414  */
1415 
1416 /*
1417  * Entry points for IP as a device and as a module.
1418  * FIXME: down the road we might want a separate module and driver qinit.
1419  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1420  */
1421 static struct qinit iprinitv4 = {
1422 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1423 	&ip_mod_info
1424 };
1425 
1426 struct qinit iprinitv6 = {
1427 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1428 	&ip_mod_info
1429 };
1430 
1431 static struct qinit ipwinitv4 = {
1432 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1433 	&ip_mod_info
1434 };
1435 
1436 struct qinit ipwinitv6 = {
1437 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1438 	&ip_mod_info
1439 };
1440 
1441 static struct qinit iplrinit = {
1442 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1443 	&ip_mod_info
1444 };
1445 
1446 static struct qinit iplwinit = {
1447 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1448 	&ip_mod_info
1449 };
1450 
1451 /* For AF_INET aka /dev/ip */
1452 struct streamtab ipinfov4 = {
1453 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1454 };
1455 
1456 /* For AF_INET6 aka /dev/ip6 */
1457 struct streamtab ipinfov6 = {
1458 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1459 };
1460 
1461 #ifdef	DEBUG
1462 static boolean_t skip_sctp_cksum = B_FALSE;
1463 #endif
1464 
1465 /*
1466  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1467  * ip_rput_v6(), ip_output(), etc.  If the message
1468  * block already has a M_CTL at the front of it, then simply set the zoneid
1469  * appropriately.
1470  */
1471 mblk_t *
1472 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1473 {
1474 	mblk_t		*first_mp;
1475 	ipsec_out_t	*io;
1476 
1477 	ASSERT(zoneid != ALL_ZONES);
1478 	if (mp->b_datap->db_type == M_CTL) {
1479 		io = (ipsec_out_t *)mp->b_rptr;
1480 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1481 		io->ipsec_out_zoneid = zoneid;
1482 		return (mp);
1483 	}
1484 
1485 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1486 	if (first_mp == NULL)
1487 		return (NULL);
1488 	io = (ipsec_out_t *)first_mp->b_rptr;
1489 	/* This is not a secure packet */
1490 	io->ipsec_out_secure = B_FALSE;
1491 	io->ipsec_out_zoneid = zoneid;
1492 	first_mp->b_cont = mp;
1493 	return (first_mp);
1494 }
1495 
1496 /*
1497  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1498  */
1499 mblk_t *
1500 ip_copymsg(mblk_t *mp)
1501 {
1502 	mblk_t *nmp;
1503 	ipsec_info_t *in;
1504 
1505 	if (mp->b_datap->db_type != M_CTL)
1506 		return (copymsg(mp));
1507 
1508 	in = (ipsec_info_t *)mp->b_rptr;
1509 
1510 	/*
1511 	 * Note that M_CTL is also used for delivering ICMP error messages
1512 	 * upstream to transport layers.
1513 	 */
1514 	if (in->ipsec_info_type != IPSEC_OUT &&
1515 	    in->ipsec_info_type != IPSEC_IN)
1516 		return (copymsg(mp));
1517 
1518 	nmp = copymsg(mp->b_cont);
1519 
1520 	if (in->ipsec_info_type == IPSEC_OUT) {
1521 		return (ipsec_out_tag(mp, nmp,
1522 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1523 	} else {
1524 		return (ipsec_in_tag(mp, nmp,
1525 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1526 	}
1527 }
1528 
1529 /* Generate an ICMP fragmentation needed message. */
1530 static void
1531 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1532     ip_stack_t *ipst)
1533 {
1534 	icmph_t	icmph;
1535 	mblk_t *first_mp;
1536 	boolean_t mctl_present;
1537 
1538 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1539 
1540 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1541 		if (mctl_present)
1542 			freeb(first_mp);
1543 		return;
1544 	}
1545 
1546 	bzero(&icmph, sizeof (icmph_t));
1547 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1548 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1549 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1550 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1551 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1552 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1553 	    ipst);
1554 }
1555 
1556 /*
1557  * icmp_inbound deals with ICMP messages in the following ways.
1558  *
1559  * 1) It needs to send a reply back and possibly delivering it
1560  *    to the "interested" upper clients.
1561  * 2) It needs to send it to the upper clients only.
1562  * 3) It needs to change some values in IP only.
1563  * 4) It needs to change some values in IP and upper layers e.g TCP.
1564  *
1565  * We need to accomodate icmp messages coming in clear until we get
1566  * everything secure from the wire. If icmp_accept_clear_messages
1567  * is zero we check with the global policy and act accordingly. If
1568  * it is non-zero, we accept the message without any checks. But
1569  * *this does not mean* that this will be delivered to the upper
1570  * clients. By accepting we might send replies back, change our MTU
1571  * value etc. but delivery to the ULP/clients depends on their policy
1572  * dispositions.
1573  *
1574  * We handle the above 4 cases in the context of IPsec in the
1575  * following way :
1576  *
1577  * 1) Send the reply back in the same way as the request came in.
1578  *    If it came in encrypted, it goes out encrypted. If it came in
1579  *    clear, it goes out in clear. Thus, this will prevent chosen
1580  *    plain text attack.
1581  * 2) The client may or may not expect things to come in secure.
1582  *    If it comes in secure, the policy constraints are checked
1583  *    before delivering it to the upper layers. If it comes in
1584  *    clear, ipsec_inbound_accept_clear will decide whether to
1585  *    accept this in clear or not. In both the cases, if the returned
1586  *    message (IP header + 8 bytes) that caused the icmp message has
1587  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1588  *    sending up. If there are only 8 bytes of returned message, then
1589  *    upper client will not be notified.
1590  * 3) Check with global policy to see whether it matches the constaints.
1591  *    But this will be done only if icmp_accept_messages_in_clear is
1592  *    zero.
1593  * 4) If we need to change both in IP and ULP, then the decision taken
1594  *    while affecting the values in IP and while delivering up to TCP
1595  *    should be the same.
1596  *
1597  * 	There are two cases.
1598  *
1599  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1600  *	   failed), we will not deliver it to the ULP, even though they
1601  *	   are *willing* to accept in *clear*. This is fine as our global
1602  *	   disposition to icmp messages asks us reject the datagram.
1603  *
1604  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1605  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1606  *	   to deliver it to ULP (policy failed), it can lead to
1607  *	   consistency problems. The cases known at this time are
1608  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1609  *	   values :
1610  *
1611  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1612  *	     and Upper layer rejects. Then the communication will
1613  *	     come to a stop. This is solved by making similar decisions
1614  *	     at both levels. Currently, when we are unable to deliver
1615  *	     to the Upper Layer (due to policy failures) while IP has
1616  *	     adjusted ire_max_frag, the next outbound datagram would
1617  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1618  *	     will be with the right level of protection. Thus the right
1619  *	     value will be communicated even if we are not able to
1620  *	     communicate when we get from the wire initially. But this
1621  *	     assumes there would be at least one outbound datagram after
1622  *	     IP has adjusted its ire_max_frag value. To make things
1623  *	     simpler, we accept in clear after the validation of
1624  *	     AH/ESP headers.
1625  *
1626  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1627  *	     upper layer depending on the level of protection the upper
1628  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1629  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1630  *	     should be accepted in clear when the Upper layer expects secure.
1631  *	     Thus the communication may get aborted by some bad ICMP
1632  *	     packets.
1633  *
1634  * IPQoS Notes:
1635  * The only instance when a packet is sent for processing is when there
1636  * isn't an ICMP client and if we are interested in it.
1637  * If there is a client, IPPF processing will take place in the
1638  * ip_fanout_proto routine.
1639  *
1640  * Zones notes:
1641  * The packet is only processed in the context of the specified zone: typically
1642  * only this zone will reply to an echo request, and only interested clients in
1643  * this zone will receive a copy of the packet. This means that the caller must
1644  * call icmp_inbound() for each relevant zone.
1645  */
1646 static void
1647 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1648     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1649     ill_t *recv_ill, zoneid_t zoneid)
1650 {
1651 	icmph_t	*icmph;
1652 	ipha_t	*ipha;
1653 	int	iph_hdr_length;
1654 	int	hdr_length;
1655 	boolean_t	interested;
1656 	uint32_t	ts;
1657 	uchar_t	*wptr;
1658 	ipif_t	*ipif;
1659 	mblk_t *first_mp;
1660 	ipsec_in_t *ii;
1661 	timestruc_t now;
1662 	uint32_t ill_index;
1663 	ip_stack_t *ipst;
1664 
1665 	ASSERT(ill != NULL);
1666 	ipst = ill->ill_ipst;
1667 
1668 	first_mp = mp;
1669 	if (mctl_present) {
1670 		mp = first_mp->b_cont;
1671 		ASSERT(mp != NULL);
1672 	}
1673 
1674 	ipha = (ipha_t *)mp->b_rptr;
1675 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1676 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1677 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1678 		if (first_mp == NULL)
1679 			return;
1680 	}
1681 
1682 	/*
1683 	 * On a labeled system, we have to check whether the zone itself is
1684 	 * permitted to receive raw traffic.
1685 	 */
1686 	if (is_system_labeled()) {
1687 		if (zoneid == ALL_ZONES)
1688 			zoneid = tsol_packet_to_zoneid(mp);
1689 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1690 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1691 			    zoneid));
1692 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1693 			freemsg(first_mp);
1694 			return;
1695 		}
1696 	}
1697 
1698 	/*
1699 	 * We have accepted the ICMP message. It means that we will
1700 	 * respond to the packet if needed. It may not be delivered
1701 	 * to the upper client depending on the policy constraints
1702 	 * and the disposition in ipsec_inbound_accept_clear.
1703 	 */
1704 
1705 	ASSERT(ill != NULL);
1706 
1707 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1708 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1709 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1710 		/* Last chance to get real. */
1711 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1712 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1713 			freemsg(first_mp);
1714 			return;
1715 		}
1716 		/* Refresh iph following the pullup. */
1717 		ipha = (ipha_t *)mp->b_rptr;
1718 	}
1719 	/* ICMP header checksum, including checksum field, should be zero. */
1720 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1721 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1722 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1723 		freemsg(first_mp);
1724 		return;
1725 	}
1726 	/* The IP header will always be a multiple of four bytes */
1727 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1728 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1729 	    icmph->icmph_code));
1730 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1731 	/* We will set "interested" to "true" if we want a copy */
1732 	interested = B_FALSE;
1733 	switch (icmph->icmph_type) {
1734 	case ICMP_ECHO_REPLY:
1735 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1736 		break;
1737 	case ICMP_DEST_UNREACHABLE:
1738 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1739 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1740 		interested = B_TRUE;	/* Pass up to transport */
1741 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1742 		break;
1743 	case ICMP_SOURCE_QUENCH:
1744 		interested = B_TRUE;	/* Pass up to transport */
1745 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1746 		break;
1747 	case ICMP_REDIRECT:
1748 		if (!ipst->ips_ip_ignore_redirect)
1749 			interested = B_TRUE;
1750 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1751 		break;
1752 	case ICMP_ECHO_REQUEST:
1753 		/*
1754 		 * Whether to respond to echo requests that come in as IP
1755 		 * broadcasts or as IP multicast is subject to debate
1756 		 * (what isn't?).  We aim to please, you pick it.
1757 		 * Default is do it.
1758 		 */
1759 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1760 			/* unicast: always respond */
1761 			interested = B_TRUE;
1762 		} else if (CLASSD(ipha->ipha_dst)) {
1763 			/* multicast: respond based on tunable */
1764 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1765 		} else if (broadcast) {
1766 			/* broadcast: respond based on tunable */
1767 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1768 		}
1769 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1770 		break;
1771 	case ICMP_ROUTER_ADVERTISEMENT:
1772 	case ICMP_ROUTER_SOLICITATION:
1773 		break;
1774 	case ICMP_TIME_EXCEEDED:
1775 		interested = B_TRUE;	/* Pass up to transport */
1776 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1777 		break;
1778 	case ICMP_PARAM_PROBLEM:
1779 		interested = B_TRUE;	/* Pass up to transport */
1780 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1781 		break;
1782 	case ICMP_TIME_STAMP_REQUEST:
1783 		/* Response to Time Stamp Requests is local policy. */
1784 		if (ipst->ips_ip_g_resp_to_timestamp &&
1785 		    /* So is whether to respond if it was an IP broadcast. */
1786 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1787 			int tstamp_len = 3 * sizeof (uint32_t);
1788 
1789 			if (wptr +  tstamp_len > mp->b_wptr) {
1790 				if (!pullupmsg(mp, wptr + tstamp_len -
1791 				    mp->b_rptr)) {
1792 					BUMP_MIB(ill->ill_ip_mib,
1793 					    ipIfStatsInDiscards);
1794 					freemsg(first_mp);
1795 					return;
1796 				}
1797 				/* Refresh ipha following the pullup. */
1798 				ipha = (ipha_t *)mp->b_rptr;
1799 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1800 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1801 			}
1802 			interested = B_TRUE;
1803 		}
1804 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1805 		break;
1806 	case ICMP_TIME_STAMP_REPLY:
1807 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1808 		break;
1809 	case ICMP_INFO_REQUEST:
1810 		/* Per RFC 1122 3.2.2.7, ignore this. */
1811 	case ICMP_INFO_REPLY:
1812 		break;
1813 	case ICMP_ADDRESS_MASK_REQUEST:
1814 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1815 		    !broadcast) &&
1816 		    /* TODO m_pullup of complete header? */
1817 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1818 			interested = B_TRUE;
1819 		}
1820 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1821 		break;
1822 	case ICMP_ADDRESS_MASK_REPLY:
1823 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1824 		break;
1825 	default:
1826 		interested = B_TRUE;	/* Pass up to transport */
1827 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1828 		break;
1829 	}
1830 	/* See if there is an ICMP client. */
1831 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1832 		/* If there is an ICMP client and we want one too, copy it. */
1833 		mblk_t *first_mp1;
1834 
1835 		if (!interested) {
1836 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1837 			    ip_policy, recv_ill, zoneid);
1838 			return;
1839 		}
1840 		first_mp1 = ip_copymsg(first_mp);
1841 		if (first_mp1 != NULL) {
1842 			ip_fanout_proto(q, first_mp1, ill, ipha,
1843 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1844 		}
1845 	} else if (!interested) {
1846 		freemsg(first_mp);
1847 		return;
1848 	} else {
1849 		/*
1850 		 * Initiate policy processing for this packet if ip_policy
1851 		 * is true.
1852 		 */
1853 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1854 			ill_index = ill->ill_phyint->phyint_ifindex;
1855 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1856 			if (mp == NULL) {
1857 				if (mctl_present) {
1858 					freeb(first_mp);
1859 				}
1860 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1861 				return;
1862 			}
1863 		}
1864 	}
1865 	/* We want to do something with it. */
1866 	/* Check db_ref to make sure we can modify the packet. */
1867 	if (mp->b_datap->db_ref > 1) {
1868 		mblk_t	*first_mp1;
1869 
1870 		first_mp1 = ip_copymsg(first_mp);
1871 		freemsg(first_mp);
1872 		if (!first_mp1) {
1873 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1874 			return;
1875 		}
1876 		first_mp = first_mp1;
1877 		if (mctl_present) {
1878 			mp = first_mp->b_cont;
1879 			ASSERT(mp != NULL);
1880 		} else {
1881 			mp = first_mp;
1882 		}
1883 		ipha = (ipha_t *)mp->b_rptr;
1884 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1885 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1886 	}
1887 	switch (icmph->icmph_type) {
1888 	case ICMP_ADDRESS_MASK_REQUEST:
1889 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1890 		if (ipif == NULL) {
1891 			freemsg(first_mp);
1892 			return;
1893 		}
1894 		/*
1895 		 * outging interface must be IPv4
1896 		 */
1897 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1898 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1899 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1900 		ipif_refrele(ipif);
1901 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1902 		break;
1903 	case ICMP_ECHO_REQUEST:
1904 		icmph->icmph_type = ICMP_ECHO_REPLY;
1905 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1906 		break;
1907 	case ICMP_TIME_STAMP_REQUEST: {
1908 		uint32_t *tsp;
1909 
1910 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1911 		tsp = (uint32_t *)wptr;
1912 		tsp++;		/* Skip past 'originate time' */
1913 		/* Compute # of milliseconds since midnight */
1914 		gethrestime(&now);
1915 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1916 		    now.tv_nsec / (NANOSEC / MILLISEC);
1917 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1918 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1919 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1920 		break;
1921 	}
1922 	default:
1923 		ipha = (ipha_t *)&icmph[1];
1924 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1925 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1926 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1927 				freemsg(first_mp);
1928 				return;
1929 			}
1930 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1931 			ipha = (ipha_t *)&icmph[1];
1932 		}
1933 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1934 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1935 			freemsg(first_mp);
1936 			return;
1937 		}
1938 		hdr_length = IPH_HDR_LENGTH(ipha);
1939 		if (hdr_length < sizeof (ipha_t)) {
1940 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1941 			freemsg(first_mp);
1942 			return;
1943 		}
1944 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1945 			if (!pullupmsg(mp,
1946 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1947 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1948 				freemsg(first_mp);
1949 				return;
1950 			}
1951 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1952 			ipha = (ipha_t *)&icmph[1];
1953 		}
1954 		switch (icmph->icmph_type) {
1955 		case ICMP_REDIRECT:
1956 			/*
1957 			 * As there is no upper client to deliver, we don't
1958 			 * need the first_mp any more.
1959 			 */
1960 			if (mctl_present) {
1961 				freeb(first_mp);
1962 			}
1963 			icmp_redirect(ill, mp);
1964 			return;
1965 		case ICMP_DEST_UNREACHABLE:
1966 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1967 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1968 				    zoneid, mp, iph_hdr_length, ipst)) {
1969 					freemsg(first_mp);
1970 					return;
1971 				}
1972 				/*
1973 				 * icmp_inbound_too_big() may alter mp.
1974 				 * Resynch ipha and icmph accordingly.
1975 				 */
1976 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1977 				ipha = (ipha_t *)&icmph[1];
1978 			}
1979 			/* FALLTHRU */
1980 		default :
1981 			/*
1982 			 * IPQoS notes: Since we have already done IPQoS
1983 			 * processing we don't want to do it again in
1984 			 * the fanout routines called by
1985 			 * icmp_inbound_error_fanout, hence the last
1986 			 * argument, ip_policy, is B_FALSE.
1987 			 */
1988 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1989 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1990 			    B_FALSE, recv_ill, zoneid);
1991 		}
1992 		return;
1993 	}
1994 	/* Send out an ICMP packet */
1995 	icmph->icmph_checksum = 0;
1996 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1997 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1998 		ipif_t	*ipif_chosen;
1999 		/*
2000 		 * Make it look like it was directed to us, so we don't look
2001 		 * like a fool with a broadcast or multicast source address.
2002 		 */
2003 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2004 		/*
2005 		 * Make sure that we haven't grabbed an interface that's DOWN.
2006 		 */
2007 		if (ipif != NULL) {
2008 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2009 			    ipha->ipha_src, zoneid);
2010 			if (ipif_chosen != NULL) {
2011 				ipif_refrele(ipif);
2012 				ipif = ipif_chosen;
2013 			}
2014 		}
2015 		if (ipif == NULL) {
2016 			ip0dbg(("icmp_inbound: "
2017 			    "No source for broadcast/multicast:\n"
2018 			    "\tsrc 0x%x dst 0x%x ill %p "
2019 			    "ipif_lcl_addr 0x%x\n",
2020 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2021 			    (void *)ill,
2022 			    ill->ill_ipif->ipif_lcl_addr));
2023 			freemsg(first_mp);
2024 			return;
2025 		}
2026 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2027 		ipha->ipha_dst = ipif->ipif_src_addr;
2028 		ipif_refrele(ipif);
2029 	}
2030 	/* Reset time to live. */
2031 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2032 	{
2033 		/* Swap source and destination addresses */
2034 		ipaddr_t tmp;
2035 
2036 		tmp = ipha->ipha_src;
2037 		ipha->ipha_src = ipha->ipha_dst;
2038 		ipha->ipha_dst = tmp;
2039 	}
2040 	ipha->ipha_ident = 0;
2041 	if (!IS_SIMPLE_IPH(ipha))
2042 		icmp_options_update(ipha);
2043 
2044 	if (!mctl_present) {
2045 		/*
2046 		 * This packet should go out the same way as it
2047 		 * came in i.e in clear. To make sure that global
2048 		 * policy will not be applied to this in ip_wput_ire,
2049 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2050 		 */
2051 		ASSERT(first_mp == mp);
2052 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2053 		if (first_mp == NULL) {
2054 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2055 			freemsg(mp);
2056 			return;
2057 		}
2058 		ii = (ipsec_in_t *)first_mp->b_rptr;
2059 
2060 		/* This is not a secure packet */
2061 		ii->ipsec_in_secure = B_FALSE;
2062 		first_mp->b_cont = mp;
2063 	} else {
2064 		ii = (ipsec_in_t *)first_mp->b_rptr;
2065 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2066 	}
2067 	ii->ipsec_in_zoneid = zoneid;
2068 	ASSERT(zoneid != ALL_ZONES);
2069 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2070 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2071 		return;
2072 	}
2073 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2074 	put(WR(q), first_mp);
2075 }
2076 
2077 static ipaddr_t
2078 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2079 {
2080 	conn_t *connp;
2081 	connf_t *connfp;
2082 	ipaddr_t nexthop_addr = INADDR_ANY;
2083 	int hdr_length = IPH_HDR_LENGTH(ipha);
2084 	uint16_t *up;
2085 	uint32_t ports;
2086 	ip_stack_t *ipst = ill->ill_ipst;
2087 
2088 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2089 	switch (ipha->ipha_protocol) {
2090 		case IPPROTO_TCP:
2091 		{
2092 			tcph_t *tcph;
2093 
2094 			/* do a reverse lookup */
2095 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2096 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2097 			    TCPS_LISTEN, ipst);
2098 			break;
2099 		}
2100 		case IPPROTO_UDP:
2101 		{
2102 			uint32_t dstport, srcport;
2103 
2104 			((uint16_t *)&ports)[0] = up[1];
2105 			((uint16_t *)&ports)[1] = up[0];
2106 
2107 			/* Extract ports in net byte order */
2108 			dstport = htons(ntohl(ports) & 0xFFFF);
2109 			srcport = htons(ntohl(ports) >> 16);
2110 
2111 			connfp = &ipst->ips_ipcl_udp_fanout[
2112 			    IPCL_UDP_HASH(dstport, ipst)];
2113 			mutex_enter(&connfp->connf_lock);
2114 			connp = connfp->connf_head;
2115 
2116 			/* do a reverse lookup */
2117 			while ((connp != NULL) &&
2118 			    (!IPCL_UDP_MATCH(connp, dstport,
2119 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2120 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2121 				connp = connp->conn_next;
2122 			}
2123 			if (connp != NULL)
2124 				CONN_INC_REF(connp);
2125 			mutex_exit(&connfp->connf_lock);
2126 			break;
2127 		}
2128 		case IPPROTO_SCTP:
2129 		{
2130 			in6_addr_t map_src, map_dst;
2131 
2132 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2133 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2134 			((uint16_t *)&ports)[0] = up[1];
2135 			((uint16_t *)&ports)[1] = up[0];
2136 
2137 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2138 			    zoneid, ipst->ips_netstack->netstack_sctp);
2139 			if (connp == NULL) {
2140 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2141 				    zoneid, ports, ipha, ipst);
2142 			} else {
2143 				CONN_INC_REF(connp);
2144 				SCTP_REFRELE(CONN2SCTP(connp));
2145 			}
2146 			break;
2147 		}
2148 		default:
2149 		{
2150 			ipha_t ripha;
2151 
2152 			ripha.ipha_src = ipha->ipha_dst;
2153 			ripha.ipha_dst = ipha->ipha_src;
2154 			ripha.ipha_protocol = ipha->ipha_protocol;
2155 
2156 			connfp = &ipst->ips_ipcl_proto_fanout[
2157 			    ipha->ipha_protocol];
2158 			mutex_enter(&connfp->connf_lock);
2159 			connp = connfp->connf_head;
2160 			for (connp = connfp->connf_head; connp != NULL;
2161 			    connp = connp->conn_next) {
2162 				if (IPCL_PROTO_MATCH(connp,
2163 				    ipha->ipha_protocol, &ripha, ill,
2164 				    0, zoneid)) {
2165 					CONN_INC_REF(connp);
2166 					break;
2167 				}
2168 			}
2169 			mutex_exit(&connfp->connf_lock);
2170 		}
2171 	}
2172 	if (connp != NULL) {
2173 		if (connp->conn_nexthop_set)
2174 			nexthop_addr = connp->conn_nexthop_v4;
2175 		CONN_DEC_REF(connp);
2176 	}
2177 	return (nexthop_addr);
2178 }
2179 
2180 /* Table from RFC 1191 */
2181 static int icmp_frag_size_table[] =
2182 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2183 
2184 /*
2185  * Process received ICMP Packet too big.
2186  * After updating any IRE it does the fanout to any matching transport streams.
2187  * Assumes the message has been pulled up till the IP header that caused
2188  * the error.
2189  *
2190  * Returns B_FALSE on failure and B_TRUE on success.
2191  */
2192 static boolean_t
2193 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2194     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2195     ip_stack_t *ipst)
2196 {
2197 	ire_t	*ire, *first_ire;
2198 	int	mtu, orig_mtu;
2199 	int	hdr_length;
2200 	ipaddr_t nexthop_addr;
2201 	boolean_t disable_pmtud;
2202 
2203 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2204 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2205 	ASSERT(ill != NULL);
2206 
2207 	hdr_length = IPH_HDR_LENGTH(ipha);
2208 
2209 	/* Drop if the original packet contained a source route */
2210 	if (ip_source_route_included(ipha)) {
2211 		return (B_FALSE);
2212 	}
2213 	/*
2214 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2215 	 * header.
2216 	 */
2217 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2218 	    mp->b_wptr) {
2219 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2220 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2221 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2222 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2223 			return (B_FALSE);
2224 		}
2225 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2226 		ipha = (ipha_t *)&icmph[1];
2227 	}
2228 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2229 	if (nexthop_addr != INADDR_ANY) {
2230 		/* nexthop set */
2231 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2232 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2233 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2234 	} else {
2235 		/* nexthop not set */
2236 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2237 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2238 	}
2239 
2240 	if (!first_ire) {
2241 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2242 		    ntohl(ipha->ipha_dst)));
2243 		return (B_FALSE);
2244 	}
2245 
2246 	/* Check for MTU discovery advice as described in RFC 1191 */
2247 	mtu = ntohs(icmph->icmph_du_mtu);
2248 	orig_mtu = mtu;
2249 	disable_pmtud = B_FALSE;
2250 
2251 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2252 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2253 	    ire = ire->ire_next) {
2254 		/*
2255 		 * Look for the connection to which this ICMP message is
2256 		 * directed. If it has the IP_NEXTHOP option set, then the
2257 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2258 		 * option. Else the search is limited to regular IREs.
2259 		 */
2260 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2261 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2262 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2263 		    (nexthop_addr != INADDR_ANY)))
2264 			continue;
2265 
2266 		mutex_enter(&ire->ire_lock);
2267 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2268 			uint32_t length;
2269 			int	i;
2270 
2271 			/*
2272 			 * Use the table from RFC 1191 to figure out
2273 			 * the next "plateau" based on the length in
2274 			 * the original IP packet.
2275 			 */
2276 			length = ntohs(ipha->ipha_length);
2277 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2278 			    uint32_t, length);
2279 			if (ire->ire_max_frag <= length &&
2280 			    ire->ire_max_frag >= length - hdr_length) {
2281 				/*
2282 				 * Handle broken BSD 4.2 systems that
2283 				 * return the wrong iph_length in ICMP
2284 				 * errors.
2285 				 */
2286 				length -= hdr_length;
2287 			}
2288 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2289 				if (length > icmp_frag_size_table[i])
2290 					break;
2291 			}
2292 			if (i == A_CNT(icmp_frag_size_table)) {
2293 				/* Smaller than 68! */
2294 				disable_pmtud = B_TRUE;
2295 				mtu = ipst->ips_ip_pmtu_min;
2296 			} else {
2297 				mtu = icmp_frag_size_table[i];
2298 				if (mtu < ipst->ips_ip_pmtu_min) {
2299 					mtu = ipst->ips_ip_pmtu_min;
2300 					disable_pmtud = B_TRUE;
2301 				}
2302 			}
2303 			/* Fool the ULP into believing our guessed PMTU. */
2304 			icmph->icmph_du_zero = 0;
2305 			icmph->icmph_du_mtu = htons(mtu);
2306 		}
2307 		if (disable_pmtud)
2308 			ire->ire_frag_flag = 0;
2309 		/* Reduce the IRE max frag value as advised. */
2310 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2311 		if (ire->ire_max_frag == mtu) {
2312 			/* Decreased it */
2313 			ire->ire_marks |= IRE_MARK_PMTU;
2314 		}
2315 		mutex_exit(&ire->ire_lock);
2316 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2317 		    ire, int, orig_mtu, int, mtu);
2318 	}
2319 	rw_exit(&first_ire->ire_bucket->irb_lock);
2320 	ire_refrele(first_ire);
2321 	return (B_TRUE);
2322 }
2323 
2324 /*
2325  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2326  * calls this function.
2327  */
2328 static mblk_t *
2329 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2330 {
2331 	ipha_t *ipha;
2332 	icmph_t *icmph;
2333 	ipha_t *in_ipha;
2334 	int length;
2335 
2336 	ASSERT(mp->b_datap->db_type == M_DATA);
2337 
2338 	/*
2339 	 * For Self-encapsulated packets, we added an extra IP header
2340 	 * without the options. Inner IP header is the one from which
2341 	 * the outer IP header was formed. Thus, we need to remove the
2342 	 * outer IP header. To do this, we pullup the whole message
2343 	 * and overlay whatever follows the outer IP header over the
2344 	 * outer IP header.
2345 	 */
2346 
2347 	if (!pullupmsg(mp, -1))
2348 		return (NULL);
2349 
2350 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2351 	ipha = (ipha_t *)&icmph[1];
2352 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2353 
2354 	/*
2355 	 * The length that we want to overlay is following the inner
2356 	 * IP header. Subtracting the IP header + icmp header + outer
2357 	 * IP header's length should give us the length that we want to
2358 	 * overlay.
2359 	 */
2360 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2361 	    hdr_length;
2362 	/*
2363 	 * Overlay whatever follows the inner header over the
2364 	 * outer header.
2365 	 */
2366 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2367 
2368 	/* Set the wptr to account for the outer header */
2369 	mp->b_wptr -= hdr_length;
2370 	return (mp);
2371 }
2372 
2373 /*
2374  * Try to pass the ICMP message upstream in case the ULP cares.
2375  *
2376  * If the packet that caused the ICMP error is secure, we send
2377  * it to AH/ESP to make sure that the attached packet has a
2378  * valid association. ipha in the code below points to the
2379  * IP header of the packet that caused the error.
2380  *
2381  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2382  * in the context of IPsec. Normally we tell the upper layer
2383  * whenever we send the ire (including ip_bind), the IPsec header
2384  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2385  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2386  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2387  * same thing. As TCP has the IPsec options size that needs to be
2388  * adjusted, we just pass the MTU unchanged.
2389  *
2390  * IFN could have been generated locally or by some router.
2391  *
2392  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2393  *	    This happens because IP adjusted its value of MTU on an
2394  *	    earlier IFN message and could not tell the upper layer,
2395  *	    the new adjusted value of MTU e.g. Packet was encrypted
2396  *	    or there was not enough information to fanout to upper
2397  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2398  *	    generates the IFN, where IPsec processing has *not* been
2399  *	    done.
2400  *
2401  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2402  *	    could have generated this. This happens because ire_max_frag
2403  *	    value in IP was set to a new value, while the IPsec processing
2404  *	    was being done and after we made the fragmentation check in
2405  *	    ip_wput_ire. Thus on return from IPsec processing,
2406  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2407  *	    and generates the IFN. As IPsec processing is over, we fanout
2408  *	    to AH/ESP to remove the header.
2409  *
2410  *	    In both these cases, ipsec_in_loopback will be set indicating
2411  *	    that IFN was generated locally.
2412  *
2413  * ROUTER : IFN could be secure or non-secure.
2414  *
2415  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2416  *	      packet in error has AH/ESP headers to validate the AH/ESP
2417  *	      headers. AH/ESP will verify whether there is a valid SA or
2418  *	      not and send it back. We will fanout again if we have more
2419  *	      data in the packet.
2420  *
2421  *	      If the packet in error does not have AH/ESP, we handle it
2422  *	      like any other case.
2423  *
2424  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2425  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2426  *	      for validation. AH/ESP will verify whether there is a
2427  *	      valid SA or not and send it back. We will fanout again if
2428  *	      we have more data in the packet.
2429  *
2430  *	      If the packet in error does not have AH/ESP, we handle it
2431  *	      like any other case.
2432  */
2433 static void
2434 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2435     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2436     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2437     zoneid_t zoneid)
2438 {
2439 	uint16_t *up;	/* Pointer to ports in ULP header */
2440 	uint32_t ports;	/* reversed ports for fanout */
2441 	ipha_t ripha;	/* With reversed addresses */
2442 	mblk_t *first_mp;
2443 	ipsec_in_t *ii;
2444 	tcph_t	*tcph;
2445 	conn_t	*connp;
2446 	ip_stack_t *ipst;
2447 
2448 	ASSERT(ill != NULL);
2449 
2450 	ASSERT(recv_ill != NULL);
2451 	ipst = recv_ill->ill_ipst;
2452 
2453 	first_mp = mp;
2454 	if (mctl_present) {
2455 		mp = first_mp->b_cont;
2456 		ASSERT(mp != NULL);
2457 
2458 		ii = (ipsec_in_t *)first_mp->b_rptr;
2459 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2460 	} else {
2461 		ii = NULL;
2462 	}
2463 
2464 	switch (ipha->ipha_protocol) {
2465 	case IPPROTO_UDP:
2466 		/*
2467 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2468 		 * transport header.
2469 		 */
2470 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2471 		    mp->b_wptr) {
2472 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2473 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2474 				goto discard_pkt;
2475 			}
2476 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2477 			ipha = (ipha_t *)&icmph[1];
2478 		}
2479 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2480 
2481 		/*
2482 		 * Attempt to find a client stream based on port.
2483 		 * Note that we do a reverse lookup since the header is
2484 		 * in the form we sent it out.
2485 		 * The ripha header is only used for the IP_UDP_MATCH and we
2486 		 * only set the src and dst addresses and protocol.
2487 		 */
2488 		ripha.ipha_src = ipha->ipha_dst;
2489 		ripha.ipha_dst = ipha->ipha_src;
2490 		ripha.ipha_protocol = ipha->ipha_protocol;
2491 		((uint16_t *)&ports)[0] = up[1];
2492 		((uint16_t *)&ports)[1] = up[0];
2493 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2494 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2495 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2496 		    icmph->icmph_type, icmph->icmph_code));
2497 
2498 		/* Have to change db_type after any pullupmsg */
2499 		DB_TYPE(mp) = M_CTL;
2500 
2501 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2502 		    mctl_present, ip_policy, recv_ill, zoneid);
2503 		return;
2504 
2505 	case IPPROTO_TCP:
2506 		/*
2507 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2508 		 * transport header.
2509 		 */
2510 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2511 		    mp->b_wptr) {
2512 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2513 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2514 				goto discard_pkt;
2515 			}
2516 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2517 			ipha = (ipha_t *)&icmph[1];
2518 		}
2519 		/*
2520 		 * Find a TCP client stream for this packet.
2521 		 * Note that we do a reverse lookup since the header is
2522 		 * in the form we sent it out.
2523 		 */
2524 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2525 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2526 		    ipst);
2527 		if (connp == NULL)
2528 			goto discard_pkt;
2529 
2530 		/* Have to change db_type after any pullupmsg */
2531 		DB_TYPE(mp) = M_CTL;
2532 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2533 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2534 		return;
2535 
2536 	case IPPROTO_SCTP:
2537 		/*
2538 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2539 		 * transport header.
2540 		 */
2541 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2542 		    mp->b_wptr) {
2543 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2544 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2545 				goto discard_pkt;
2546 			}
2547 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2548 			ipha = (ipha_t *)&icmph[1];
2549 		}
2550 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2551 		/*
2552 		 * Find a SCTP client stream for this packet.
2553 		 * Note that we do a reverse lookup since the header is
2554 		 * in the form we sent it out.
2555 		 * The ripha header is only used for the matching and we
2556 		 * only set the src and dst addresses, protocol, and version.
2557 		 */
2558 		ripha.ipha_src = ipha->ipha_dst;
2559 		ripha.ipha_dst = ipha->ipha_src;
2560 		ripha.ipha_protocol = ipha->ipha_protocol;
2561 		ripha.ipha_version_and_hdr_length =
2562 		    ipha->ipha_version_and_hdr_length;
2563 		((uint16_t *)&ports)[0] = up[1];
2564 		((uint16_t *)&ports)[1] = up[0];
2565 
2566 		/* Have to change db_type after any pullupmsg */
2567 		DB_TYPE(mp) = M_CTL;
2568 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2569 		    mctl_present, ip_policy, zoneid);
2570 		return;
2571 
2572 	case IPPROTO_ESP:
2573 	case IPPROTO_AH: {
2574 		int ipsec_rc;
2575 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2576 
2577 		/*
2578 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2579 		 * We will re-use the IPSEC_IN if it is already present as
2580 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2581 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2582 		 * one and attach it in the front.
2583 		 */
2584 		if (ii != NULL) {
2585 			/*
2586 			 * ip_fanout_proto_again converts the ICMP errors
2587 			 * that come back from AH/ESP to M_DATA so that
2588 			 * if it is non-AH/ESP and we do a pullupmsg in
2589 			 * this function, it would work. Convert it back
2590 			 * to M_CTL before we send up as this is a ICMP
2591 			 * error. This could have been generated locally or
2592 			 * by some router. Validate the inner IPsec
2593 			 * headers.
2594 			 *
2595 			 * NOTE : ill_index is used by ip_fanout_proto_again
2596 			 * to locate the ill.
2597 			 */
2598 			ASSERT(ill != NULL);
2599 			ii->ipsec_in_ill_index =
2600 			    ill->ill_phyint->phyint_ifindex;
2601 			ii->ipsec_in_rill_index =
2602 			    recv_ill->ill_phyint->phyint_ifindex;
2603 			DB_TYPE(first_mp->b_cont) = M_CTL;
2604 		} else {
2605 			/*
2606 			 * IPSEC_IN is not present. We attach a ipsec_in
2607 			 * message and send up to IPsec for validating
2608 			 * and removing the IPsec headers. Clear
2609 			 * ipsec_in_secure so that when we return
2610 			 * from IPsec, we don't mistakenly think that this
2611 			 * is a secure packet came from the network.
2612 			 *
2613 			 * NOTE : ill_index is used by ip_fanout_proto_again
2614 			 * to locate the ill.
2615 			 */
2616 			ASSERT(first_mp == mp);
2617 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2618 			if (first_mp == NULL) {
2619 				freemsg(mp);
2620 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2621 				return;
2622 			}
2623 			ii = (ipsec_in_t *)first_mp->b_rptr;
2624 
2625 			/* This is not a secure packet */
2626 			ii->ipsec_in_secure = B_FALSE;
2627 			first_mp->b_cont = mp;
2628 			DB_TYPE(mp) = M_CTL;
2629 			ASSERT(ill != NULL);
2630 			ii->ipsec_in_ill_index =
2631 			    ill->ill_phyint->phyint_ifindex;
2632 			ii->ipsec_in_rill_index =
2633 			    recv_ill->ill_phyint->phyint_ifindex;
2634 		}
2635 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2636 
2637 		if (!ipsec_loaded(ipss)) {
2638 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2639 			return;
2640 		}
2641 
2642 		if (ipha->ipha_protocol == IPPROTO_ESP)
2643 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2644 		else
2645 			ipsec_rc = ipsecah_icmp_error(first_mp);
2646 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2647 			return;
2648 
2649 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2650 		return;
2651 	}
2652 	default:
2653 		/*
2654 		 * The ripha header is only used for the lookup and we
2655 		 * only set the src and dst addresses and protocol.
2656 		 */
2657 		ripha.ipha_src = ipha->ipha_dst;
2658 		ripha.ipha_dst = ipha->ipha_src;
2659 		ripha.ipha_protocol = ipha->ipha_protocol;
2660 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2661 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2662 		    ntohl(ipha->ipha_dst),
2663 		    icmph->icmph_type, icmph->icmph_code));
2664 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2665 			ipha_t *in_ipha;
2666 
2667 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2668 			    mp->b_wptr) {
2669 				if (!pullupmsg(mp, (uchar_t *)ipha +
2670 				    hdr_length + sizeof (ipha_t) -
2671 				    mp->b_rptr)) {
2672 					goto discard_pkt;
2673 				}
2674 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2675 				ipha = (ipha_t *)&icmph[1];
2676 			}
2677 			/*
2678 			 * Caller has verified that length has to be
2679 			 * at least the size of IP header.
2680 			 */
2681 			ASSERT(hdr_length >= sizeof (ipha_t));
2682 			/*
2683 			 * Check the sanity of the inner IP header like
2684 			 * we did for the outer header.
2685 			 */
2686 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2687 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2688 				goto discard_pkt;
2689 			}
2690 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2691 				goto discard_pkt;
2692 			}
2693 			/* Check for Self-encapsulated tunnels */
2694 			if (in_ipha->ipha_src == ipha->ipha_src &&
2695 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2696 
2697 				mp = icmp_inbound_self_encap_error(mp,
2698 				    iph_hdr_length, hdr_length);
2699 				if (mp == NULL)
2700 					goto discard_pkt;
2701 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2702 				ipha = (ipha_t *)&icmph[1];
2703 				hdr_length = IPH_HDR_LENGTH(ipha);
2704 				/*
2705 				 * The packet in error is self-encapsualted.
2706 				 * And we are finding it further encapsulated
2707 				 * which we could not have possibly generated.
2708 				 */
2709 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2710 					goto discard_pkt;
2711 				}
2712 				icmp_inbound_error_fanout(q, ill, first_mp,
2713 				    icmph, ipha, iph_hdr_length, hdr_length,
2714 				    mctl_present, ip_policy, recv_ill, zoneid);
2715 				return;
2716 			}
2717 		}
2718 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2719 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2720 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2721 		    ii != NULL &&
2722 		    ii->ipsec_in_loopback &&
2723 		    ii->ipsec_in_secure) {
2724 			/*
2725 			 * For IP tunnels that get a looped-back
2726 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2727 			 * reported new MTU to take into account the IPsec
2728 			 * headers protecting this configured tunnel.
2729 			 *
2730 			 * This allows the tunnel module (tun.c) to blindly
2731 			 * accept the MTU reported in an ICMP "too big"
2732 			 * message.
2733 			 *
2734 			 * Non-looped back ICMP messages will just be
2735 			 * handled by the security protocols (if needed),
2736 			 * and the first subsequent packet will hit this
2737 			 * path.
2738 			 */
2739 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2740 			    ipsec_in_extra_length(first_mp));
2741 		}
2742 		/* Have to change db_type after any pullupmsg */
2743 		DB_TYPE(mp) = M_CTL;
2744 
2745 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2746 		    ip_policy, recv_ill, zoneid);
2747 		return;
2748 	}
2749 	/* NOTREACHED */
2750 discard_pkt:
2751 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2752 drop_pkt:;
2753 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2754 	freemsg(first_mp);
2755 }
2756 
2757 /*
2758  * Common IP options parser.
2759  *
2760  * Setup routine: fill in *optp with options-parsing state, then
2761  * tail-call ipoptp_next to return the first option.
2762  */
2763 uint8_t
2764 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2765 {
2766 	uint32_t totallen; /* total length of all options */
2767 
2768 	totallen = ipha->ipha_version_and_hdr_length -
2769 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2770 	totallen <<= 2;
2771 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2772 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2773 	optp->ipoptp_flags = 0;
2774 	return (ipoptp_next(optp));
2775 }
2776 
2777 /*
2778  * Common IP options parser: extract next option.
2779  */
2780 uint8_t
2781 ipoptp_next(ipoptp_t *optp)
2782 {
2783 	uint8_t *end = optp->ipoptp_end;
2784 	uint8_t *cur = optp->ipoptp_next;
2785 	uint8_t opt, len, pointer;
2786 
2787 	/*
2788 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2789 	 * has been corrupted.
2790 	 */
2791 	ASSERT(cur <= end);
2792 
2793 	if (cur == end)
2794 		return (IPOPT_EOL);
2795 
2796 	opt = cur[IPOPT_OPTVAL];
2797 
2798 	/*
2799 	 * Skip any NOP options.
2800 	 */
2801 	while (opt == IPOPT_NOP) {
2802 		cur++;
2803 		if (cur == end)
2804 			return (IPOPT_EOL);
2805 		opt = cur[IPOPT_OPTVAL];
2806 	}
2807 
2808 	if (opt == IPOPT_EOL)
2809 		return (IPOPT_EOL);
2810 
2811 	/*
2812 	 * Option requiring a length.
2813 	 */
2814 	if ((cur + 1) >= end) {
2815 		optp->ipoptp_flags |= IPOPTP_ERROR;
2816 		return (IPOPT_EOL);
2817 	}
2818 	len = cur[IPOPT_OLEN];
2819 	if (len < 2) {
2820 		optp->ipoptp_flags |= IPOPTP_ERROR;
2821 		return (IPOPT_EOL);
2822 	}
2823 	optp->ipoptp_cur = cur;
2824 	optp->ipoptp_len = len;
2825 	optp->ipoptp_next = cur + len;
2826 	if (cur + len > end) {
2827 		optp->ipoptp_flags |= IPOPTP_ERROR;
2828 		return (IPOPT_EOL);
2829 	}
2830 
2831 	/*
2832 	 * For the options which require a pointer field, make sure
2833 	 * its there, and make sure it points to either something
2834 	 * inside this option, or the end of the option.
2835 	 */
2836 	switch (opt) {
2837 	case IPOPT_RR:
2838 	case IPOPT_TS:
2839 	case IPOPT_LSRR:
2840 	case IPOPT_SSRR:
2841 		if (len <= IPOPT_OFFSET) {
2842 			optp->ipoptp_flags |= IPOPTP_ERROR;
2843 			return (opt);
2844 		}
2845 		pointer = cur[IPOPT_OFFSET];
2846 		if (pointer - 1 > len) {
2847 			optp->ipoptp_flags |= IPOPTP_ERROR;
2848 			return (opt);
2849 		}
2850 		break;
2851 	}
2852 
2853 	/*
2854 	 * Sanity check the pointer field based on the type of the
2855 	 * option.
2856 	 */
2857 	switch (opt) {
2858 	case IPOPT_RR:
2859 	case IPOPT_SSRR:
2860 	case IPOPT_LSRR:
2861 		if (pointer < IPOPT_MINOFF_SR)
2862 			optp->ipoptp_flags |= IPOPTP_ERROR;
2863 		break;
2864 	case IPOPT_TS:
2865 		if (pointer < IPOPT_MINOFF_IT)
2866 			optp->ipoptp_flags |= IPOPTP_ERROR;
2867 		/*
2868 		 * Note that the Internet Timestamp option also
2869 		 * contains two four bit fields (the Overflow field,
2870 		 * and the Flag field), which follow the pointer
2871 		 * field.  We don't need to check that these fields
2872 		 * fall within the length of the option because this
2873 		 * was implicitely done above.  We've checked that the
2874 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2875 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2876 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2877 		 */
2878 		ASSERT(len > IPOPT_POS_OV_FLG);
2879 		break;
2880 	}
2881 
2882 	return (opt);
2883 }
2884 
2885 /*
2886  * Use the outgoing IP header to create an IP_OPTIONS option the way
2887  * it was passed down from the application.
2888  */
2889 int
2890 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2891 {
2892 	ipoptp_t	opts;
2893 	const uchar_t	*opt;
2894 	uint8_t		optval;
2895 	uint8_t		optlen;
2896 	uint32_t	len = 0;
2897 	uchar_t	*buf1 = buf;
2898 
2899 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2900 	len += IP_ADDR_LEN;
2901 	bzero(buf1, IP_ADDR_LEN);
2902 
2903 	/*
2904 	 * OK to cast away const here, as we don't store through the returned
2905 	 * opts.ipoptp_cur pointer.
2906 	 */
2907 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2908 	    optval != IPOPT_EOL;
2909 	    optval = ipoptp_next(&opts)) {
2910 		int	off;
2911 
2912 		opt = opts.ipoptp_cur;
2913 		optlen = opts.ipoptp_len;
2914 		switch (optval) {
2915 		case IPOPT_SSRR:
2916 		case IPOPT_LSRR:
2917 
2918 			/*
2919 			 * Insert ipha_dst as the first entry in the source
2920 			 * route and move down the entries on step.
2921 			 * The last entry gets placed at buf1.
2922 			 */
2923 			buf[IPOPT_OPTVAL] = optval;
2924 			buf[IPOPT_OLEN] = optlen;
2925 			buf[IPOPT_OFFSET] = optlen;
2926 
2927 			off = optlen - IP_ADDR_LEN;
2928 			if (off < 0) {
2929 				/* No entries in source route */
2930 				break;
2931 			}
2932 			/* Last entry in source route */
2933 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2934 			off -= IP_ADDR_LEN;
2935 
2936 			while (off > 0) {
2937 				bcopy(opt + off,
2938 				    buf + off + IP_ADDR_LEN,
2939 				    IP_ADDR_LEN);
2940 				off -= IP_ADDR_LEN;
2941 			}
2942 			/* ipha_dst into first slot */
2943 			bcopy(&ipha->ipha_dst,
2944 			    buf + off + IP_ADDR_LEN,
2945 			    IP_ADDR_LEN);
2946 			buf += optlen;
2947 			len += optlen;
2948 			break;
2949 
2950 		case IPOPT_COMSEC:
2951 		case IPOPT_SECURITY:
2952 			/* if passing up a label is not ok, then remove */
2953 			if (is_system_labeled())
2954 				break;
2955 			/* FALLTHROUGH */
2956 		default:
2957 			bcopy(opt, buf, optlen);
2958 			buf += optlen;
2959 			len += optlen;
2960 			break;
2961 		}
2962 	}
2963 done:
2964 	/* Pad the resulting options */
2965 	while (len & 0x3) {
2966 		*buf++ = IPOPT_EOL;
2967 		len++;
2968 	}
2969 	return (len);
2970 }
2971 
2972 /*
2973  * Update any record route or timestamp options to include this host.
2974  * Reverse any source route option.
2975  * This routine assumes that the options are well formed i.e. that they
2976  * have already been checked.
2977  */
2978 static void
2979 icmp_options_update(ipha_t *ipha)
2980 {
2981 	ipoptp_t	opts;
2982 	uchar_t		*opt;
2983 	uint8_t		optval;
2984 	ipaddr_t	src;		/* Our local address */
2985 	ipaddr_t	dst;
2986 
2987 	ip2dbg(("icmp_options_update\n"));
2988 	src = ipha->ipha_src;
2989 	dst = ipha->ipha_dst;
2990 
2991 	for (optval = ipoptp_first(&opts, ipha);
2992 	    optval != IPOPT_EOL;
2993 	    optval = ipoptp_next(&opts)) {
2994 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2995 		opt = opts.ipoptp_cur;
2996 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2997 		    optval, opts.ipoptp_len));
2998 		switch (optval) {
2999 			int off1, off2;
3000 		case IPOPT_SSRR:
3001 		case IPOPT_LSRR:
3002 			/*
3003 			 * Reverse the source route.  The first entry
3004 			 * should be the next to last one in the current
3005 			 * source route (the last entry is our address).
3006 			 * The last entry should be the final destination.
3007 			 */
3008 			off1 = IPOPT_MINOFF_SR - 1;
3009 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3010 			if (off2 < 0) {
3011 				/* No entries in source route */
3012 				ip1dbg((
3013 				    "icmp_options_update: bad src route\n"));
3014 				break;
3015 			}
3016 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3017 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3018 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3019 			off2 -= IP_ADDR_LEN;
3020 
3021 			while (off1 < off2) {
3022 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3023 				bcopy((char *)opt + off2, (char *)opt + off1,
3024 				    IP_ADDR_LEN);
3025 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3026 				off1 += IP_ADDR_LEN;
3027 				off2 -= IP_ADDR_LEN;
3028 			}
3029 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3030 			break;
3031 		}
3032 	}
3033 }
3034 
3035 /*
3036  * Process received ICMP Redirect messages.
3037  */
3038 static void
3039 icmp_redirect(ill_t *ill, mblk_t *mp)
3040 {
3041 	ipha_t	*ipha;
3042 	int	iph_hdr_length;
3043 	icmph_t	*icmph;
3044 	ipha_t	*ipha_err;
3045 	ire_t	*ire;
3046 	ire_t	*prev_ire;
3047 	ire_t	*save_ire;
3048 	ipaddr_t  src, dst, gateway;
3049 	iulp_t	ulp_info = { 0 };
3050 	int	error;
3051 	ip_stack_t *ipst;
3052 
3053 	ASSERT(ill != NULL);
3054 	ipst = ill->ill_ipst;
3055 
3056 	ipha = (ipha_t *)mp->b_rptr;
3057 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3058 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3059 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3060 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3061 		freemsg(mp);
3062 		return;
3063 	}
3064 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3065 	ipha_err = (ipha_t *)&icmph[1];
3066 	src = ipha->ipha_src;
3067 	dst = ipha_err->ipha_dst;
3068 	gateway = icmph->icmph_rd_gateway;
3069 	/* Make sure the new gateway is reachable somehow. */
3070 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3071 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3072 	/*
3073 	 * Make sure we had a route for the dest in question and that
3074 	 * that route was pointing to the old gateway (the source of the
3075 	 * redirect packet.)
3076 	 */
3077 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3078 	    NULL, MATCH_IRE_GW, ipst);
3079 	/*
3080 	 * Check that
3081 	 *	the redirect was not from ourselves
3082 	 *	the new gateway and the old gateway are directly reachable
3083 	 */
3084 	if (!prev_ire ||
3085 	    !ire ||
3086 	    ire->ire_type == IRE_LOCAL) {
3087 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3088 		freemsg(mp);
3089 		if (ire != NULL)
3090 			ire_refrele(ire);
3091 		if (prev_ire != NULL)
3092 			ire_refrele(prev_ire);
3093 		return;
3094 	}
3095 
3096 	/*
3097 	 * Should we use the old ULP info to create the new gateway?  From
3098 	 * a user's perspective, we should inherit the info so that it
3099 	 * is a "smooth" transition.  If we do not do that, then new
3100 	 * connections going thru the new gateway will have no route metrics,
3101 	 * which is counter-intuitive to user.  From a network point of
3102 	 * view, this may or may not make sense even though the new gateway
3103 	 * is still directly connected to us so the route metrics should not
3104 	 * change much.
3105 	 *
3106 	 * But if the old ire_uinfo is not initialized, we do another
3107 	 * recursive lookup on the dest using the new gateway.  There may
3108 	 * be a route to that.  If so, use it to initialize the redirect
3109 	 * route.
3110 	 */
3111 	if (prev_ire->ire_uinfo.iulp_set) {
3112 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3113 	} else {
3114 		ire_t *tmp_ire;
3115 		ire_t *sire;
3116 
3117 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3118 		    ALL_ZONES, 0, NULL,
3119 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3120 		    ipst);
3121 		if (sire != NULL) {
3122 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3123 			/*
3124 			 * If sire != NULL, ire_ftable_lookup() should not
3125 			 * return a NULL value.
3126 			 */
3127 			ASSERT(tmp_ire != NULL);
3128 			ire_refrele(tmp_ire);
3129 			ire_refrele(sire);
3130 		} else if (tmp_ire != NULL) {
3131 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3132 			    sizeof (iulp_t));
3133 			ire_refrele(tmp_ire);
3134 		}
3135 	}
3136 	if (prev_ire->ire_type == IRE_CACHE)
3137 		ire_delete(prev_ire);
3138 	ire_refrele(prev_ire);
3139 	/*
3140 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3141 	 * require TOS routing
3142 	 */
3143 	switch (icmph->icmph_code) {
3144 	case 0:
3145 	case 1:
3146 		/* TODO: TOS specificity for cases 2 and 3 */
3147 	case 2:
3148 	case 3:
3149 		break;
3150 	default:
3151 		freemsg(mp);
3152 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3153 		ire_refrele(ire);
3154 		return;
3155 	}
3156 	/*
3157 	 * Create a Route Association.  This will allow us to remember that
3158 	 * someone we believe told us to use the particular gateway.
3159 	 */
3160 	save_ire = ire;
3161 	ire = ire_create(
3162 	    (uchar_t *)&dst,			/* dest addr */
3163 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3164 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3165 	    (uchar_t *)&gateway,		/* gateway addr */
3166 	    &save_ire->ire_max_frag,		/* max frag */
3167 	    NULL,				/* no src nce */
3168 	    NULL,				/* no rfq */
3169 	    NULL,				/* no stq */
3170 	    IRE_HOST,
3171 	    NULL,				/* ipif */
3172 	    0,					/* cmask */
3173 	    0,					/* phandle */
3174 	    0,					/* ihandle */
3175 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3176 	    &ulp_info,
3177 	    NULL,				/* tsol_gc_t */
3178 	    NULL,				/* gcgrp */
3179 	    ipst);
3180 
3181 	if (ire == NULL) {
3182 		freemsg(mp);
3183 		ire_refrele(save_ire);
3184 		return;
3185 	}
3186 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3187 	ire_refrele(save_ire);
3188 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3189 
3190 	if (error == 0) {
3191 		ire_refrele(ire);		/* Held in ire_add_v4 */
3192 		/* tell routing sockets that we received a redirect */
3193 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3194 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3195 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3196 	}
3197 
3198 	/*
3199 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3200 	 * This together with the added IRE has the effect of
3201 	 * modifying an existing redirect.
3202 	 */
3203 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3204 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3205 	if (prev_ire != NULL) {
3206 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3207 			ire_delete(prev_ire);
3208 		ire_refrele(prev_ire);
3209 	}
3210 
3211 	freemsg(mp);
3212 }
3213 
3214 /*
3215  * Generate an ICMP parameter problem message.
3216  */
3217 static void
3218 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3219 	ip_stack_t *ipst)
3220 {
3221 	icmph_t	icmph;
3222 	boolean_t mctl_present;
3223 	mblk_t *first_mp;
3224 
3225 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3226 
3227 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3228 		if (mctl_present)
3229 			freeb(first_mp);
3230 		return;
3231 	}
3232 
3233 	bzero(&icmph, sizeof (icmph_t));
3234 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3235 	icmph.icmph_pp_ptr = ptr;
3236 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3237 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3238 	    ipst);
3239 }
3240 
3241 /*
3242  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3243  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3244  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3245  * an icmp error packet can be sent.
3246  * Assigns an appropriate source address to the packet. If ipha_dst is
3247  * one of our addresses use it for source. Otherwise pick a source based
3248  * on a route lookup back to ipha_src.
3249  * Note that ipha_src must be set here since the
3250  * packet is likely to arrive on an ill queue in ip_wput() which will
3251  * not set a source address.
3252  */
3253 static void
3254 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3255     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3256 {
3257 	ipaddr_t dst;
3258 	icmph_t	*icmph;
3259 	ipha_t	*ipha;
3260 	uint_t	len_needed;
3261 	size_t	msg_len;
3262 	mblk_t	*mp1;
3263 	ipaddr_t src;
3264 	ire_t	*ire;
3265 	mblk_t *ipsec_mp;
3266 	ipsec_out_t	*io = NULL;
3267 
3268 	if (mctl_present) {
3269 		/*
3270 		 * If it is :
3271 		 *
3272 		 * 1) a IPSEC_OUT, then this is caused by outbound
3273 		 *    datagram originating on this host. IPsec processing
3274 		 *    may or may not have been done. Refer to comments above
3275 		 *    icmp_inbound_error_fanout for details.
3276 		 *
3277 		 * 2) a IPSEC_IN if we are generating a icmp_message
3278 		 *    for an incoming datagram destined for us i.e called
3279 		 *    from ip_fanout_send_icmp.
3280 		 */
3281 		ipsec_info_t *in;
3282 		ipsec_mp = mp;
3283 		mp = ipsec_mp->b_cont;
3284 
3285 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3286 		ipha = (ipha_t *)mp->b_rptr;
3287 
3288 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3289 		    in->ipsec_info_type == IPSEC_IN);
3290 
3291 		if (in->ipsec_info_type == IPSEC_IN) {
3292 			/*
3293 			 * Convert the IPSEC_IN to IPSEC_OUT.
3294 			 */
3295 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3296 				BUMP_MIB(&ipst->ips_ip_mib,
3297 				    ipIfStatsOutDiscards);
3298 				return;
3299 			}
3300 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3301 		} else {
3302 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3303 			io = (ipsec_out_t *)in;
3304 			/*
3305 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3306 			 * ire lookup.
3307 			 */
3308 			io->ipsec_out_proc_begin = B_FALSE;
3309 		}
3310 		ASSERT(zoneid != ALL_ZONES);
3311 		/*
3312 		 * The IPSEC_IN (now an IPSEC_OUT) didn't have its zoneid
3313 		 * initialized.  We need to do that now.
3314 		 */
3315 		io->ipsec_out_zoneid = zoneid;
3316 	} else {
3317 		/*
3318 		 * This is in clear. The icmp message we are building
3319 		 * here should go out in clear.
3320 		 *
3321 		 * Pardon the convolution of it all, but it's easier to
3322 		 * allocate a "use cleartext" IPSEC_IN message and convert
3323 		 * it than it is to allocate a new one.
3324 		 */
3325 		ipsec_in_t *ii;
3326 		ASSERT(DB_TYPE(mp) == M_DATA);
3327 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3328 		if (ipsec_mp == NULL) {
3329 			freemsg(mp);
3330 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3331 			return;
3332 		}
3333 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3334 
3335 		/* This is not a secure packet */
3336 		ii->ipsec_in_secure = B_FALSE;
3337 		/*
3338 		 * For trusted extensions using a shared IP address we can
3339 		 * send using any zoneid.
3340 		 */
3341 		if (zoneid == ALL_ZONES)
3342 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3343 		else
3344 			ii->ipsec_in_zoneid = zoneid;
3345 		ipsec_mp->b_cont = mp;
3346 		ipha = (ipha_t *)mp->b_rptr;
3347 		/*
3348 		 * Convert the IPSEC_IN to IPSEC_OUT.
3349 		 */
3350 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3351 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3352 			return;
3353 		}
3354 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3355 	}
3356 
3357 	/* Remember our eventual destination */
3358 	dst = ipha->ipha_src;
3359 
3360 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3361 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3362 	if (ire != NULL &&
3363 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3364 		src = ipha->ipha_dst;
3365 	} else {
3366 		if (ire != NULL)
3367 			ire_refrele(ire);
3368 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3369 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3370 		    ipst);
3371 		if (ire == NULL) {
3372 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3373 			freemsg(ipsec_mp);
3374 			return;
3375 		}
3376 		src = ire->ire_src_addr;
3377 	}
3378 
3379 	if (ire != NULL)
3380 		ire_refrele(ire);
3381 
3382 	/*
3383 	 * Check if we can send back more then 8 bytes in addition to
3384 	 * the IP header.  We try to send 64 bytes of data and the internal
3385 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3386 	 */
3387 	len_needed = IPH_HDR_LENGTH(ipha);
3388 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3389 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3390 
3391 		if (!pullupmsg(mp, -1)) {
3392 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3393 			freemsg(ipsec_mp);
3394 			return;
3395 		}
3396 		ipha = (ipha_t *)mp->b_rptr;
3397 
3398 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3399 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3400 			    len_needed));
3401 		} else {
3402 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3403 
3404 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3405 			len_needed += ip_hdr_length_v6(mp, ip6h);
3406 		}
3407 	}
3408 	len_needed += ipst->ips_ip_icmp_return;
3409 	msg_len = msgdsize(mp);
3410 	if (msg_len > len_needed) {
3411 		(void) adjmsg(mp, len_needed - msg_len);
3412 		msg_len = len_needed;
3413 	}
3414 	/* Make sure we propagate the cred/label for TX */
3415 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3416 	if (mp1 == NULL) {
3417 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3418 		freemsg(ipsec_mp);
3419 		return;
3420 	}
3421 	mp1->b_cont = mp;
3422 	mp = mp1;
3423 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3424 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3425 	    io->ipsec_out_type == IPSEC_OUT);
3426 	ipsec_mp->b_cont = mp;
3427 
3428 	/*
3429 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3430 	 * node generates be accepted in peace by all on-host destinations.
3431 	 * If we do NOT assume that all on-host destinations trust
3432 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3433 	 * (Look for ipsec_out_icmp_loopback).
3434 	 */
3435 	io->ipsec_out_icmp_loopback = B_TRUE;
3436 
3437 	ipha = (ipha_t *)mp->b_rptr;
3438 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3439 	*ipha = icmp_ipha;
3440 	ipha->ipha_src = src;
3441 	ipha->ipha_dst = dst;
3442 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3443 	msg_len += sizeof (icmp_ipha) + len;
3444 	if (msg_len > IP_MAXPACKET) {
3445 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3446 		msg_len = IP_MAXPACKET;
3447 	}
3448 	ipha->ipha_length = htons((uint16_t)msg_len);
3449 	icmph = (icmph_t *)&ipha[1];
3450 	bcopy(stuff, icmph, len);
3451 	icmph->icmph_checksum = 0;
3452 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3453 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3454 	put(q, ipsec_mp);
3455 }
3456 
3457 /*
3458  * Determine if an ICMP error packet can be sent given the rate limit.
3459  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3460  * in milliseconds) and a burst size. Burst size number of packets can
3461  * be sent arbitrarely closely spaced.
3462  * The state is tracked using two variables to implement an approximate
3463  * token bucket filter:
3464  *	icmp_pkt_err_last - lbolt value when the last burst started
3465  *	icmp_pkt_err_sent - number of packets sent in current burst
3466  */
3467 boolean_t
3468 icmp_err_rate_limit(ip_stack_t *ipst)
3469 {
3470 	clock_t now = TICK_TO_MSEC(lbolt);
3471 	uint_t refilled; /* Number of packets refilled in tbf since last */
3472 	/* Guard against changes by loading into local variable */
3473 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3474 
3475 	if (err_interval == 0)
3476 		return (B_FALSE);
3477 
3478 	if (ipst->ips_icmp_pkt_err_last > now) {
3479 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3480 		ipst->ips_icmp_pkt_err_last = 0;
3481 		ipst->ips_icmp_pkt_err_sent = 0;
3482 	}
3483 	/*
3484 	 * If we are in a burst update the token bucket filter.
3485 	 * Update the "last" time to be close to "now" but make sure
3486 	 * we don't loose precision.
3487 	 */
3488 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3489 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3490 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3491 			ipst->ips_icmp_pkt_err_sent = 0;
3492 		} else {
3493 			ipst->ips_icmp_pkt_err_sent -= refilled;
3494 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3495 		}
3496 	}
3497 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3498 		/* Start of new burst */
3499 		ipst->ips_icmp_pkt_err_last = now;
3500 	}
3501 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3502 		ipst->ips_icmp_pkt_err_sent++;
3503 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3504 		    ipst->ips_icmp_pkt_err_sent));
3505 		return (B_FALSE);
3506 	}
3507 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3508 	return (B_TRUE);
3509 }
3510 
3511 /*
3512  * Check if it is ok to send an IPv4 ICMP error packet in
3513  * response to the IPv4 packet in mp.
3514  * Free the message and return null if no
3515  * ICMP error packet should be sent.
3516  */
3517 static mblk_t *
3518 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3519 {
3520 	icmph_t	*icmph;
3521 	ipha_t	*ipha;
3522 	uint_t	len_needed;
3523 	ire_t	*src_ire;
3524 	ire_t	*dst_ire;
3525 
3526 	if (!mp)
3527 		return (NULL);
3528 	ipha = (ipha_t *)mp->b_rptr;
3529 	if (ip_csum_hdr(ipha)) {
3530 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3531 		freemsg(mp);
3532 		return (NULL);
3533 	}
3534 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3535 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3536 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3537 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3538 	if (src_ire != NULL || dst_ire != NULL ||
3539 	    CLASSD(ipha->ipha_dst) ||
3540 	    CLASSD(ipha->ipha_src) ||
3541 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3542 		/* Note: only errors to the fragment with offset 0 */
3543 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3544 		freemsg(mp);
3545 		if (src_ire != NULL)
3546 			ire_refrele(src_ire);
3547 		if (dst_ire != NULL)
3548 			ire_refrele(dst_ire);
3549 		return (NULL);
3550 	}
3551 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3552 		/*
3553 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3554 		 * errors in response to any ICMP errors.
3555 		 */
3556 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3557 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3558 			if (!pullupmsg(mp, len_needed)) {
3559 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3560 				freemsg(mp);
3561 				return (NULL);
3562 			}
3563 			ipha = (ipha_t *)mp->b_rptr;
3564 		}
3565 		icmph = (icmph_t *)
3566 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3567 		switch (icmph->icmph_type) {
3568 		case ICMP_DEST_UNREACHABLE:
3569 		case ICMP_SOURCE_QUENCH:
3570 		case ICMP_TIME_EXCEEDED:
3571 		case ICMP_PARAM_PROBLEM:
3572 		case ICMP_REDIRECT:
3573 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3574 			freemsg(mp);
3575 			return (NULL);
3576 		default:
3577 			break;
3578 		}
3579 	}
3580 	/*
3581 	 * If this is a labeled system, then check to see if we're allowed to
3582 	 * send a response to this particular sender.  If not, then just drop.
3583 	 */
3584 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3585 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3586 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3587 		freemsg(mp);
3588 		return (NULL);
3589 	}
3590 	if (icmp_err_rate_limit(ipst)) {
3591 		/*
3592 		 * Only send ICMP error packets every so often.
3593 		 * This should be done on a per port/source basis,
3594 		 * but for now this will suffice.
3595 		 */
3596 		freemsg(mp);
3597 		return (NULL);
3598 	}
3599 	return (mp);
3600 }
3601 
3602 /*
3603  * Generate an ICMP redirect message.
3604  */
3605 static void
3606 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3607 {
3608 	icmph_t	icmph;
3609 
3610 	/*
3611 	 * We are called from ip_rput where we could
3612 	 * not have attached an IPSEC_IN.
3613 	 */
3614 	ASSERT(mp->b_datap->db_type == M_DATA);
3615 
3616 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3617 		return;
3618 	}
3619 
3620 	bzero(&icmph, sizeof (icmph_t));
3621 	icmph.icmph_type = ICMP_REDIRECT;
3622 	icmph.icmph_code = 1;
3623 	icmph.icmph_rd_gateway = gateway;
3624 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3625 	/* Redirects sent by router, and router is global zone */
3626 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3627 }
3628 
3629 /*
3630  * Generate an ICMP time exceeded message.
3631  */
3632 void
3633 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3634     ip_stack_t *ipst)
3635 {
3636 	icmph_t	icmph;
3637 	boolean_t mctl_present;
3638 	mblk_t *first_mp;
3639 
3640 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3641 
3642 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3643 		if (mctl_present)
3644 			freeb(first_mp);
3645 		return;
3646 	}
3647 
3648 	bzero(&icmph, sizeof (icmph_t));
3649 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3650 	icmph.icmph_code = code;
3651 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3652 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3653 	    ipst);
3654 }
3655 
3656 /*
3657  * Generate an ICMP unreachable message.
3658  */
3659 void
3660 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3661     ip_stack_t *ipst)
3662 {
3663 	icmph_t	icmph;
3664 	mblk_t *first_mp;
3665 	boolean_t mctl_present;
3666 
3667 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3668 
3669 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3670 		if (mctl_present)
3671 			freeb(first_mp);
3672 		return;
3673 	}
3674 
3675 	bzero(&icmph, sizeof (icmph_t));
3676 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3677 	icmph.icmph_code = code;
3678 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3679 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3680 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3681 	    zoneid, ipst);
3682 }
3683 
3684 /*
3685  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3686  * duplicate.  As long as someone else holds the address, the interface will
3687  * stay down.  When that conflict goes away, the interface is brought back up.
3688  * This is done so that accidental shutdowns of addresses aren't made
3689  * permanent.  Your server will recover from a failure.
3690  *
3691  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3692  * user space process (dhcpagent).
3693  *
3694  * Recovery completes if ARP reports that the address is now ours (via
3695  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3696  *
3697  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3698  */
3699 static void
3700 ipif_dup_recovery(void *arg)
3701 {
3702 	ipif_t *ipif = arg;
3703 	ill_t *ill = ipif->ipif_ill;
3704 	mblk_t *arp_add_mp;
3705 	mblk_t *arp_del_mp;
3706 	ip_stack_t *ipst = ill->ill_ipst;
3707 
3708 	ipif->ipif_recovery_id = 0;
3709 
3710 	/*
3711 	 * No lock needed for moving or condemned check, as this is just an
3712 	 * optimization.
3713 	 */
3714 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3715 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3716 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3717 		/* No reason to try to bring this address back. */
3718 		return;
3719 	}
3720 
3721 	/* ACE_F_UNVERIFIED restarts DAD */
3722 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3723 		goto alloc_fail;
3724 
3725 	if (ipif->ipif_arp_del_mp == NULL) {
3726 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3727 			goto alloc_fail;
3728 		ipif->ipif_arp_del_mp = arp_del_mp;
3729 	}
3730 
3731 	putnext(ill->ill_rq, arp_add_mp);
3732 	return;
3733 
3734 alloc_fail:
3735 	/*
3736 	 * On allocation failure, just restart the timer.  Note that the ipif
3737 	 * is down here, so no other thread could be trying to start a recovery
3738 	 * timer.  The ill_lock protects the condemned flag and the recovery
3739 	 * timer ID.
3740 	 */
3741 	freemsg(arp_add_mp);
3742 	mutex_enter(&ill->ill_lock);
3743 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3744 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3745 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3746 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3747 	}
3748 	mutex_exit(&ill->ill_lock);
3749 }
3750 
3751 /*
3752  * This is for exclusive changes due to ARP.  Either tear down an interface due
3753  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3754  */
3755 /* ARGSUSED */
3756 static void
3757 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3758 {
3759 	ill_t	*ill = rq->q_ptr;
3760 	arh_t *arh;
3761 	ipaddr_t src;
3762 	ipif_t	*ipif;
3763 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3764 	char hbuf[MAC_STR_LEN];
3765 	char sbuf[INET_ADDRSTRLEN];
3766 	const char *failtype;
3767 	boolean_t bring_up;
3768 	ip_stack_t *ipst = ill->ill_ipst;
3769 
3770 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3771 	case AR_CN_READY:
3772 		failtype = NULL;
3773 		bring_up = B_TRUE;
3774 		break;
3775 	case AR_CN_FAILED:
3776 		failtype = "in use";
3777 		bring_up = B_FALSE;
3778 		break;
3779 	default:
3780 		failtype = "claimed";
3781 		bring_up = B_FALSE;
3782 		break;
3783 	}
3784 
3785 	arh = (arh_t *)mp->b_cont->b_rptr;
3786 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3787 
3788 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3789 	    sizeof (hbuf));
3790 	(void) ip_dot_addr(src, sbuf);
3791 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3792 
3793 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3794 		    ipif->ipif_lcl_addr != src) {
3795 			continue;
3796 		}
3797 
3798 		/*
3799 		 * If we failed on a recovery probe, then restart the timer to
3800 		 * try again later.
3801 		 */
3802 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3803 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3804 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3805 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3806 		    ipst->ips_ip_dup_recovery > 0 &&
3807 		    ipif->ipif_recovery_id == 0) {
3808 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3809 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3810 			continue;
3811 		}
3812 
3813 		/*
3814 		 * If what we're trying to do has already been done, then do
3815 		 * nothing.
3816 		 */
3817 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3818 			continue;
3819 
3820 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3821 
3822 		if (failtype == NULL) {
3823 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3824 			    ibuf);
3825 		} else {
3826 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3827 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3828 		}
3829 
3830 		if (bring_up) {
3831 			ASSERT(ill->ill_dl_up);
3832 			/*
3833 			 * Free up the ARP delete message so we can allocate
3834 			 * a fresh one through the normal path.
3835 			 */
3836 			freemsg(ipif->ipif_arp_del_mp);
3837 			ipif->ipif_arp_del_mp = NULL;
3838 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3839 			    EINPROGRESS) {
3840 				ipif->ipif_addr_ready = 1;
3841 				(void) ipif_up_done(ipif);
3842 				ASSERT(ill->ill_move_ipif == NULL);
3843 			}
3844 			continue;
3845 		}
3846 
3847 		mutex_enter(&ill->ill_lock);
3848 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3849 		ipif->ipif_flags |= IPIF_DUPLICATE;
3850 		ill->ill_ipif_dup_count++;
3851 		mutex_exit(&ill->ill_lock);
3852 		/*
3853 		 * Already exclusive on the ill; no need to handle deferred
3854 		 * processing here.
3855 		 */
3856 		(void) ipif_down(ipif, NULL, NULL);
3857 		ipif_down_tail(ipif);
3858 		mutex_enter(&ill->ill_lock);
3859 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3860 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3861 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3862 		    ipst->ips_ip_dup_recovery > 0) {
3863 			ASSERT(ipif->ipif_recovery_id == 0);
3864 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3865 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3866 		}
3867 		mutex_exit(&ill->ill_lock);
3868 	}
3869 	freemsg(mp);
3870 }
3871 
3872 /* ARGSUSED */
3873 static void
3874 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3875 {
3876 	ill_t	*ill = rq->q_ptr;
3877 	arh_t *arh;
3878 	ipaddr_t src;
3879 	ipif_t	*ipif;
3880 
3881 	arh = (arh_t *)mp->b_cont->b_rptr;
3882 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3883 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3884 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3885 			(void) ipif_resolver_up(ipif, Res_act_defend);
3886 	}
3887 	freemsg(mp);
3888 }
3889 
3890 /*
3891  * News from ARP.  ARP sends notification of interesting events down
3892  * to its clients using M_CTL messages with the interesting ARP packet
3893  * attached via b_cont.
3894  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3895  * queue as opposed to ARP sending the message to all the clients, i.e. all
3896  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3897  * table if a cache IRE is found to delete all the entries for the address in
3898  * the packet.
3899  */
3900 static void
3901 ip_arp_news(queue_t *q, mblk_t *mp)
3902 {
3903 	arcn_t		*arcn;
3904 	arh_t		*arh;
3905 	ire_t		*ire = NULL;
3906 	char		hbuf[MAC_STR_LEN];
3907 	char		sbuf[INET_ADDRSTRLEN];
3908 	ipaddr_t	src;
3909 	in6_addr_t	v6src;
3910 	boolean_t	isv6 = B_FALSE;
3911 	ipif_t		*ipif;
3912 	ill_t		*ill;
3913 	ip_stack_t	*ipst;
3914 
3915 	if (CONN_Q(q)) {
3916 		conn_t *connp = Q_TO_CONN(q);
3917 
3918 		ipst = connp->conn_netstack->netstack_ip;
3919 	} else {
3920 		ill_t *ill = (ill_t *)q->q_ptr;
3921 
3922 		ipst = ill->ill_ipst;
3923 	}
3924 
3925 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3926 		if (q->q_next) {
3927 			putnext(q, mp);
3928 		} else
3929 			freemsg(mp);
3930 		return;
3931 	}
3932 	arh = (arh_t *)mp->b_cont->b_rptr;
3933 	/* Is it one we are interested in? */
3934 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3935 		isv6 = B_TRUE;
3936 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3937 		    IPV6_ADDR_LEN);
3938 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3939 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3940 		    IP_ADDR_LEN);
3941 	} else {
3942 		freemsg(mp);
3943 		return;
3944 	}
3945 
3946 	ill = q->q_ptr;
3947 
3948 	arcn = (arcn_t *)mp->b_rptr;
3949 	switch (arcn->arcn_code) {
3950 	case AR_CN_BOGON:
3951 		/*
3952 		 * Someone is sending ARP packets with a source protocol
3953 		 * address that we have published and for which we believe our
3954 		 * entry is authoritative and (when ill_arp_extend is set)
3955 		 * verified to be unique on the network.
3956 		 *
3957 		 * The ARP module internally handles the cases where the sender
3958 		 * is just probing (for DAD) and where the hardware address of
3959 		 * a non-authoritative entry has changed.  Thus, these are the
3960 		 * real conflicts, and we have to do resolution.
3961 		 *
3962 		 * We back away quickly from the address if it's from DHCP or
3963 		 * otherwise temporary and hasn't been used recently (or at
3964 		 * all).  We'd like to include "deprecated" addresses here as
3965 		 * well (as there's no real reason to defend something we're
3966 		 * discarding), but IPMP "reuses" this flag to mean something
3967 		 * other than the standard meaning.
3968 		 *
3969 		 * If the ARP module above is not extended (meaning that it
3970 		 * doesn't know how to defend the address), then we just log
3971 		 * the problem as we always did and continue on.  It's not
3972 		 * right, but there's little else we can do, and those old ATM
3973 		 * users are going away anyway.
3974 		 */
3975 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3976 		    hbuf, sizeof (hbuf));
3977 		(void) ip_dot_addr(src, sbuf);
3978 		if (isv6) {
3979 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3980 			    ipst);
3981 		} else {
3982 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3983 		}
3984 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3985 			uint32_t now;
3986 			uint32_t maxage;
3987 			clock_t lused;
3988 			uint_t maxdefense;
3989 			uint_t defs;
3990 
3991 			/*
3992 			 * First, figure out if this address hasn't been used
3993 			 * in a while.  If it hasn't, then it's a better
3994 			 * candidate for abandoning.
3995 			 */
3996 			ipif = ire->ire_ipif;
3997 			ASSERT(ipif != NULL);
3998 			now = gethrestime_sec();
3999 			maxage = now - ire->ire_create_time;
4000 			if (maxage > ipst->ips_ip_max_temp_idle)
4001 				maxage = ipst->ips_ip_max_temp_idle;
4002 			lused = drv_hztousec(ddi_get_lbolt() -
4003 			    ire->ire_last_used_time) / MICROSEC + 1;
4004 			if (lused >= maxage && (ipif->ipif_flags &
4005 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4006 				maxdefense = ipst->ips_ip_max_temp_defend;
4007 			else
4008 				maxdefense = ipst->ips_ip_max_defend;
4009 
4010 			/*
4011 			 * Now figure out how many times we've defended
4012 			 * ourselves.  Ignore defenses that happened long in
4013 			 * the past.
4014 			 */
4015 			mutex_enter(&ire->ire_lock);
4016 			if ((defs = ire->ire_defense_count) > 0 &&
4017 			    now - ire->ire_defense_time >
4018 			    ipst->ips_ip_defend_interval) {
4019 				ire->ire_defense_count = defs = 0;
4020 			}
4021 			ire->ire_defense_count++;
4022 			ire->ire_defense_time = now;
4023 			mutex_exit(&ire->ire_lock);
4024 			ill_refhold(ill);
4025 			ire_refrele(ire);
4026 
4027 			/*
4028 			 * If we've defended ourselves too many times already,
4029 			 * then give up and tear down the interface(s) using
4030 			 * this address.  Otherwise, defend by sending out a
4031 			 * gratuitous ARP.
4032 			 */
4033 			if (defs >= maxdefense && ill->ill_arp_extend) {
4034 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4035 				    B_FALSE);
4036 			} else {
4037 				cmn_err(CE_WARN,
4038 				    "node %s is using our IP address %s on %s",
4039 				    hbuf, sbuf, ill->ill_name);
4040 				/*
4041 				 * If this is an old (ATM) ARP module, then
4042 				 * don't try to defend the address.  Remain
4043 				 * compatible with the old behavior.  Defend
4044 				 * only with new ARP.
4045 				 */
4046 				if (ill->ill_arp_extend) {
4047 					qwriter_ip(ill, q, mp, ip_arp_defend,
4048 					    NEW_OP, B_FALSE);
4049 				} else {
4050 					ill_refrele(ill);
4051 				}
4052 			}
4053 			return;
4054 		}
4055 		cmn_err(CE_WARN,
4056 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4057 		    hbuf, sbuf, ill->ill_name);
4058 		if (ire != NULL)
4059 			ire_refrele(ire);
4060 		break;
4061 	case AR_CN_ANNOUNCE:
4062 		if (isv6) {
4063 			/*
4064 			 * For XRESOLV interfaces.
4065 			 * Delete the IRE cache entry and NCE for this
4066 			 * v6 address
4067 			 */
4068 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4069 			/*
4070 			 * If v6src is a non-zero, it's a router address
4071 			 * as below. Do the same sort of thing to clean
4072 			 * out off-net IRE_CACHE entries that go through
4073 			 * the router.
4074 			 */
4075 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4076 				ire_walk_v6(ire_delete_cache_gw_v6,
4077 				    (char *)&v6src, ALL_ZONES, ipst);
4078 			}
4079 		} else {
4080 			nce_hw_map_t hwm;
4081 
4082 			/*
4083 			 * ARP gives us a copy of any packet where it thinks
4084 			 * the address has changed, so that we can update our
4085 			 * caches.  We're responsible for caching known answers
4086 			 * in the current design.  We check whether the
4087 			 * hardware address really has changed in all of our
4088 			 * entries that have cached this mapping, and if so, we
4089 			 * blow them away.  This way we will immediately pick
4090 			 * up the rare case of a host changing hardware
4091 			 * address.
4092 			 */
4093 			if (src == 0)
4094 				break;
4095 			hwm.hwm_addr = src;
4096 			hwm.hwm_hwlen = arh->arh_hlen;
4097 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4098 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4099 			ndp_walk_common(ipst->ips_ndp4, NULL,
4100 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4101 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4102 		}
4103 		break;
4104 	case AR_CN_READY:
4105 		/* No external v6 resolver has a contract to use this */
4106 		if (isv6)
4107 			break;
4108 		/* If the link is down, we'll retry this later */
4109 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4110 			break;
4111 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4112 		    NULL, NULL, ipst);
4113 		if (ipif != NULL) {
4114 			/*
4115 			 * If this is a duplicate recovery, then we now need to
4116 			 * go exclusive to bring this thing back up.
4117 			 */
4118 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4119 			    IPIF_DUPLICATE) {
4120 				ipif_refrele(ipif);
4121 				ill_refhold(ill);
4122 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4123 				    B_FALSE);
4124 				return;
4125 			}
4126 			/*
4127 			 * If this is the first notice that this address is
4128 			 * ready, then let the user know now.
4129 			 */
4130 			if ((ipif->ipif_flags & IPIF_UP) &&
4131 			    !ipif->ipif_addr_ready) {
4132 				ipif_mask_reply(ipif);
4133 				ipif_up_notify(ipif);
4134 			}
4135 			ipif->ipif_addr_ready = 1;
4136 			ipif_refrele(ipif);
4137 		}
4138 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4139 		if (ire != NULL) {
4140 			ire->ire_defense_count = 0;
4141 			ire_refrele(ire);
4142 		}
4143 		break;
4144 	case AR_CN_FAILED:
4145 		/* No external v6 resolver has a contract to use this */
4146 		if (isv6)
4147 			break;
4148 		if (!ill->ill_arp_extend) {
4149 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4150 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4151 			(void) ip_dot_addr(src, sbuf);
4152 
4153 			cmn_err(CE_WARN,
4154 			    "node %s is using our IP address %s on %s",
4155 			    hbuf, sbuf, ill->ill_name);
4156 			break;
4157 		}
4158 		ill_refhold(ill);
4159 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4160 		return;
4161 	}
4162 	freemsg(mp);
4163 }
4164 
4165 /*
4166  * Create a mblk suitable for carrying the interface index and/or source link
4167  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4168  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4169  * application.
4170  */
4171 mblk_t *
4172 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4173     ip_stack_t *ipst)
4174 {
4175 	mblk_t		*mp;
4176 	ip_pktinfo_t	*pinfo;
4177 	ipha_t 		*ipha;
4178 	struct ether_header *pether;
4179 	boolean_t	ipmp_ill_held = B_FALSE;
4180 
4181 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4182 	if (mp == NULL) {
4183 		ip1dbg(("ip_add_info: allocation failure.\n"));
4184 		return (data_mp);
4185 	}
4186 
4187 	ipha = (ipha_t *)data_mp->b_rptr;
4188 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4189 	bzero(pinfo, sizeof (ip_pktinfo_t));
4190 	pinfo->ip_pkt_flags = (uchar_t)flags;
4191 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4192 
4193 	pether = (struct ether_header *)((char *)ipha
4194 	    - sizeof (struct ether_header));
4195 
4196 	/*
4197 	 * Make sure the interface is an ethernet type, since this option
4198 	 * is currently supported only on this type of interface. Also make
4199 	 * sure we are pointing correctly above db_base.
4200 	 */
4201 	if ((flags & IPF_RECVSLLA) &&
4202 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4203 	    (ill->ill_type == IFT_ETHER) &&
4204 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4205 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4206 		bcopy(pether->ether_shost.ether_addr_octet,
4207 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4208 	} else {
4209 		/*
4210 		 * Clear the bit. Indicate to upper layer that IP is not
4211 		 * sending this ancillary info.
4212 		 */
4213 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4214 	}
4215 
4216 	/*
4217 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4218 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4219 	 * IPF_RECVADDR support on test addresses is not needed.)
4220 	 *
4221 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4222 	 * processing a packet looped back to an IPMP data address
4223 	 * (since those IRE_LOCALs are tied to IPMP ills).
4224 	 */
4225 	if (IS_UNDER_IPMP(ill)) {
4226 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4227 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4228 			freemsg(mp);
4229 			return (data_mp);
4230 		}
4231 		ipmp_ill_held = B_TRUE;
4232 	}
4233 
4234 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4235 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4236 	if (flags & IPF_RECVADDR) {
4237 		ipif_t	*ipif;
4238 		ire_t	*ire;
4239 
4240 		/*
4241 		 * Only valid for V4
4242 		 */
4243 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4244 		    (IPV4_VERSION << 4));
4245 
4246 		ipif = ipif_get_next_ipif(NULL, ill);
4247 		if (ipif != NULL) {
4248 			/*
4249 			 * Since a decision has already been made to deliver the
4250 			 * packet, there is no need to test for SECATTR and
4251 			 * ZONEONLY.
4252 			 * When a multicast packet is transmitted
4253 			 * a cache entry is created for the multicast address.
4254 			 * When delivering a copy of the packet or when new
4255 			 * packets are received we do not want to match on the
4256 			 * cached entry so explicitly match on
4257 			 * IRE_LOCAL and IRE_LOOPBACK
4258 			 */
4259 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4260 			    IRE_LOCAL | IRE_LOOPBACK,
4261 			    ipif, zoneid, NULL,
4262 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4263 			if (ire == NULL) {
4264 				/*
4265 				 * packet must have come on a different
4266 				 * interface.
4267 				 * Since a decision has already been made to
4268 				 * deliver the packet, there is no need to test
4269 				 * for SECATTR and ZONEONLY.
4270 				 * Only match on local and broadcast ire's.
4271 				 * See detailed comment above.
4272 				 */
4273 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4274 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4275 				    NULL, MATCH_IRE_TYPE, ipst);
4276 			}
4277 
4278 			if (ire == NULL) {
4279 				/*
4280 				 * This is either a multicast packet or
4281 				 * the address has been removed since
4282 				 * the packet was received.
4283 				 * Return INADDR_ANY so that normal source
4284 				 * selection occurs for the response.
4285 				 */
4286 
4287 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4288 			} else {
4289 				pinfo->ip_pkt_match_addr.s_addr =
4290 				    ire->ire_src_addr;
4291 				ire_refrele(ire);
4292 			}
4293 			ipif_refrele(ipif);
4294 		} else {
4295 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4296 		}
4297 	}
4298 
4299 	if (ipmp_ill_held)
4300 		ill_refrele(ill);
4301 
4302 	mp->b_datap->db_type = M_CTL;
4303 	mp->b_wptr += sizeof (ip_pktinfo_t);
4304 	mp->b_cont = data_mp;
4305 
4306 	return (mp);
4307 }
4308 
4309 /*
4310  * Used to determine the most accurate cred_t to use for TX.
4311  * First priority is SCM_UCRED having set the label in the message,
4312  * which is used for MLP on UDP. Second priority is the open credentials
4313  * with the peer's label (aka conn_effective_cred), which is needed for
4314  * MLP on TCP/SCTP and for MAC-Exempt. Last priority is the open credentials.
4315  */
4316 cred_t *
4317 ip_best_cred(mblk_t *mp, conn_t *connp, pid_t *pidp)
4318 {
4319 	cred_t *cr;
4320 
4321 	cr = msg_getcred(mp, pidp);
4322 	if (cr != NULL && crgetlabel(cr) != NULL)
4323 		return (cr);
4324 	*pidp = NOPID;
4325 	return (CONN_CRED(connp));
4326 }
4327 
4328 /*
4329  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4330  * part of the bind request.
4331  */
4332 
4333 boolean_t
4334 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4335 {
4336 	ipsec_in_t *ii;
4337 
4338 	ASSERT(policy_mp != NULL);
4339 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4340 
4341 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4342 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4343 
4344 	connp->conn_policy = ii->ipsec_in_policy;
4345 	ii->ipsec_in_policy = NULL;
4346 
4347 	if (ii->ipsec_in_action != NULL) {
4348 		if (connp->conn_latch == NULL) {
4349 			connp->conn_latch = iplatch_create();
4350 			if (connp->conn_latch == NULL)
4351 				return (B_FALSE);
4352 		}
4353 		ipsec_latch_inbound(connp->conn_latch, ii);
4354 	}
4355 	return (B_TRUE);
4356 }
4357 
4358 static void
4359 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4360 {
4361 	/*
4362 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4363 	 * We can't do this in ip_bind_get_ire because the policy
4364 	 * may not have been inherited at that point in time and hence
4365 	 * conn_out_enforce_policy may not be set.
4366 	 */
4367 	if (ire_requested && connp->conn_out_enforce_policy &&
4368 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4369 		ire_t *ire = (ire_t *)mp->b_rptr;
4370 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4371 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4372 	}
4373 }
4374 
4375 /*
4376  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4377  * and to arrange for power-fanout assist.  The ULP is identified by
4378  * adding a single byte at the end of the original bind message.
4379  * A ULP other than UDP or TCP that wishes to be recognized passes
4380  * down a bind with a zero length address.
4381  *
4382  * The binding works as follows:
4383  * - A zero byte address means just bind to the protocol.
4384  * - A four byte address is treated as a request to validate
4385  *   that the address is a valid local address, appropriate for
4386  *   an application to bind to. This does not affect any fanout
4387  *   information in IP.
4388  * - A sizeof sin_t byte address is used to bind to only the local address
4389  *   and port.
4390  * - A sizeof ipa_conn_t byte address contains complete fanout information
4391  *   consisting of local and remote addresses and ports.  In
4392  *   this case, the addresses are both validated as appropriate
4393  *   for this operation, and, if so, the information is retained
4394  *   for use in the inbound fanout.
4395  *
4396  * The ULP (except in the zero-length bind) can append an
4397  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4398  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4399  * a copy of the source or destination IRE (source for local bind;
4400  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4401  * policy information contained should be copied on to the conn.
4402  *
4403  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4404  */
4405 mblk_t *
4406 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4407 {
4408 	ssize_t		len;
4409 	struct T_bind_req	*tbr;
4410 	sin_t		*sin;
4411 	ipa_conn_t	*ac;
4412 	uchar_t		*ucp;
4413 	mblk_t		*mp1;
4414 	boolean_t	ire_requested;
4415 	int		error = 0;
4416 	int		protocol;
4417 	ipa_conn_x_t	*acx;
4418 	cred_t		*cr;
4419 
4420 	/*
4421 	 * All Solaris components should pass a db_credp
4422 	 * for this TPI message, hence we ASSERT.
4423 	 * But in case there is some other M_PROTO that looks
4424 	 * like a TPI message sent by some other kernel
4425 	 * component, we check and return an error.
4426 	 */
4427 	cr = msg_getcred(mp, NULL);
4428 	ASSERT(cr != NULL);
4429 	if (cr == NULL) {
4430 		error = EINVAL;
4431 		goto bad_addr;
4432 	}
4433 
4434 	ASSERT(!connp->conn_af_isv6);
4435 	connp->conn_pkt_isv6 = B_FALSE;
4436 
4437 	len = MBLKL(mp);
4438 	if (len < (sizeof (*tbr) + 1)) {
4439 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4440 		    "ip_bind: bogus msg, len %ld", len);
4441 		/* XXX: Need to return something better */
4442 		goto bad_addr;
4443 	}
4444 	/* Back up and extract the protocol identifier. */
4445 	mp->b_wptr--;
4446 	protocol = *mp->b_wptr & 0xFF;
4447 	tbr = (struct T_bind_req *)mp->b_rptr;
4448 	/* Reset the message type in preparation for shipping it back. */
4449 	DB_TYPE(mp) = M_PCPROTO;
4450 
4451 	connp->conn_ulp = (uint8_t)protocol;
4452 
4453 	/*
4454 	 * Check for a zero length address.  This is from a protocol that
4455 	 * wants to register to receive all packets of its type.
4456 	 */
4457 	if (tbr->ADDR_length == 0) {
4458 		/*
4459 		 * These protocols are now intercepted in ip_bind_v6().
4460 		 * Reject protocol-level binds here for now.
4461 		 *
4462 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4463 		 * so that the protocol type cannot be SCTP.
4464 		 */
4465 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4466 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4467 			goto bad_addr;
4468 		}
4469 
4470 		/*
4471 		 *
4472 		 * The udp module never sends down a zero-length address,
4473 		 * and allowing this on a labeled system will break MLP
4474 		 * functionality.
4475 		 */
4476 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4477 			goto bad_addr;
4478 
4479 		if (connp->conn_mac_exempt)
4480 			goto bad_addr;
4481 
4482 		/* No hash here really.  The table is big enough. */
4483 		connp->conn_srcv6 = ipv6_all_zeros;
4484 
4485 		ipcl_proto_insert(connp, protocol);
4486 
4487 		tbr->PRIM_type = T_BIND_ACK;
4488 		return (mp);
4489 	}
4490 
4491 	/* Extract the address pointer from the message. */
4492 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4493 	    tbr->ADDR_length);
4494 	if (ucp == NULL) {
4495 		ip1dbg(("ip_bind: no address\n"));
4496 		goto bad_addr;
4497 	}
4498 	if (!OK_32PTR(ucp)) {
4499 		ip1dbg(("ip_bind: unaligned address\n"));
4500 		goto bad_addr;
4501 	}
4502 	/*
4503 	 * Check for trailing mps.
4504 	 */
4505 
4506 	mp1 = mp->b_cont;
4507 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4508 
4509 	switch (tbr->ADDR_length) {
4510 	default:
4511 		ip1dbg(("ip_bind: bad address length %d\n",
4512 		    (int)tbr->ADDR_length));
4513 		goto bad_addr;
4514 
4515 	case IP_ADDR_LEN:
4516 		/* Verification of local address only */
4517 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4518 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4519 		break;
4520 
4521 	case sizeof (sin_t):
4522 		sin = (sin_t *)ucp;
4523 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4524 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4525 		break;
4526 
4527 	case sizeof (ipa_conn_t):
4528 		ac = (ipa_conn_t *)ucp;
4529 		/* For raw socket, the local port is not set. */
4530 		if (ac->ac_lport == 0)
4531 			ac->ac_lport = connp->conn_lport;
4532 		/* Always verify destination reachability. */
4533 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4534 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4535 		    B_TRUE, B_TRUE, cr);
4536 		break;
4537 
4538 	case sizeof (ipa_conn_x_t):
4539 		acx = (ipa_conn_x_t *)ucp;
4540 		/*
4541 		 * Whether or not to verify destination reachability depends
4542 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4543 		 */
4544 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4545 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4546 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4547 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4548 		break;
4549 	}
4550 	ASSERT(error != EINPROGRESS);
4551 	if (error != 0)
4552 		goto bad_addr;
4553 
4554 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4555 
4556 	/* Send it home. */
4557 	mp->b_datap->db_type = M_PCPROTO;
4558 	tbr->PRIM_type = T_BIND_ACK;
4559 	return (mp);
4560 
4561 bad_addr:
4562 	/*
4563 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4564 	 * a unix errno.
4565 	 */
4566 	if (error > 0)
4567 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4568 	else
4569 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4570 	return (mp);
4571 }
4572 
4573 /*
4574  * Here address is verified to be a valid local address.
4575  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4576  * address is also considered a valid local address.
4577  * In the case of a broadcast/multicast address, however, the
4578  * upper protocol is expected to reset the src address
4579  * to 0 if it sees a IRE_BROADCAST type returned so that
4580  * no packets are emitted with broadcast/multicast address as
4581  * source address (that violates hosts requirements RFC 1122)
4582  * The addresses valid for bind are:
4583  *	(1) - INADDR_ANY (0)
4584  *	(2) - IP address of an UP interface
4585  *	(3) - IP address of a DOWN interface
4586  *	(4) - valid local IP broadcast addresses. In this case
4587  *	the conn will only receive packets destined to
4588  *	the specified broadcast address.
4589  *	(5) - a multicast address. In this case
4590  *	the conn will only receive packets destined to
4591  *	the specified multicast address. Note: the
4592  *	application still has to issue an
4593  *	IP_ADD_MEMBERSHIP socket option.
4594  *
4595  * On error, return -1 for TBADADDR otherwise pass the
4596  * errno with TSYSERR reply.
4597  *
4598  * In all the above cases, the bound address must be valid in the current zone.
4599  * When the address is loopback, multicast or broadcast, there might be many
4600  * matching IREs so bind has to look up based on the zone.
4601  *
4602  * Note: lport is in network byte order.
4603  *
4604  */
4605 int
4606 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4607     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4608 {
4609 	int		error = 0;
4610 	ire_t		*src_ire;
4611 	zoneid_t	zoneid;
4612 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4613 	mblk_t		*mp = NULL;
4614 	boolean_t	ire_requested = B_FALSE;
4615 	boolean_t	ipsec_policy_set = B_FALSE;
4616 
4617 	if (mpp)
4618 		mp = *mpp;
4619 
4620 	if (mp != NULL) {
4621 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4622 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4623 	}
4624 
4625 	/*
4626 	 * If it was previously connected, conn_fully_bound would have
4627 	 * been set.
4628 	 */
4629 	connp->conn_fully_bound = B_FALSE;
4630 
4631 	src_ire = NULL;
4632 
4633 	zoneid = IPCL_ZONEID(connp);
4634 
4635 	if (src_addr) {
4636 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4637 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4638 		/*
4639 		 * If an address other than 0.0.0.0 is requested,
4640 		 * we verify that it is a valid address for bind
4641 		 * Note: Following code is in if-else-if form for
4642 		 * readability compared to a condition check.
4643 		 */
4644 		/* LINTED - statement has no consequence */
4645 		if (IRE_IS_LOCAL(src_ire)) {
4646 			/*
4647 			 * (2) Bind to address of local UP interface
4648 			 */
4649 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4650 			/*
4651 			 * (4) Bind to broadcast address
4652 			 * Note: permitted only from transports that
4653 			 * request IRE
4654 			 */
4655 			if (!ire_requested)
4656 				error = EADDRNOTAVAIL;
4657 		} else {
4658 			/*
4659 			 * (3) Bind to address of local DOWN interface
4660 			 * (ipif_lookup_addr() looks up all interfaces
4661 			 * but we do not get here for UP interfaces
4662 			 * - case (2) above)
4663 			 */
4664 			/* LINTED - statement has no consequent */
4665 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4666 				/* The address exists */
4667 			} else if (CLASSD(src_addr)) {
4668 				error = 0;
4669 				if (src_ire != NULL)
4670 					ire_refrele(src_ire);
4671 				/*
4672 				 * (5) bind to multicast address.
4673 				 * Fake out the IRE returned to upper
4674 				 * layer to be a broadcast IRE.
4675 				 */
4676 				src_ire = ire_ctable_lookup(
4677 				    INADDR_BROADCAST, INADDR_ANY,
4678 				    IRE_BROADCAST, NULL, zoneid, NULL,
4679 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4680 				    ipst);
4681 				if (src_ire == NULL || !ire_requested)
4682 					error = EADDRNOTAVAIL;
4683 			} else {
4684 				/*
4685 				 * Not a valid address for bind
4686 				 */
4687 				error = EADDRNOTAVAIL;
4688 			}
4689 		}
4690 		if (error) {
4691 			/* Red Alert!  Attempting to be a bogon! */
4692 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4693 			    ntohl(src_addr)));
4694 			goto bad_addr;
4695 		}
4696 	}
4697 
4698 	/*
4699 	 * Allow setting new policies. For example, disconnects come
4700 	 * down as ipa_t bind. As we would have set conn_policy_cached
4701 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4702 	 * can change after the disconnect.
4703 	 */
4704 	connp->conn_policy_cached = B_FALSE;
4705 
4706 	/*
4707 	 * If not fanout_insert this was just an address verification
4708 	 */
4709 	if (fanout_insert) {
4710 		/*
4711 		 * The addresses have been verified. Time to insert in
4712 		 * the correct fanout list.
4713 		 */
4714 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4715 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4716 		connp->conn_lport = lport;
4717 		connp->conn_fport = 0;
4718 		/*
4719 		 * Do we need to add a check to reject Multicast packets
4720 		 */
4721 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4722 	}
4723 
4724 	if (error == 0) {
4725 		if (ire_requested) {
4726 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4727 				error = -1;
4728 				/* Falls through to bad_addr */
4729 			}
4730 		} else if (ipsec_policy_set) {
4731 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4732 				error = -1;
4733 				/* Falls through to bad_addr */
4734 			}
4735 		}
4736 	}
4737 bad_addr:
4738 	if (error != 0) {
4739 		if (connp->conn_anon_port) {
4740 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4741 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4742 			    B_FALSE);
4743 		}
4744 		connp->conn_mlp_type = mlptSingle;
4745 	}
4746 	if (src_ire != NULL)
4747 		IRE_REFRELE(src_ire);
4748 	return (error);
4749 }
4750 
4751 int
4752 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4753     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4754 {
4755 	int error;
4756 	mblk_t	*mp = NULL;
4757 	boolean_t ire_requested;
4758 
4759 	if (ire_mpp)
4760 		mp = *ire_mpp;
4761 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4762 
4763 	ASSERT(!connp->conn_af_isv6);
4764 	connp->conn_pkt_isv6 = B_FALSE;
4765 	connp->conn_ulp = protocol;
4766 
4767 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4768 	    fanout_insert);
4769 	if (error == 0) {
4770 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4771 		    ire_requested);
4772 	} else if (error < 0) {
4773 		error = -TBADADDR;
4774 	}
4775 	return (error);
4776 }
4777 
4778 /*
4779  * Verify that both the source and destination addresses
4780  * are valid.  If verify_dst is false, then the destination address may be
4781  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4782  * destination reachability, while tunnels do not.
4783  * Note that we allow connect to broadcast and multicast
4784  * addresses when ire_requested is set. Thus the ULP
4785  * has to check for IRE_BROADCAST and multicast.
4786  *
4787  * Returns zero if ok.
4788  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4789  * (for use with TSYSERR reply).
4790  *
4791  * Note: lport and fport are in network byte order.
4792  */
4793 int
4794 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4795     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4796     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4797 {
4798 
4799 	ire_t		*src_ire;
4800 	ire_t		*dst_ire;
4801 	int		error = 0;
4802 	ire_t		*sire = NULL;
4803 	ire_t		*md_dst_ire = NULL;
4804 	ire_t		*lso_dst_ire = NULL;
4805 	ill_t		*ill = NULL;
4806 	zoneid_t	zoneid;
4807 	ipaddr_t	src_addr = *src_addrp;
4808 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4809 	mblk_t		*mp = NULL;
4810 	boolean_t	ire_requested = B_FALSE;
4811 	boolean_t	ipsec_policy_set = B_FALSE;
4812 	ts_label_t	*tsl = NULL;
4813 	cred_t		*effective_cred = NULL;
4814 
4815 	if (mpp)
4816 		mp = *mpp;
4817 
4818 	if (mp != NULL) {
4819 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4820 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4821 	}
4822 
4823 	src_ire = dst_ire = NULL;
4824 
4825 	/*
4826 	 * If we never got a disconnect before, clear it now.
4827 	 */
4828 	connp->conn_fully_bound = B_FALSE;
4829 
4830 	zoneid = IPCL_ZONEID(connp);
4831 
4832 	/*
4833 	 * Check whether Trusted Solaris policy allows communication with this
4834 	 * host, and pretend that the destination is unreachable if not.
4835 	 *
4836 	 * This is never a problem for TCP, since that transport is known to
4837 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4838 	 * handling.  If the remote is unreachable, it will be detected at that
4839 	 * point, so there's no reason to check it here.
4840 	 *
4841 	 * Note that for sendto (and other datagram-oriented friends), this
4842 	 * check is done as part of the data path label computation instead.
4843 	 * The check here is just to make non-TCP connect() report the right
4844 	 * error.
4845 	 */
4846 	if (is_system_labeled() && !IPCL_IS_TCP(connp)) {
4847 		if ((error = tsol_check_dest(cr, &dst_addr, IPV4_VERSION,
4848 		    connp->conn_mac_exempt, &effective_cred)) != 0) {
4849 			if (ip_debug > 2) {
4850 				pr_addr_dbg(
4851 				    "ip_bind_connected_v4:"
4852 				    " no label for dst %s\n",
4853 				    AF_INET, &dst_addr);
4854 			}
4855 			goto bad_addr;
4856 		}
4857 
4858 		/*
4859 		 * tsol_check_dest() may have created a new cred with
4860 		 * a modified security label. Use that cred if it exists
4861 		 * for ire lookups.
4862 		 */
4863 		if (effective_cred == NULL) {
4864 			tsl = crgetlabel(cr);
4865 		} else {
4866 			tsl = crgetlabel(effective_cred);
4867 		}
4868 	}
4869 
4870 	if (CLASSD(dst_addr)) {
4871 		/* Pick up an IRE_BROADCAST */
4872 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4873 		    NULL, zoneid, tsl,
4874 		    (MATCH_IRE_RECURSIVE |
4875 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4876 		    MATCH_IRE_SECATTR), ipst);
4877 	} else {
4878 		/*
4879 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4880 		 * and onlink ipif is not found set ENETUNREACH error.
4881 		 */
4882 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4883 			ipif_t *ipif;
4884 
4885 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4886 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4887 			if (ipif == NULL) {
4888 				error = ENETUNREACH;
4889 				goto bad_addr;
4890 			}
4891 			ipif_refrele(ipif);
4892 		}
4893 
4894 		if (connp->conn_nexthop_set) {
4895 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4896 			    0, 0, NULL, NULL, zoneid, tsl,
4897 			    MATCH_IRE_SECATTR, ipst);
4898 		} else {
4899 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4900 			    &sire, zoneid, tsl,
4901 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4902 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4903 			    MATCH_IRE_SECATTR), ipst);
4904 		}
4905 	}
4906 	/*
4907 	 * dst_ire can't be a broadcast when not ire_requested.
4908 	 * We also prevent ire's with src address INADDR_ANY to
4909 	 * be used, which are created temporarily for
4910 	 * sending out packets from endpoints that have
4911 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4912 	 * reachable.  If verify_dst is false, the destination needn't be
4913 	 * reachable.
4914 	 *
4915 	 * If we match on a reject or black hole, then we've got a
4916 	 * local failure.  May as well fail out the connect() attempt,
4917 	 * since it's never going to succeed.
4918 	 */
4919 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4920 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4921 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4922 		/*
4923 		 * If we're verifying destination reachability, we always want
4924 		 * to complain here.
4925 		 *
4926 		 * If we're not verifying destination reachability but the
4927 		 * destination has a route, we still want to fail on the
4928 		 * temporary address and broadcast address tests.
4929 		 */
4930 		if (verify_dst || (dst_ire != NULL)) {
4931 			if (ip_debug > 2) {
4932 				pr_addr_dbg("ip_bind_connected_v4:"
4933 				    "bad connected dst %s\n",
4934 				    AF_INET, &dst_addr);
4935 			}
4936 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4937 				error = ENETUNREACH;
4938 			else
4939 				error = EHOSTUNREACH;
4940 			goto bad_addr;
4941 		}
4942 	}
4943 
4944 	/*
4945 	 * If the app does a connect(), it means that it will most likely
4946 	 * send more than 1 packet to the destination.  It makes sense
4947 	 * to clear the temporary flag.
4948 	 */
4949 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4950 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4951 		irb_t *irb = dst_ire->ire_bucket;
4952 
4953 		rw_enter(&irb->irb_lock, RW_WRITER);
4954 		/*
4955 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4956 		 * the lock to guarantee irb_tmp_ire_cnt.
4957 		 */
4958 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4959 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4960 			irb->irb_tmp_ire_cnt--;
4961 		}
4962 		rw_exit(&irb->irb_lock);
4963 	}
4964 
4965 	/*
4966 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4967 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4968 	 * eligibility tests for passive connects are handled separately
4969 	 * through tcp_adapt_ire().  We do this before the source address
4970 	 * selection, because dst_ire may change after a call to
4971 	 * ipif_select_source().  This is a best-effort check, as the
4972 	 * packet for this connection may not actually go through
4973 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4974 	 * calling ip_newroute().  This is why we further check on the
4975 	 * IRE during LSO/Multidata packet transmission in
4976 	 * tcp_lsosend()/tcp_multisend().
4977 	 */
4978 	if (!ipsec_policy_set && dst_ire != NULL &&
4979 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4980 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4981 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4982 			lso_dst_ire = dst_ire;
4983 			IRE_REFHOLD(lso_dst_ire);
4984 		} else if (ipst->ips_ip_multidata_outbound &&
4985 		    ILL_MDT_CAPABLE(ill)) {
4986 			md_dst_ire = dst_ire;
4987 			IRE_REFHOLD(md_dst_ire);
4988 		}
4989 	}
4990 
4991 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4992 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4993 		/*
4994 		 * If the IRE belongs to a different zone, look for a matching
4995 		 * route in the forwarding table and use the source address from
4996 		 * that route.
4997 		 */
4998 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4999 		    zoneid, 0, NULL,
5000 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
5001 		    MATCH_IRE_RJ_BHOLE, ipst);
5002 		if (src_ire == NULL) {
5003 			error = EHOSTUNREACH;
5004 			goto bad_addr;
5005 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
5006 			if (!(src_ire->ire_type & IRE_HOST))
5007 				error = ENETUNREACH;
5008 			else
5009 				error = EHOSTUNREACH;
5010 			goto bad_addr;
5011 		}
5012 		if (src_addr == INADDR_ANY)
5013 			src_addr = src_ire->ire_src_addr;
5014 		ire_refrele(src_ire);
5015 		src_ire = NULL;
5016 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
5017 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
5018 			src_addr = sire->ire_src_addr;
5019 			ire_refrele(dst_ire);
5020 			dst_ire = sire;
5021 			sire = NULL;
5022 		} else {
5023 			/*
5024 			 * Pick a source address so that a proper inbound
5025 			 * load spreading would happen.
5026 			 */
5027 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
5028 			ipif_t *src_ipif = NULL;
5029 			ire_t *ipif_ire;
5030 
5031 			/*
5032 			 * Supply a local source address such that inbound
5033 			 * load spreading happens.
5034 			 *
5035 			 * Determine the best source address on this ill for
5036 			 * the destination.
5037 			 *
5038 			 * 1) For broadcast, we should return a broadcast ire
5039 			 *    found above so that upper layers know that the
5040 			 *    destination address is a broadcast address.
5041 			 *
5042 			 * 2) If the ipif is DEPRECATED, select a better
5043 			 *    source address.  Similarly, if the ipif is on
5044 			 *    the IPMP meta-interface, pick a source address
5045 			 *    at random to improve inbound load spreading.
5046 			 *
5047 			 * 3) If the outgoing interface is part of a usesrc
5048 			 *    group, then try selecting a source address from
5049 			 *    the usesrc ILL.
5050 			 */
5051 			if ((dst_ire->ire_zoneid != zoneid &&
5052 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5053 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5054 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5055 			    (IS_IPMP(ire_ill) ||
5056 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5057 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
5058 				/*
5059 				 * If the destination is reachable via a
5060 				 * given gateway, the selected source address
5061 				 * should be in the same subnet as the gateway.
5062 				 * Otherwise, the destination is not reachable.
5063 				 *
5064 				 * If there are no interfaces on the same subnet
5065 				 * as the destination, ipif_select_source gives
5066 				 * first non-deprecated interface which might be
5067 				 * on a different subnet than the gateway.
5068 				 * This is not desirable. Hence pass the dst_ire
5069 				 * source address to ipif_select_source.
5070 				 * It is sure that the destination is reachable
5071 				 * with the dst_ire source address subnet.
5072 				 * So passing dst_ire source address to
5073 				 * ipif_select_source will make sure that the
5074 				 * selected source will be on the same subnet
5075 				 * as dst_ire source address.
5076 				 */
5077 				ipaddr_t saddr =
5078 				    dst_ire->ire_ipif->ipif_src_addr;
5079 				src_ipif = ipif_select_source(ire_ill,
5080 				    saddr, zoneid);
5081 				if (src_ipif != NULL) {
5082 					if (IS_VNI(src_ipif->ipif_ill)) {
5083 						/*
5084 						 * For VNI there is no
5085 						 * interface route
5086 						 */
5087 						src_addr =
5088 						    src_ipif->ipif_src_addr;
5089 					} else {
5090 						ipif_ire =
5091 						    ipif_to_ire(src_ipif);
5092 						if (ipif_ire != NULL) {
5093 							IRE_REFRELE(dst_ire);
5094 							dst_ire = ipif_ire;
5095 						}
5096 						src_addr =
5097 						    dst_ire->ire_src_addr;
5098 					}
5099 					ipif_refrele(src_ipif);
5100 				} else {
5101 					src_addr = dst_ire->ire_src_addr;
5102 				}
5103 			} else {
5104 				src_addr = dst_ire->ire_src_addr;
5105 			}
5106 		}
5107 	}
5108 
5109 	/*
5110 	 * We do ire_route_lookup() here (and not
5111 	 * interface lookup as we assert that
5112 	 * src_addr should only come from an
5113 	 * UP interface for hard binding.
5114 	 */
5115 	ASSERT(src_ire == NULL);
5116 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5117 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5118 	/* src_ire must be a local|loopback */
5119 	if (!IRE_IS_LOCAL(src_ire)) {
5120 		if (ip_debug > 2) {
5121 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5122 			    "src %s\n", AF_INET, &src_addr);
5123 		}
5124 		error = EADDRNOTAVAIL;
5125 		goto bad_addr;
5126 	}
5127 
5128 	/*
5129 	 * If the source address is a loopback address, the
5130 	 * destination had best be local or multicast.
5131 	 * The transports that can't handle multicast will reject
5132 	 * those addresses.
5133 	 */
5134 	if (src_ire->ire_type == IRE_LOOPBACK &&
5135 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5136 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5137 		error = -1;
5138 		goto bad_addr;
5139 	}
5140 
5141 	/*
5142 	 * Allow setting new policies. For example, disconnects come
5143 	 * down as ipa_t bind. As we would have set conn_policy_cached
5144 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5145 	 * can change after the disconnect.
5146 	 */
5147 	connp->conn_policy_cached = B_FALSE;
5148 
5149 	/*
5150 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5151 	 * can handle their passed-in conn's.
5152 	 */
5153 
5154 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5155 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5156 	connp->conn_lport = lport;
5157 	connp->conn_fport = fport;
5158 	*src_addrp = src_addr;
5159 
5160 	ASSERT(!(ipsec_policy_set && ire_requested));
5161 	if (ire_requested) {
5162 		iulp_t *ulp_info = NULL;
5163 
5164 		/*
5165 		 * Note that sire will not be NULL if this is an off-link
5166 		 * connection and there is not cache for that dest yet.
5167 		 *
5168 		 * XXX Because of an existing bug, if there are multiple
5169 		 * default routes, the IRE returned now may not be the actual
5170 		 * default route used (default routes are chosen in a
5171 		 * round robin fashion).  So if the metrics for different
5172 		 * default routes are different, we may return the wrong
5173 		 * metrics.  This will not be a problem if the existing
5174 		 * bug is fixed.
5175 		 */
5176 		if (sire != NULL) {
5177 			ulp_info = &(sire->ire_uinfo);
5178 		}
5179 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5180 			error = -1;
5181 			goto bad_addr;
5182 		}
5183 		mp = *mpp;
5184 	} else if (ipsec_policy_set) {
5185 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5186 			error = -1;
5187 			goto bad_addr;
5188 		}
5189 	}
5190 
5191 	/*
5192 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5193 	 * we'll cache that.  If we don't, we'll inherit global policy.
5194 	 *
5195 	 * We can't insert until the conn reflects the policy. Note that
5196 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5197 	 * connections where we don't have a policy. This is to prevent
5198 	 * global policy lookups in the inbound path.
5199 	 *
5200 	 * If we insert before we set conn_policy_cached,
5201 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5202 	 * because global policy cound be non-empty. We normally call
5203 	 * ipsec_check_policy() for conn_policy_cached connections only if
5204 	 * ipc_in_enforce_policy is set. But in this case,
5205 	 * conn_policy_cached can get set anytime since we made the
5206 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5207 	 * called, which will make the above assumption false.  Thus, we
5208 	 * need to insert after we set conn_policy_cached.
5209 	 */
5210 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5211 		goto bad_addr;
5212 
5213 	if (fanout_insert) {
5214 		/*
5215 		 * The addresses have been verified. Time to insert in
5216 		 * the correct fanout list.
5217 		 */
5218 		error = ipcl_conn_insert(connp, protocol, src_addr,
5219 		    dst_addr, connp->conn_ports);
5220 	}
5221 
5222 	if (error == 0) {
5223 		connp->conn_fully_bound = B_TRUE;
5224 		/*
5225 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5226 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5227 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5228 		 * ip_xxinfo_return(), which performs further checks
5229 		 * against them and upon success, returns the LSO/MDT info
5230 		 * mblk which we will attach to the bind acknowledgment.
5231 		 */
5232 		if (lso_dst_ire != NULL) {
5233 			mblk_t *lsoinfo_mp;
5234 
5235 			ASSERT(ill->ill_lso_capab != NULL);
5236 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5237 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5238 				if (mp == NULL) {
5239 					*mpp = lsoinfo_mp;
5240 				} else {
5241 					linkb(mp, lsoinfo_mp);
5242 				}
5243 			}
5244 		} else if (md_dst_ire != NULL) {
5245 			mblk_t *mdinfo_mp;
5246 
5247 			ASSERT(ill->ill_mdt_capab != NULL);
5248 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5249 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5250 				if (mp == NULL) {
5251 					*mpp = mdinfo_mp;
5252 				} else {
5253 					linkb(mp, mdinfo_mp);
5254 				}
5255 			}
5256 		}
5257 	}
5258 bad_addr:
5259 	if (ipsec_policy_set) {
5260 		ASSERT(mp != NULL);
5261 		freeb(mp);
5262 		/*
5263 		 * As of now assume that nothing else accompanies
5264 		 * IPSEC_POLICY_SET.
5265 		 */
5266 		*mpp = NULL;
5267 	}
5268 	if (src_ire != NULL)
5269 		IRE_REFRELE(src_ire);
5270 	if (dst_ire != NULL)
5271 		IRE_REFRELE(dst_ire);
5272 	if (sire != NULL)
5273 		IRE_REFRELE(sire);
5274 	if (md_dst_ire != NULL)
5275 		IRE_REFRELE(md_dst_ire);
5276 	if (lso_dst_ire != NULL)
5277 		IRE_REFRELE(lso_dst_ire);
5278 	if (effective_cred != NULL)
5279 		crfree(effective_cred);
5280 	return (error);
5281 }
5282 
5283 int
5284 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5285     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5286     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5287 {
5288 	int error;
5289 	mblk_t	*mp = NULL;
5290 	boolean_t ire_requested;
5291 
5292 	if (ire_mpp)
5293 		mp = *ire_mpp;
5294 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5295 
5296 	ASSERT(!connp->conn_af_isv6);
5297 	connp->conn_pkt_isv6 = B_FALSE;
5298 	connp->conn_ulp = protocol;
5299 
5300 	/* For raw socket, the local port is not set. */
5301 	if (lport == 0)
5302 		lport = connp->conn_lport;
5303 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5304 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5305 	if (error == 0) {
5306 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5307 		    ire_requested);
5308 	} else if (error < 0) {
5309 		error = -TBADADDR;
5310 	}
5311 	return (error);
5312 }
5313 
5314 /*
5315  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5316  * Prefers dst_ire over src_ire.
5317  */
5318 static boolean_t
5319 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5320 {
5321 	mblk_t	*mp = *mpp;
5322 	ire_t	*ret_ire;
5323 
5324 	ASSERT(mp != NULL);
5325 
5326 	if (ire != NULL) {
5327 		/*
5328 		 * mp initialized above to IRE_DB_REQ_TYPE
5329 		 * appended mblk. Its <upper protocol>'s
5330 		 * job to make sure there is room.
5331 		 */
5332 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5333 			return (B_FALSE);
5334 
5335 		mp->b_datap->db_type = IRE_DB_TYPE;
5336 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5337 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5338 		ret_ire = (ire_t *)mp->b_rptr;
5339 		/*
5340 		 * Pass the latest setting of the ip_path_mtu_discovery and
5341 		 * copy the ulp info if any.
5342 		 */
5343 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5344 		    IPH_DF : 0;
5345 		if (ulp_info != NULL) {
5346 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5347 			    sizeof (iulp_t));
5348 		}
5349 		ret_ire->ire_mp = mp;
5350 	} else {
5351 		/*
5352 		 * No IRE was found. Remove IRE mblk.
5353 		 */
5354 		*mpp = mp->b_cont;
5355 		freeb(mp);
5356 	}
5357 	return (B_TRUE);
5358 }
5359 
5360 /*
5361  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5362  * the final piece where we don't.  Return a pointer to the first mblk in the
5363  * result, and update the pointer to the next mblk to chew on.  If anything
5364  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5365  * NULL pointer.
5366  */
5367 mblk_t *
5368 ip_carve_mp(mblk_t **mpp, ssize_t len)
5369 {
5370 	mblk_t	*mp0;
5371 	mblk_t	*mp1;
5372 	mblk_t	*mp2;
5373 
5374 	if (!len || !mpp || !(mp0 = *mpp))
5375 		return (NULL);
5376 	/* If we aren't going to consume the first mblk, we need a dup. */
5377 	if (mp0->b_wptr - mp0->b_rptr > len) {
5378 		mp1 = dupb(mp0);
5379 		if (mp1) {
5380 			/* Partition the data between the two mblks. */
5381 			mp1->b_wptr = mp1->b_rptr + len;
5382 			mp0->b_rptr = mp1->b_wptr;
5383 			/*
5384 			 * after adjustments if mblk not consumed is now
5385 			 * unaligned, try to align it. If this fails free
5386 			 * all messages and let upper layer recover.
5387 			 */
5388 			if (!OK_32PTR(mp0->b_rptr)) {
5389 				if (!pullupmsg(mp0, -1)) {
5390 					freemsg(mp0);
5391 					freemsg(mp1);
5392 					*mpp = NULL;
5393 					return (NULL);
5394 				}
5395 			}
5396 		}
5397 		return (mp1);
5398 	}
5399 	/* Eat through as many mblks as we need to get len bytes. */
5400 	len -= mp0->b_wptr - mp0->b_rptr;
5401 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5402 		if (mp2->b_wptr - mp2->b_rptr > len) {
5403 			/*
5404 			 * We won't consume the entire last mblk.  Like
5405 			 * above, dup and partition it.
5406 			 */
5407 			mp1->b_cont = dupb(mp2);
5408 			mp1 = mp1->b_cont;
5409 			if (!mp1) {
5410 				/*
5411 				 * Trouble.  Rather than go to a lot of
5412 				 * trouble to clean up, we free the messages.
5413 				 * This won't be any worse than losing it on
5414 				 * the wire.
5415 				 */
5416 				freemsg(mp0);
5417 				freemsg(mp2);
5418 				*mpp = NULL;
5419 				return (NULL);
5420 			}
5421 			mp1->b_wptr = mp1->b_rptr + len;
5422 			mp2->b_rptr = mp1->b_wptr;
5423 			/*
5424 			 * after adjustments if mblk not consumed is now
5425 			 * unaligned, try to align it. If this fails free
5426 			 * all messages and let upper layer recover.
5427 			 */
5428 			if (!OK_32PTR(mp2->b_rptr)) {
5429 				if (!pullupmsg(mp2, -1)) {
5430 					freemsg(mp0);
5431 					freemsg(mp2);
5432 					*mpp = NULL;
5433 					return (NULL);
5434 				}
5435 			}
5436 			*mpp = mp2;
5437 			return (mp0);
5438 		}
5439 		/* Decrement len by the amount we just got. */
5440 		len -= mp2->b_wptr - mp2->b_rptr;
5441 	}
5442 	/*
5443 	 * len should be reduced to zero now.  If not our caller has
5444 	 * screwed up.
5445 	 */
5446 	if (len) {
5447 		/* Shouldn't happen! */
5448 		freemsg(mp0);
5449 		*mpp = NULL;
5450 		return (NULL);
5451 	}
5452 	/*
5453 	 * We consumed up to exactly the end of an mblk.  Detach the part
5454 	 * we are returning from the rest of the chain.
5455 	 */
5456 	mp1->b_cont = NULL;
5457 	*mpp = mp2;
5458 	return (mp0);
5459 }
5460 
5461 /* The ill stream is being unplumbed. Called from ip_close */
5462 int
5463 ip_modclose(ill_t *ill)
5464 {
5465 	boolean_t success;
5466 	ipsq_t	*ipsq;
5467 	ipif_t	*ipif;
5468 	queue_t	*q = ill->ill_rq;
5469 	ip_stack_t	*ipst = ill->ill_ipst;
5470 	int	i;
5471 
5472 	/*
5473 	 * The punlink prior to this may have initiated a capability
5474 	 * negotiation. But ipsq_enter will block until that finishes or
5475 	 * times out.
5476 	 */
5477 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5478 
5479 	/*
5480 	 * Open/close/push/pop is guaranteed to be single threaded
5481 	 * per stream by STREAMS. FS guarantees that all references
5482 	 * from top are gone before close is called. So there can't
5483 	 * be another close thread that has set CONDEMNED on this ill.
5484 	 * and cause ipsq_enter to return failure.
5485 	 */
5486 	ASSERT(success);
5487 	ipsq = ill->ill_phyint->phyint_ipsq;
5488 
5489 	/*
5490 	 * Mark it condemned. No new reference will be made to this ill.
5491 	 * Lookup functions will return an error. Threads that try to
5492 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5493 	 * that the refcnt will drop down to zero.
5494 	 */
5495 	mutex_enter(&ill->ill_lock);
5496 	ill->ill_state_flags |= ILL_CONDEMNED;
5497 	for (ipif = ill->ill_ipif; ipif != NULL;
5498 	    ipif = ipif->ipif_next) {
5499 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5500 	}
5501 	/*
5502 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5503 	 * returns  error if ILL_CONDEMNED is set
5504 	 */
5505 	cv_broadcast(&ill->ill_cv);
5506 	mutex_exit(&ill->ill_lock);
5507 
5508 	/*
5509 	 * Send all the deferred DLPI messages downstream which came in
5510 	 * during the small window right before ipsq_enter(). We do this
5511 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5512 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5513 	 */
5514 	ill_dlpi_send_deferred(ill);
5515 
5516 	/*
5517 	 * Shut down fragmentation reassembly.
5518 	 * ill_frag_timer won't start a timer again.
5519 	 * Now cancel any existing timer
5520 	 */
5521 	(void) untimeout(ill->ill_frag_timer_id);
5522 	(void) ill_frag_timeout(ill, 0);
5523 
5524 	/*
5525 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5526 	 * this ill. Then wait for the refcnts to drop to zero.
5527 	 * ill_is_freeable checks whether the ill is really quiescent.
5528 	 * Then make sure that threads that are waiting to enter the
5529 	 * ipsq have seen the error returned by ipsq_enter and have
5530 	 * gone away. Then we call ill_delete_tail which does the
5531 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5532 	 */
5533 	ill_delete(ill);
5534 	mutex_enter(&ill->ill_lock);
5535 	while (!ill_is_freeable(ill))
5536 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5537 	while (ill->ill_waiters)
5538 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5539 
5540 	mutex_exit(&ill->ill_lock);
5541 
5542 	/*
5543 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5544 	 * it held until the end of the function since the cleanup
5545 	 * below needs to be able to use the ip_stack_t.
5546 	 */
5547 	netstack_hold(ipst->ips_netstack);
5548 
5549 	/* qprocsoff is done via ill_delete_tail */
5550 	ill_delete_tail(ill);
5551 	ASSERT(ill->ill_ipst == NULL);
5552 
5553 	/*
5554 	 * Walk through all upper (conn) streams and qenable
5555 	 * those that have queued data.
5556 	 * close synchronization needs this to
5557 	 * be done to ensure that all upper layers blocked
5558 	 * due to flow control to the closing device
5559 	 * get unblocked.
5560 	 */
5561 	ip1dbg(("ip_wsrv: walking\n"));
5562 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5563 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5564 	}
5565 
5566 	mutex_enter(&ipst->ips_ip_mi_lock);
5567 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5568 	mutex_exit(&ipst->ips_ip_mi_lock);
5569 
5570 	/*
5571 	 * credp could be null if the open didn't succeed and ip_modopen
5572 	 * itself calls ip_close.
5573 	 */
5574 	if (ill->ill_credp != NULL)
5575 		crfree(ill->ill_credp);
5576 
5577 	/*
5578 	 * Now we are done with the module close pieces that
5579 	 * need the netstack_t.
5580 	 */
5581 	netstack_rele(ipst->ips_netstack);
5582 
5583 	mi_close_free((IDP)ill);
5584 	q->q_ptr = WR(q)->q_ptr = NULL;
5585 
5586 	ipsq_exit(ipsq);
5587 
5588 	return (0);
5589 }
5590 
5591 /*
5592  * This is called as part of close() for IP, UDP, ICMP, and RTS
5593  * in order to quiesce the conn.
5594  */
5595 void
5596 ip_quiesce_conn(conn_t *connp)
5597 {
5598 	boolean_t	drain_cleanup_reqd = B_FALSE;
5599 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5600 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5601 	ip_stack_t	*ipst;
5602 
5603 	ASSERT(!IPCL_IS_TCP(connp));
5604 	ipst = connp->conn_netstack->netstack_ip;
5605 
5606 	/*
5607 	 * Mark the conn as closing, and this conn must not be
5608 	 * inserted in future into any list. Eg. conn_drain_insert(),
5609 	 * won't insert this conn into the conn_drain_list.
5610 	 * Similarly ill_pending_mp_add() will not add any mp to
5611 	 * the pending mp list, after this conn has started closing.
5612 	 *
5613 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5614 	 * cannot get set henceforth.
5615 	 */
5616 	mutex_enter(&connp->conn_lock);
5617 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5618 	connp->conn_state_flags |= CONN_CLOSING;
5619 	if (connp->conn_idl != NULL)
5620 		drain_cleanup_reqd = B_TRUE;
5621 	if (connp->conn_oper_pending_ill != NULL)
5622 		conn_ioctl_cleanup_reqd = B_TRUE;
5623 	if (connp->conn_dhcpinit_ill != NULL) {
5624 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5625 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5626 		connp->conn_dhcpinit_ill = NULL;
5627 	}
5628 	if (connp->conn_ilg_inuse != 0)
5629 		ilg_cleanup_reqd = B_TRUE;
5630 	mutex_exit(&connp->conn_lock);
5631 
5632 	if (conn_ioctl_cleanup_reqd)
5633 		conn_ioctl_cleanup(connp);
5634 
5635 	if (is_system_labeled() && connp->conn_anon_port) {
5636 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5637 		    connp->conn_mlp_type, connp->conn_ulp,
5638 		    ntohs(connp->conn_lport), B_FALSE);
5639 		connp->conn_anon_port = 0;
5640 	}
5641 	connp->conn_mlp_type = mlptSingle;
5642 
5643 	/*
5644 	 * Remove this conn from any fanout list it is on.
5645 	 * and then wait for any threads currently operating
5646 	 * on this endpoint to finish
5647 	 */
5648 	ipcl_hash_remove(connp);
5649 
5650 	/*
5651 	 * Remove this conn from the drain list, and do
5652 	 * any other cleanup that may be required.
5653 	 * (Only non-tcp streams may have a non-null conn_idl.
5654 	 * TCP streams are never flow controlled, and
5655 	 * conn_idl will be null)
5656 	 */
5657 	if (drain_cleanup_reqd)
5658 		conn_drain_tail(connp, B_TRUE);
5659 
5660 	if (connp == ipst->ips_ip_g_mrouter)
5661 		(void) ip_mrouter_done(NULL, ipst);
5662 
5663 	if (ilg_cleanup_reqd)
5664 		ilg_delete_all(connp);
5665 
5666 	conn_delete_ire(connp, NULL);
5667 
5668 	/*
5669 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5670 	 * callers from write side can't be there now because close
5671 	 * is in progress. The only other caller is ipcl_walk
5672 	 * which checks for the condemned flag.
5673 	 */
5674 	mutex_enter(&connp->conn_lock);
5675 	connp->conn_state_flags |= CONN_CONDEMNED;
5676 	while (connp->conn_ref != 1)
5677 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5678 	connp->conn_state_flags |= CONN_QUIESCED;
5679 	mutex_exit(&connp->conn_lock);
5680 }
5681 
5682 /* ARGSUSED */
5683 int
5684 ip_close(queue_t *q, int flags)
5685 {
5686 	conn_t		*connp;
5687 
5688 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5689 
5690 	/*
5691 	 * Call the appropriate delete routine depending on whether this is
5692 	 * a module or device.
5693 	 */
5694 	if (WR(q)->q_next != NULL) {
5695 		/* This is a module close */
5696 		return (ip_modclose((ill_t *)q->q_ptr));
5697 	}
5698 
5699 	connp = q->q_ptr;
5700 	ip_quiesce_conn(connp);
5701 
5702 	qprocsoff(q);
5703 
5704 	/*
5705 	 * Now we are truly single threaded on this stream, and can
5706 	 * delete the things hanging off the connp, and finally the connp.
5707 	 * We removed this connp from the fanout list, it cannot be
5708 	 * accessed thru the fanouts, and we already waited for the
5709 	 * conn_ref to drop to 0. We are already in close, so
5710 	 * there cannot be any other thread from the top. qprocsoff
5711 	 * has completed, and service has completed or won't run in
5712 	 * future.
5713 	 */
5714 	ASSERT(connp->conn_ref == 1);
5715 
5716 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5717 
5718 	connp->conn_ref--;
5719 	ipcl_conn_destroy(connp);
5720 
5721 	q->q_ptr = WR(q)->q_ptr = NULL;
5722 	return (0);
5723 }
5724 
5725 /*
5726  * Wapper around putnext() so that ip_rts_request can merely use
5727  * conn_recv.
5728  */
5729 /*ARGSUSED2*/
5730 static void
5731 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5732 {
5733 	conn_t *connp = (conn_t *)arg1;
5734 
5735 	putnext(connp->conn_rq, mp);
5736 }
5737 
5738 /*
5739  * Called when the module is about to be unloaded
5740  */
5741 void
5742 ip_ddi_destroy(void)
5743 {
5744 	tnet_fini();
5745 
5746 	icmp_ddi_g_destroy();
5747 	rts_ddi_g_destroy();
5748 	udp_ddi_g_destroy();
5749 	sctp_ddi_g_destroy();
5750 	tcp_ddi_g_destroy();
5751 	ipsec_policy_g_destroy();
5752 	ipcl_g_destroy();
5753 	ip_net_g_destroy();
5754 	ip_ire_g_fini();
5755 	inet_minor_destroy(ip_minor_arena_sa);
5756 #if defined(_LP64)
5757 	inet_minor_destroy(ip_minor_arena_la);
5758 #endif
5759 
5760 #ifdef DEBUG
5761 	list_destroy(&ip_thread_list);
5762 	rw_destroy(&ip_thread_rwlock);
5763 	tsd_destroy(&ip_thread_data);
5764 #endif
5765 
5766 	netstack_unregister(NS_IP);
5767 }
5768 
5769 /*
5770  * First step in cleanup.
5771  */
5772 /* ARGSUSED */
5773 static void
5774 ip_stack_shutdown(netstackid_t stackid, void *arg)
5775 {
5776 	ip_stack_t *ipst = (ip_stack_t *)arg;
5777 
5778 #ifdef NS_DEBUG
5779 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5780 #endif
5781 
5782 	/* Get rid of loopback interfaces and their IREs */
5783 	ip_loopback_cleanup(ipst);
5784 
5785 	/*
5786 	 * The *_hook_shutdown()s start the process of notifying any
5787 	 * consumers that things are going away.... nothing is destroyed.
5788 	 */
5789 	ipv4_hook_shutdown(ipst);
5790 	ipv6_hook_shutdown(ipst);
5791 
5792 	mutex_enter(&ipst->ips_capab_taskq_lock);
5793 	ipst->ips_capab_taskq_quit = B_TRUE;
5794 	cv_signal(&ipst->ips_capab_taskq_cv);
5795 	mutex_exit(&ipst->ips_capab_taskq_lock);
5796 
5797 	mutex_enter(&ipst->ips_mrt_lock);
5798 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5799 	cv_signal(&ipst->ips_mrt_cv);
5800 	mutex_exit(&ipst->ips_mrt_lock);
5801 }
5802 
5803 /*
5804  * Free the IP stack instance.
5805  */
5806 static void
5807 ip_stack_fini(netstackid_t stackid, void *arg)
5808 {
5809 	ip_stack_t *ipst = (ip_stack_t *)arg;
5810 	int ret;
5811 
5812 #ifdef NS_DEBUG
5813 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5814 #endif
5815 	/*
5816 	 * At this point, all of the notifications that the events and
5817 	 * protocols are going away have been run, meaning that we can
5818 	 * now set about starting to clean things up.
5819 	 */
5820 	ipv4_hook_destroy(ipst);
5821 	ipv6_hook_destroy(ipst);
5822 	ip_net_destroy(ipst);
5823 
5824 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5825 	cv_destroy(&ipst->ips_capab_taskq_cv);
5826 
5827 	mutex_enter(&ipst->ips_mrt_lock);
5828 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5829 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5830 	mutex_destroy(&ipst->ips_mrt_lock);
5831 	cv_destroy(&ipst->ips_mrt_cv);
5832 	cv_destroy(&ipst->ips_mrt_done_cv);
5833 
5834 	ipmp_destroy(ipst);
5835 	rw_destroy(&ipst->ips_srcid_lock);
5836 
5837 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5838 	ipst->ips_ip_mibkp = NULL;
5839 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5840 	ipst->ips_icmp_mibkp = NULL;
5841 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5842 	ipst->ips_ip_kstat = NULL;
5843 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5844 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5845 	ipst->ips_ip6_kstat = NULL;
5846 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5847 
5848 	nd_free(&ipst->ips_ip_g_nd);
5849 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5850 	ipst->ips_param_arr = NULL;
5851 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5852 	ipst->ips_ndp_arr = NULL;
5853 
5854 	ip_mrouter_stack_destroy(ipst);
5855 
5856 	mutex_destroy(&ipst->ips_ip_mi_lock);
5857 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5858 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5859 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5860 
5861 	ret = untimeout(ipst->ips_igmp_timeout_id);
5862 	if (ret == -1) {
5863 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5864 	} else {
5865 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5866 		ipst->ips_igmp_timeout_id = 0;
5867 	}
5868 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5869 	if (ret == -1) {
5870 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5871 	} else {
5872 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5873 		ipst->ips_igmp_slowtimeout_id = 0;
5874 	}
5875 	ret = untimeout(ipst->ips_mld_timeout_id);
5876 	if (ret == -1) {
5877 		ASSERT(ipst->ips_mld_timeout_id == 0);
5878 	} else {
5879 		ASSERT(ipst->ips_mld_timeout_id != 0);
5880 		ipst->ips_mld_timeout_id = 0;
5881 	}
5882 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5883 	if (ret == -1) {
5884 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5885 	} else {
5886 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5887 		ipst->ips_mld_slowtimeout_id = 0;
5888 	}
5889 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5890 	if (ret == -1) {
5891 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5892 	} else {
5893 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5894 		ipst->ips_ip_ire_expire_id = 0;
5895 	}
5896 
5897 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5898 	mutex_destroy(&ipst->ips_mld_timer_lock);
5899 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5900 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5901 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5902 	rw_destroy(&ipst->ips_ill_g_lock);
5903 
5904 	ipobs_fini(ipst);
5905 	ip_ire_fini(ipst);
5906 	ip6_asp_free(ipst);
5907 	conn_drain_fini(ipst);
5908 	ipcl_destroy(ipst);
5909 
5910 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5911 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5912 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5913 	ipst->ips_ndp4 = NULL;
5914 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5915 	ipst->ips_ndp6 = NULL;
5916 
5917 	if (ipst->ips_loopback_ksp != NULL) {
5918 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5919 		ipst->ips_loopback_ksp = NULL;
5920 	}
5921 
5922 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5923 	ipst->ips_phyint_g_list = NULL;
5924 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5925 	ipst->ips_ill_g_heads = NULL;
5926 
5927 	ldi_ident_release(ipst->ips_ldi_ident);
5928 	kmem_free(ipst, sizeof (*ipst));
5929 }
5930 
5931 /*
5932  * This function is called from the TSD destructor, and is used to debug
5933  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5934  * details.
5935  */
5936 static void
5937 ip_thread_exit(void *phash)
5938 {
5939 	th_hash_t *thh = phash;
5940 
5941 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5942 	list_remove(&ip_thread_list, thh);
5943 	rw_exit(&ip_thread_rwlock);
5944 	mod_hash_destroy_hash(thh->thh_hash);
5945 	kmem_free(thh, sizeof (*thh));
5946 }
5947 
5948 /*
5949  * Called when the IP kernel module is loaded into the kernel
5950  */
5951 void
5952 ip_ddi_init(void)
5953 {
5954 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5955 
5956 	/*
5957 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5958 	 * initial devices: ip, ip6, tcp, tcp6.
5959 	 */
5960 	/*
5961 	 * If this is a 64-bit kernel, then create two separate arenas -
5962 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5963 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5964 	 */
5965 	ip_minor_arena_la = NULL;
5966 	ip_minor_arena_sa = NULL;
5967 #if defined(_LP64)
5968 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5969 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5970 		cmn_err(CE_PANIC,
5971 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5972 	}
5973 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5974 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5975 		cmn_err(CE_PANIC,
5976 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5977 	}
5978 #else
5979 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5980 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5981 		cmn_err(CE_PANIC,
5982 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5983 	}
5984 #endif
5985 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5986 
5987 	ipcl_g_init();
5988 	ip_ire_g_init();
5989 	ip_net_g_init();
5990 
5991 #ifdef DEBUG
5992 	tsd_create(&ip_thread_data, ip_thread_exit);
5993 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5994 	list_create(&ip_thread_list, sizeof (th_hash_t),
5995 	    offsetof(th_hash_t, thh_link));
5996 #endif
5997 
5998 	/*
5999 	 * We want to be informed each time a stack is created or
6000 	 * destroyed in the kernel, so we can maintain the
6001 	 * set of udp_stack_t's.
6002 	 */
6003 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
6004 	    ip_stack_fini);
6005 
6006 	ipsec_policy_g_init();
6007 	tcp_ddi_g_init();
6008 	sctp_ddi_g_init();
6009 
6010 	tnet_init();
6011 
6012 	udp_ddi_g_init();
6013 	rts_ddi_g_init();
6014 	icmp_ddi_g_init();
6015 }
6016 
6017 /*
6018  * Initialize the IP stack instance.
6019  */
6020 static void *
6021 ip_stack_init(netstackid_t stackid, netstack_t *ns)
6022 {
6023 	ip_stack_t	*ipst;
6024 	ipparam_t	*pa;
6025 	ipndp_t		*na;
6026 	major_t		major;
6027 
6028 #ifdef NS_DEBUG
6029 	printf("ip_stack_init(stack %d)\n", stackid);
6030 #endif
6031 
6032 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6033 	ipst->ips_netstack = ns;
6034 
6035 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6036 	    KM_SLEEP);
6037 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6038 	    KM_SLEEP);
6039 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6040 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6041 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6042 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6043 
6044 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6045 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6046 	ipst->ips_igmp_deferred_next = INFINITY;
6047 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6048 	ipst->ips_mld_deferred_next = INFINITY;
6049 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6050 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6051 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6052 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6053 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6054 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6055 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6056 
6057 	ipcl_init(ipst);
6058 	ip_ire_init(ipst);
6059 	ip6_asp_init(ipst);
6060 	ipif_init(ipst);
6061 	conn_drain_init(ipst);
6062 	ip_mrouter_stack_init(ipst);
6063 
6064 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6065 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6066 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
6067 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
6068 
6069 	ipst->ips_ip_multirt_log_interval = 1000;
6070 
6071 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6072 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6073 	ipst->ips_ill_index = 1;
6074 
6075 	ipst->ips_saved_ip_g_forward = -1;
6076 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6077 
6078 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6079 	ipst->ips_param_arr = pa;
6080 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6081 
6082 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6083 	ipst->ips_ndp_arr = na;
6084 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6085 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6086 	    (caddr_t)&ipst->ips_ip_g_forward;
6087 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6088 	    (caddr_t)&ipst->ips_ipv6_forward;
6089 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6090 	    "ip_cgtp_filter") == 0);
6091 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6092 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6093 
6094 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6095 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6096 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6097 
6098 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6099 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6100 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6101 	ipst->ips_ip6_kstat =
6102 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6103 
6104 	ipst->ips_ip_src_id = 1;
6105 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6106 
6107 	ipobs_init(ipst);
6108 	ip_net_init(ipst, ns);
6109 	ipv4_hook_init(ipst);
6110 	ipv6_hook_init(ipst);
6111 	ipmp_init(ipst);
6112 
6113 	/*
6114 	 * Create the taskq dispatcher thread and initialize related stuff.
6115 	 */
6116 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6117 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6118 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6119 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6120 
6121 	/*
6122 	 * Create the mcast_restart_timers_thread() worker thread.
6123 	 */
6124 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6125 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6126 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6127 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6128 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6129 
6130 	major = mod_name_to_major(INET_NAME);
6131 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6132 	return (ipst);
6133 }
6134 
6135 /*
6136  * Allocate and initialize a DLPI template of the specified length.  (May be
6137  * called as writer.)
6138  */
6139 mblk_t *
6140 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6141 {
6142 	mblk_t	*mp;
6143 
6144 	mp = allocb(len, BPRI_MED);
6145 	if (!mp)
6146 		return (NULL);
6147 
6148 	/*
6149 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6150 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6151 	 * that other DLPI are M_PROTO.
6152 	 */
6153 	if (prim == DL_INFO_REQ) {
6154 		mp->b_datap->db_type = M_PCPROTO;
6155 	} else {
6156 		mp->b_datap->db_type = M_PROTO;
6157 	}
6158 
6159 	mp->b_wptr = mp->b_rptr + len;
6160 	bzero(mp->b_rptr, len);
6161 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6162 	return (mp);
6163 }
6164 
6165 /*
6166  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6167  */
6168 mblk_t *
6169 ip_dlnotify_alloc(uint_t notification, uint_t data)
6170 {
6171 	dl_notify_ind_t	*notifyp;
6172 	mblk_t		*mp;
6173 
6174 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6175 		return (NULL);
6176 
6177 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6178 	notifyp->dl_notification = notification;
6179 	notifyp->dl_data = data;
6180 	return (mp);
6181 }
6182 
6183 /*
6184  * Debug formatting routine.  Returns a character string representation of the
6185  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6186  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6187  *
6188  * Once the ndd table-printing interfaces are removed, this can be changed to
6189  * standard dotted-decimal form.
6190  */
6191 char *
6192 ip_dot_addr(ipaddr_t addr, char *buf)
6193 {
6194 	uint8_t *ap = (uint8_t *)&addr;
6195 
6196 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6197 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6198 	return (buf);
6199 }
6200 
6201 /*
6202  * Write the given MAC address as a printable string in the usual colon-
6203  * separated format.
6204  */
6205 const char *
6206 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6207 {
6208 	char *bp;
6209 
6210 	if (alen == 0 || buflen < 4)
6211 		return ("?");
6212 	bp = buf;
6213 	for (;;) {
6214 		/*
6215 		 * If there are more MAC address bytes available, but we won't
6216 		 * have any room to print them, then add "..." to the string
6217 		 * instead.  See below for the 'magic number' explanation.
6218 		 */
6219 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6220 			(void) strcpy(bp, "...");
6221 			break;
6222 		}
6223 		(void) sprintf(bp, "%02x", *addr++);
6224 		bp += 2;
6225 		if (--alen == 0)
6226 			break;
6227 		*bp++ = ':';
6228 		buflen -= 3;
6229 		/*
6230 		 * At this point, based on the first 'if' statement above,
6231 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6232 		 * buflen >= 4.  The first case leaves room for the final "xx"
6233 		 * number and trailing NUL byte.  The second leaves room for at
6234 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6235 		 * that statement.
6236 		 */
6237 	}
6238 	return (buf);
6239 }
6240 
6241 /*
6242  * Send an ICMP error after patching up the packet appropriately.  Returns
6243  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6244  */
6245 static boolean_t
6246 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6247     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6248     zoneid_t zoneid, ip_stack_t *ipst)
6249 {
6250 	ipha_t *ipha;
6251 	mblk_t *first_mp;
6252 	boolean_t secure;
6253 	unsigned char db_type;
6254 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6255 
6256 	first_mp = mp;
6257 	if (mctl_present) {
6258 		mp = mp->b_cont;
6259 		secure = ipsec_in_is_secure(first_mp);
6260 		ASSERT(mp != NULL);
6261 	} else {
6262 		/*
6263 		 * If this is an ICMP error being reported - which goes
6264 		 * up as M_CTLs, we need to convert them to M_DATA till
6265 		 * we finish checking with global policy because
6266 		 * ipsec_check_global_policy() assumes M_DATA as clear
6267 		 * and M_CTL as secure.
6268 		 */
6269 		db_type = DB_TYPE(mp);
6270 		DB_TYPE(mp) = M_DATA;
6271 		secure = B_FALSE;
6272 	}
6273 	/*
6274 	 * We are generating an icmp error for some inbound packet.
6275 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6276 	 * Before we generate an error, check with global policy
6277 	 * to see whether this is allowed to enter the system. As
6278 	 * there is no "conn", we are checking with global policy.
6279 	 */
6280 	ipha = (ipha_t *)mp->b_rptr;
6281 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6282 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6283 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6284 		if (first_mp == NULL)
6285 			return (B_FALSE);
6286 	}
6287 
6288 	if (!mctl_present)
6289 		DB_TYPE(mp) = db_type;
6290 
6291 	if (flags & IP_FF_SEND_ICMP) {
6292 		if (flags & IP_FF_HDR_COMPLETE) {
6293 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6294 				freemsg(first_mp);
6295 				return (B_TRUE);
6296 			}
6297 		}
6298 		if (flags & IP_FF_CKSUM) {
6299 			/*
6300 			 * Have to correct checksum since
6301 			 * the packet might have been
6302 			 * fragmented and the reassembly code in ip_rput
6303 			 * does not restore the IP checksum.
6304 			 */
6305 			ipha->ipha_hdr_checksum = 0;
6306 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6307 		}
6308 		switch (icmp_type) {
6309 		case ICMP_DEST_UNREACHABLE:
6310 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6311 			    ipst);
6312 			break;
6313 		default:
6314 			freemsg(first_mp);
6315 			break;
6316 		}
6317 	} else {
6318 		freemsg(first_mp);
6319 		return (B_FALSE);
6320 	}
6321 
6322 	return (B_TRUE);
6323 }
6324 
6325 /*
6326  * Used to send an ICMP error message when a packet is received for
6327  * a protocol that is not supported. The mblk passed as argument
6328  * is consumed by this function.
6329  */
6330 void
6331 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6332     ip_stack_t *ipst)
6333 {
6334 	mblk_t *mp;
6335 	ipha_t *ipha;
6336 	ill_t *ill;
6337 	ipsec_in_t *ii;
6338 
6339 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6340 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6341 
6342 	mp = ipsec_mp->b_cont;
6343 	ipsec_mp->b_cont = NULL;
6344 	ipha = (ipha_t *)mp->b_rptr;
6345 	/* Get ill from index in ipsec_in_t. */
6346 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6347 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6348 	    ipst);
6349 	if (ill != NULL) {
6350 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6351 			if (ip_fanout_send_icmp(q, mp, flags,
6352 			    ICMP_DEST_UNREACHABLE,
6353 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6354 				BUMP_MIB(ill->ill_ip_mib,
6355 				    ipIfStatsInUnknownProtos);
6356 			}
6357 		} else {
6358 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6359 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6360 			    0, B_FALSE, zoneid, ipst)) {
6361 				BUMP_MIB(ill->ill_ip_mib,
6362 				    ipIfStatsInUnknownProtos);
6363 			}
6364 		}
6365 		ill_refrele(ill);
6366 	} else { /* re-link for the freemsg() below. */
6367 		ipsec_mp->b_cont = mp;
6368 	}
6369 
6370 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6371 	freemsg(ipsec_mp);
6372 }
6373 
6374 /*
6375  * See if the inbound datagram has had IPsec processing applied to it.
6376  */
6377 boolean_t
6378 ipsec_in_is_secure(mblk_t *ipsec_mp)
6379 {
6380 	ipsec_in_t *ii;
6381 
6382 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6383 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6384 
6385 	if (ii->ipsec_in_loopback) {
6386 		return (ii->ipsec_in_secure);
6387 	} else {
6388 		return (ii->ipsec_in_ah_sa != NULL ||
6389 		    ii->ipsec_in_esp_sa != NULL ||
6390 		    ii->ipsec_in_decaps);
6391 	}
6392 }
6393 
6394 /*
6395  * Handle protocols with which IP is less intimate.  There
6396  * can be more than one stream bound to a particular
6397  * protocol.  When this is the case, normally each one gets a copy
6398  * of any incoming packets.
6399  *
6400  * IPsec NOTE :
6401  *
6402  * Don't allow a secure packet going up a non-secure connection.
6403  * We don't allow this because
6404  *
6405  * 1) Reply might go out in clear which will be dropped at
6406  *    the sending side.
6407  * 2) If the reply goes out in clear it will give the
6408  *    adversary enough information for getting the key in
6409  *    most of the cases.
6410  *
6411  * Moreover getting a secure packet when we expect clear
6412  * implies that SA's were added without checking for
6413  * policy on both ends. This should not happen once ISAKMP
6414  * is used to negotiate SAs as SAs will be added only after
6415  * verifying the policy.
6416  *
6417  * NOTE : If the packet was tunneled and not multicast we only send
6418  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6419  * back to delivering packets to AF_INET6 raw sockets.
6420  *
6421  * IPQoS Notes:
6422  * Once we have determined the client, invoke IPPF processing.
6423  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6424  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6425  * ip_policy will be false.
6426  *
6427  * Zones notes:
6428  * Currently only applications in the global zone can create raw sockets for
6429  * protocols other than ICMP. So unlike the broadcast / multicast case of
6430  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6431  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6432  */
6433 static void
6434 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6435     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6436     zoneid_t zoneid)
6437 {
6438 	queue_t	*rq;
6439 	mblk_t	*mp1, *first_mp1;
6440 	uint_t	protocol = ipha->ipha_protocol;
6441 	ipaddr_t dst;
6442 	boolean_t one_only;
6443 	mblk_t *first_mp = mp;
6444 	boolean_t secure;
6445 	uint32_t ill_index;
6446 	conn_t	*connp, *first_connp, *next_connp;
6447 	connf_t	*connfp;
6448 	boolean_t shared_addr;
6449 	mib2_ipIfStatsEntry_t *mibptr;
6450 	ip_stack_t *ipst = recv_ill->ill_ipst;
6451 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6452 
6453 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6454 	if (mctl_present) {
6455 		mp = first_mp->b_cont;
6456 		secure = ipsec_in_is_secure(first_mp);
6457 		ASSERT(mp != NULL);
6458 	} else {
6459 		secure = B_FALSE;
6460 	}
6461 	dst = ipha->ipha_dst;
6462 	/*
6463 	 * If the packet was tunneled and not multicast we only send to it
6464 	 * the first match.
6465 	 */
6466 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6467 	    !CLASSD(dst));
6468 
6469 	shared_addr = (zoneid == ALL_ZONES);
6470 	if (shared_addr) {
6471 		/*
6472 		 * We don't allow multilevel ports for raw IP, so no need to
6473 		 * check for that here.
6474 		 */
6475 		zoneid = tsol_packet_to_zoneid(mp);
6476 	}
6477 
6478 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6479 	mutex_enter(&connfp->connf_lock);
6480 	connp = connfp->connf_head;
6481 	for (connp = connfp->connf_head; connp != NULL;
6482 	    connp = connp->conn_next) {
6483 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6484 		    zoneid) &&
6485 		    (!is_system_labeled() ||
6486 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6487 		    connp))) {
6488 			break;
6489 		}
6490 	}
6491 
6492 	if (connp == NULL) {
6493 		/*
6494 		 * No one bound to these addresses.  Is
6495 		 * there a client that wants all
6496 		 * unclaimed datagrams?
6497 		 */
6498 		mutex_exit(&connfp->connf_lock);
6499 		/*
6500 		 * Check for IPPROTO_ENCAP...
6501 		 */
6502 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6503 			/*
6504 			 * If an IPsec mblk is here on a multicast
6505 			 * tunnel (using ip_mroute stuff), check policy here,
6506 			 * THEN ship off to ip_mroute_decap().
6507 			 *
6508 			 * BTW,  If I match a configured IP-in-IP
6509 			 * tunnel, this path will not be reached, and
6510 			 * ip_mroute_decap will never be called.
6511 			 */
6512 			first_mp = ipsec_check_global_policy(first_mp, connp,
6513 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6514 			if (first_mp != NULL) {
6515 				if (mctl_present)
6516 					freeb(first_mp);
6517 				ip_mroute_decap(q, mp, ill);
6518 			} /* Else we already freed everything! */
6519 		} else {
6520 			/*
6521 			 * Otherwise send an ICMP protocol unreachable.
6522 			 */
6523 			if (ip_fanout_send_icmp(q, first_mp, flags,
6524 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6525 			    mctl_present, zoneid, ipst)) {
6526 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6527 			}
6528 		}
6529 		return;
6530 	}
6531 
6532 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6533 
6534 	CONN_INC_REF(connp);
6535 	first_connp = connp;
6536 
6537 	/*
6538 	 * Only send message to one tunnel driver by immediately
6539 	 * terminating the loop.
6540 	 */
6541 	connp = one_only ? NULL : connp->conn_next;
6542 
6543 	for (;;) {
6544 		while (connp != NULL) {
6545 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6546 			    flags, zoneid) &&
6547 			    (!is_system_labeled() ||
6548 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6549 			    shared_addr, connp)))
6550 				break;
6551 			connp = connp->conn_next;
6552 		}
6553 
6554 		/*
6555 		 * Copy the packet.
6556 		 */
6557 		if (connp == NULL ||
6558 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6559 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6560 			/*
6561 			 * No more interested clients or memory
6562 			 * allocation failed
6563 			 */
6564 			connp = first_connp;
6565 			break;
6566 		}
6567 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6568 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6569 		CONN_INC_REF(connp);
6570 		mutex_exit(&connfp->connf_lock);
6571 		rq = connp->conn_rq;
6572 
6573 		/*
6574 		 * Check flow control
6575 		 */
6576 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6577 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6578 			if (flags & IP_FF_RAWIP) {
6579 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6580 			} else {
6581 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6582 			}
6583 
6584 			freemsg(first_mp1);
6585 		} else {
6586 			/*
6587 			 * Don't enforce here if we're an actual tunnel -
6588 			 * let "tun" do it instead.
6589 			 */
6590 			if (!IPCL_IS_IPTUN(connp) &&
6591 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6592 			    secure)) {
6593 				first_mp1 = ipsec_check_inbound_policy
6594 				    (first_mp1, connp, ipha, NULL,
6595 				    mctl_present);
6596 			}
6597 			if (first_mp1 != NULL) {
6598 				int in_flags = 0;
6599 				/*
6600 				 * ip_fanout_proto also gets called from
6601 				 * icmp_inbound_error_fanout, in which case
6602 				 * the msg type is M_CTL.  Don't add info
6603 				 * in this case for the time being. In future
6604 				 * when there is a need for knowing the
6605 				 * inbound iface index for ICMP error msgs,
6606 				 * then this can be changed.
6607 				 */
6608 				if (connp->conn_recvif)
6609 					in_flags = IPF_RECVIF;
6610 				/*
6611 				 * The ULP may support IP_RECVPKTINFO for both
6612 				 * IP v4 and v6 so pass the appropriate argument
6613 				 * based on conn IP version.
6614 				 */
6615 				if (connp->conn_ip_recvpktinfo) {
6616 					if (connp->conn_af_isv6) {
6617 						/*
6618 						 * V6 only needs index
6619 						 */
6620 						in_flags |= IPF_RECVIF;
6621 					} else {
6622 						/*
6623 						 * V4 needs index +
6624 						 * matching address.
6625 						 */
6626 						in_flags |= IPF_RECVADDR;
6627 					}
6628 				}
6629 				if ((in_flags != 0) &&
6630 				    (mp->b_datap->db_type != M_CTL)) {
6631 					/*
6632 					 * the actual data will be
6633 					 * contained in b_cont upon
6634 					 * successful return of the
6635 					 * following call else
6636 					 * original mblk is returned
6637 					 */
6638 					ASSERT(recv_ill != NULL);
6639 					mp1 = ip_add_info(mp1, recv_ill,
6640 					    in_flags, IPCL_ZONEID(connp), ipst);
6641 				}
6642 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6643 				if (mctl_present)
6644 					freeb(first_mp1);
6645 				(connp->conn_recv)(connp, mp1, NULL);
6646 			}
6647 		}
6648 		mutex_enter(&connfp->connf_lock);
6649 		/* Follow the next pointer before releasing the conn. */
6650 		next_connp = connp->conn_next;
6651 		CONN_DEC_REF(connp);
6652 		connp = next_connp;
6653 	}
6654 
6655 	/* Last one.  Send it upstream. */
6656 	mutex_exit(&connfp->connf_lock);
6657 
6658 	/*
6659 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6660 	 * will be set to false.
6661 	 */
6662 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6663 		ill_index = ill->ill_phyint->phyint_ifindex;
6664 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6665 		if (mp == NULL) {
6666 			CONN_DEC_REF(connp);
6667 			if (mctl_present) {
6668 				freeb(first_mp);
6669 			}
6670 			return;
6671 		}
6672 	}
6673 
6674 	rq = connp->conn_rq;
6675 	/*
6676 	 * Check flow control
6677 	 */
6678 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6679 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6680 		if (flags & IP_FF_RAWIP) {
6681 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6682 		} else {
6683 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6684 		}
6685 
6686 		freemsg(first_mp);
6687 	} else {
6688 		if (IPCL_IS_IPTUN(connp)) {
6689 			/*
6690 			 * Tunneled packet.  We enforce policy in the tunnel
6691 			 * module itself.
6692 			 *
6693 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6694 			 * a policy check.
6695 			 * FIXME to use conn_recv for tun later.
6696 			 */
6697 			putnext(rq, first_mp);
6698 			CONN_DEC_REF(connp);
6699 			return;
6700 		}
6701 
6702 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6703 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6704 			    ipha, NULL, mctl_present);
6705 		}
6706 
6707 		if (first_mp != NULL) {
6708 			int in_flags = 0;
6709 
6710 			/*
6711 			 * ip_fanout_proto also gets called
6712 			 * from icmp_inbound_error_fanout, in
6713 			 * which case the msg type is M_CTL.
6714 			 * Don't add info in this case for time
6715 			 * being. In future when there is a
6716 			 * need for knowing the inbound iface
6717 			 * index for ICMP error msgs, then this
6718 			 * can be changed
6719 			 */
6720 			if (connp->conn_recvif)
6721 				in_flags = IPF_RECVIF;
6722 			if (connp->conn_ip_recvpktinfo) {
6723 				if (connp->conn_af_isv6) {
6724 					/*
6725 					 * V6 only needs index
6726 					 */
6727 					in_flags |= IPF_RECVIF;
6728 				} else {
6729 					/*
6730 					 * V4 needs index +
6731 					 * matching address.
6732 					 */
6733 					in_flags |= IPF_RECVADDR;
6734 				}
6735 			}
6736 			if ((in_flags != 0) &&
6737 			    (mp->b_datap->db_type != M_CTL)) {
6738 
6739 				/*
6740 				 * the actual data will be contained in
6741 				 * b_cont upon successful return
6742 				 * of the following call else original
6743 				 * mblk is returned
6744 				 */
6745 				ASSERT(recv_ill != NULL);
6746 				mp = ip_add_info(mp, recv_ill,
6747 				    in_flags, IPCL_ZONEID(connp), ipst);
6748 			}
6749 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6750 			(connp->conn_recv)(connp, mp, NULL);
6751 			if (mctl_present)
6752 				freeb(first_mp);
6753 		}
6754 	}
6755 	CONN_DEC_REF(connp);
6756 }
6757 
6758 /*
6759  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6760  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6761  * the correct squeue, in this case the same squeue as a valid listener with
6762  * no current connection state for the packet we are processing. The function
6763  * is called for synchronizing both IPv4 and IPv6.
6764  */
6765 void
6766 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6767     tcp_stack_t *tcps, conn_t *connp)
6768 {
6769 	mblk_t *rst_mp;
6770 	tcp_xmit_reset_event_t *eventp;
6771 
6772 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6773 
6774 	if (rst_mp == NULL) {
6775 		freemsg(mp);
6776 		return;
6777 	}
6778 
6779 	rst_mp->b_datap->db_type = M_PROTO;
6780 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6781 
6782 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6783 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6784 	eventp->tcp_xre_iphdrlen = hdrlen;
6785 	eventp->tcp_xre_zoneid = zoneid;
6786 	eventp->tcp_xre_tcps = tcps;
6787 
6788 	rst_mp->b_cont = mp;
6789 	mp = rst_mp;
6790 
6791 	/*
6792 	 * Increment the connref, this ref will be released by the squeue
6793 	 * framework.
6794 	 */
6795 	CONN_INC_REF(connp);
6796 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6797 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6798 }
6799 
6800 /*
6801  * Fanout for TCP packets
6802  * The caller puts <fport, lport> in the ports parameter.
6803  *
6804  * IPQoS Notes
6805  * Before sending it to the client, invoke IPPF processing.
6806  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6807  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6808  * ip_policy is false.
6809  */
6810 static void
6811 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6812     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6813 {
6814 	mblk_t  *first_mp;
6815 	boolean_t secure;
6816 	uint32_t ill_index;
6817 	int	ip_hdr_len;
6818 	tcph_t	*tcph;
6819 	boolean_t syn_present = B_FALSE;
6820 	conn_t	*connp;
6821 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6822 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6823 
6824 	ASSERT(recv_ill != NULL);
6825 
6826 	first_mp = mp;
6827 	if (mctl_present) {
6828 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6829 		mp = first_mp->b_cont;
6830 		secure = ipsec_in_is_secure(first_mp);
6831 		ASSERT(mp != NULL);
6832 	} else {
6833 		secure = B_FALSE;
6834 	}
6835 
6836 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6837 
6838 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6839 	    zoneid, ipst)) == NULL) {
6840 		/*
6841 		 * No connected connection or listener. Send a
6842 		 * TH_RST via tcp_xmit_listeners_reset.
6843 		 */
6844 
6845 		/* Initiate IPPf processing, if needed. */
6846 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6847 			uint32_t ill_index;
6848 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6849 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6850 			if (first_mp == NULL)
6851 				return;
6852 		}
6853 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6854 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6855 		    zoneid));
6856 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6857 		    ipst->ips_netstack->netstack_tcp, NULL);
6858 		return;
6859 	}
6860 
6861 	/*
6862 	 * Allocate the SYN for the TCP connection here itself
6863 	 */
6864 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6865 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6866 		if (IPCL_IS_TCP(connp)) {
6867 			squeue_t *sqp;
6868 
6869 			/*
6870 			 * If the queue belongs to a conn, and fused tcp
6871 			 * loopback is enabled, assign the eager's squeue
6872 			 * to be that of the active connect's. Note that
6873 			 * we don't check for IP_FF_LOOPBACK here since this
6874 			 * routine gets called only for loopback (unlike the
6875 			 * IPv6 counterpart).
6876 			 */
6877 			if (do_tcp_fusion &&
6878 			    CONN_Q(q) && IPCL_IS_TCP(Q_TO_CONN(q)) &&
6879 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6880 			    !secure &&
6881 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy) {
6882 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6883 				sqp = Q_TO_CONN(q)->conn_sqp;
6884 			} else {
6885 				sqp = IP_SQUEUE_GET(lbolt);
6886 			}
6887 
6888 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6889 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6890 			syn_present = B_TRUE;
6891 		}
6892 	}
6893 
6894 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6895 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6896 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6897 		if ((flags & TH_RST) || (flags & TH_URG)) {
6898 			CONN_DEC_REF(connp);
6899 			freemsg(first_mp);
6900 			return;
6901 		}
6902 		if (flags & TH_ACK) {
6903 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6904 			    ipst->ips_netstack->netstack_tcp, connp);
6905 			CONN_DEC_REF(connp);
6906 			return;
6907 		}
6908 
6909 		CONN_DEC_REF(connp);
6910 		freemsg(first_mp);
6911 		return;
6912 	}
6913 
6914 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6915 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6916 		    NULL, mctl_present);
6917 		if (first_mp == NULL) {
6918 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6919 			CONN_DEC_REF(connp);
6920 			return;
6921 		}
6922 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6923 			ASSERT(syn_present);
6924 			if (mctl_present) {
6925 				ASSERT(first_mp != mp);
6926 				first_mp->b_datap->db_struioflag |=
6927 				    STRUIO_POLICY;
6928 			} else {
6929 				ASSERT(first_mp == mp);
6930 				mp->b_datap->db_struioflag &=
6931 				    ~STRUIO_EAGER;
6932 				mp->b_datap->db_struioflag |=
6933 				    STRUIO_POLICY;
6934 			}
6935 		} else {
6936 			/*
6937 			 * Discard first_mp early since we're dealing with a
6938 			 * fully-connected conn_t and tcp doesn't do policy in
6939 			 * this case.
6940 			 */
6941 			if (mctl_present) {
6942 				freeb(first_mp);
6943 				mctl_present = B_FALSE;
6944 			}
6945 			first_mp = mp;
6946 		}
6947 	}
6948 
6949 	/*
6950 	 * Initiate policy processing here if needed. If we get here from
6951 	 * icmp_inbound_error_fanout, ip_policy is false.
6952 	 */
6953 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6954 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6955 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6956 		if (mp == NULL) {
6957 			CONN_DEC_REF(connp);
6958 			if (mctl_present)
6959 				freeb(first_mp);
6960 			return;
6961 		} else if (mctl_present) {
6962 			ASSERT(first_mp != mp);
6963 			first_mp->b_cont = mp;
6964 		} else {
6965 			first_mp = mp;
6966 		}
6967 	}
6968 
6969 	/* Handle socket options. */
6970 	if (!syn_present &&
6971 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6972 		/* Add header */
6973 		ASSERT(recv_ill != NULL);
6974 		/*
6975 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6976 		 * IPF_RECVIF.
6977 		 */
6978 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6979 		    ipst);
6980 		if (mp == NULL) {
6981 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6982 			CONN_DEC_REF(connp);
6983 			if (mctl_present)
6984 				freeb(first_mp);
6985 			return;
6986 		} else if (mctl_present) {
6987 			/*
6988 			 * ip_add_info might return a new mp.
6989 			 */
6990 			ASSERT(first_mp != mp);
6991 			first_mp->b_cont = mp;
6992 		} else {
6993 			first_mp = mp;
6994 		}
6995 	}
6996 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6997 	if (IPCL_IS_TCP(connp)) {
6998 		/* do not drain, certain use cases can blow the stack */
6999 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
7000 		    connp, SQ_NODRAIN, SQTAG_IP_FANOUT_TCP);
7001 	} else {
7002 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
7003 		(connp->conn_recv)(connp, first_mp, NULL);
7004 		CONN_DEC_REF(connp);
7005 	}
7006 }
7007 
7008 /*
7009  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
7010  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
7011  * is not consumed.
7012  *
7013  * One of four things can happen, all of which affect the passed-in mblk:
7014  *
7015  * 1.) ICMP messages that go through here just get returned TRUE.
7016  *
7017  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
7018  *
7019  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
7020  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
7021  *
7022  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
7023  */
7024 static boolean_t
7025 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
7026     ipsec_stack_t *ipss)
7027 {
7028 	int shift, plen, iph_len;
7029 	ipha_t *ipha;
7030 	udpha_t *udpha;
7031 	uint32_t *spi;
7032 	uint32_t esp_ports;
7033 	uint8_t *orptr;
7034 	boolean_t free_ire;
7035 
7036 	if (DB_TYPE(mp) == M_CTL) {
7037 		/*
7038 		 * ICMP message with UDP inside.  Don't bother stripping, just
7039 		 * send it up.
7040 		 *
7041 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
7042 		 * to ignore errors set by ICMP anyway ('cause they might be
7043 		 * forged), but that's the app's decision, not ours.
7044 		 */
7045 
7046 		/* Bunch of reality checks for DEBUG kernels... */
7047 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
7048 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
7049 
7050 		return (B_TRUE);
7051 	}
7052 
7053 	ipha = (ipha_t *)mp->b_rptr;
7054 	iph_len = IPH_HDR_LENGTH(ipha);
7055 	plen = ntohs(ipha->ipha_length);
7056 
7057 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
7058 		/*
7059 		 * Most likely a keepalive for the benefit of an intervening
7060 		 * NAT.  These aren't for us, per se, so drop it.
7061 		 *
7062 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
7063 		 * byte packets (keepalives are 1-byte), but we'll drop them
7064 		 * also.
7065 		 */
7066 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7067 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7068 		return (B_FALSE);
7069 	}
7070 
7071 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7072 		/* might as well pull it all up - it might be ESP. */
7073 		if (!pullupmsg(mp, -1)) {
7074 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7075 			    DROPPER(ipss, ipds_esp_nomem),
7076 			    &ipss->ipsec_dropper);
7077 			return (B_FALSE);
7078 		}
7079 
7080 		ipha = (ipha_t *)mp->b_rptr;
7081 	}
7082 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7083 	if (*spi == 0) {
7084 		/* UDP packet - remove 0-spi. */
7085 		shift = sizeof (uint32_t);
7086 	} else {
7087 		/* ESP-in-UDP packet - reduce to ESP. */
7088 		ipha->ipha_protocol = IPPROTO_ESP;
7089 		shift = sizeof (udpha_t);
7090 	}
7091 
7092 	/* Fix IP header */
7093 	ipha->ipha_length = htons(plen - shift);
7094 	ipha->ipha_hdr_checksum = 0;
7095 
7096 	orptr = mp->b_rptr;
7097 	mp->b_rptr += shift;
7098 
7099 	udpha = (udpha_t *)(orptr + iph_len);
7100 	if (*spi == 0) {
7101 		ASSERT((uint8_t *)ipha == orptr);
7102 		udpha->uha_length = htons(plen - shift - iph_len);
7103 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7104 		esp_ports = 0;
7105 	} else {
7106 		esp_ports = *((uint32_t *)udpha);
7107 		ASSERT(esp_ports != 0);
7108 	}
7109 	ovbcopy(orptr, orptr + shift, iph_len);
7110 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7111 		ipha = (ipha_t *)(orptr + shift);
7112 
7113 		free_ire = (ire == NULL);
7114 		if (free_ire) {
7115 			/* Re-acquire ire. */
7116 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7117 			    ipss->ipsec_netstack->netstack_ip);
7118 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7119 				if (ire != NULL)
7120 					ire_refrele(ire);
7121 				/*
7122 				 * Do a regular freemsg(), as this is an IP
7123 				 * error (no local route) not an IPsec one.
7124 				 */
7125 				freemsg(mp);
7126 			}
7127 		}
7128 
7129 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7130 		if (free_ire)
7131 			ire_refrele(ire);
7132 	}
7133 
7134 	return (esp_ports == 0);
7135 }
7136 
7137 /*
7138  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7139  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7140  * Caller is responsible for dropping references to the conn, and freeing
7141  * first_mp.
7142  *
7143  * IPQoS Notes
7144  * Before sending it to the client, invoke IPPF processing. Policy processing
7145  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7146  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7147  * ip_wput_local, ip_policy is false.
7148  */
7149 static void
7150 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7151     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7152     boolean_t ip_policy)
7153 {
7154 	boolean_t	mctl_present = (first_mp != NULL);
7155 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7156 	uint32_t	ill_index;
7157 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7158 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7159 
7160 	ASSERT(ill != NULL);
7161 
7162 	if (mctl_present)
7163 		first_mp->b_cont = mp;
7164 	else
7165 		first_mp = mp;
7166 
7167 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7168 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7169 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7170 		freemsg(first_mp);
7171 		return;
7172 	}
7173 
7174 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7175 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7176 		    NULL, mctl_present);
7177 		/* Freed by ipsec_check_inbound_policy(). */
7178 		if (first_mp == NULL) {
7179 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7180 			return;
7181 		}
7182 	}
7183 	if (mctl_present)
7184 		freeb(first_mp);
7185 
7186 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7187 	if (connp->conn_udp->udp_nat_t_endpoint) {
7188 		if (mctl_present) {
7189 			/* mctl_present *shouldn't* happen. */
7190 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7191 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7192 			    &ipss->ipsec_dropper);
7193 			return;
7194 		}
7195 
7196 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7197 			return;
7198 	}
7199 
7200 	/* Handle options. */
7201 	if (connp->conn_recvif)
7202 		in_flags = IPF_RECVIF;
7203 	/*
7204 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7205 	 * passed to ip_add_info is based on IP version of connp.
7206 	 */
7207 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7208 		if (connp->conn_af_isv6) {
7209 			/*
7210 			 * V6 only needs index
7211 			 */
7212 			in_flags |= IPF_RECVIF;
7213 		} else {
7214 			/*
7215 			 * V4 needs index + matching address.
7216 			 */
7217 			in_flags |= IPF_RECVADDR;
7218 		}
7219 	}
7220 
7221 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7222 		in_flags |= IPF_RECVSLLA;
7223 
7224 	/*
7225 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7226 	 * freed if the packet is dropped. The caller will do so.
7227 	 */
7228 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7229 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7230 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7231 		if (mp == NULL) {
7232 			return;
7233 		}
7234 	}
7235 	if ((in_flags != 0) &&
7236 	    (mp->b_datap->db_type != M_CTL)) {
7237 		/*
7238 		 * The actual data will be contained in b_cont
7239 		 * upon successful return of the following call
7240 		 * else original mblk is returned
7241 		 */
7242 		ASSERT(recv_ill != NULL);
7243 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7244 		    ipst);
7245 	}
7246 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7247 	/* Send it upstream */
7248 	(connp->conn_recv)(connp, mp, NULL);
7249 }
7250 
7251 /*
7252  * Fanout for UDP packets.
7253  * The caller puts <fport, lport> in the ports parameter.
7254  *
7255  * If SO_REUSEADDR is set all multicast and broadcast packets
7256  * will be delivered to all streams bound to the same port.
7257  *
7258  * Zones notes:
7259  * Multicast and broadcast packets will be distributed to streams in all zones.
7260  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7261  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7262  * packets. To maintain this behavior with multiple zones, the conns are grouped
7263  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7264  * each zone. If unset, all the following conns in the same zone are skipped.
7265  */
7266 static void
7267 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7268     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7269     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7270 {
7271 	uint32_t	dstport, srcport;
7272 	ipaddr_t	dst;
7273 	mblk_t		*first_mp;
7274 	boolean_t	secure;
7275 	in6_addr_t	v6src;
7276 	conn_t		*connp;
7277 	connf_t		*connfp;
7278 	conn_t		*first_connp;
7279 	conn_t		*next_connp;
7280 	mblk_t		*mp1, *first_mp1;
7281 	ipaddr_t	src;
7282 	zoneid_t	last_zoneid;
7283 	boolean_t	reuseaddr;
7284 	boolean_t	shared_addr;
7285 	boolean_t	unlabeled;
7286 	ip_stack_t	*ipst;
7287 
7288 	ASSERT(recv_ill != NULL);
7289 	ipst = recv_ill->ill_ipst;
7290 
7291 	first_mp = mp;
7292 	if (mctl_present) {
7293 		mp = first_mp->b_cont;
7294 		first_mp->b_cont = NULL;
7295 		secure = ipsec_in_is_secure(first_mp);
7296 		ASSERT(mp != NULL);
7297 	} else {
7298 		first_mp = NULL;
7299 		secure = B_FALSE;
7300 	}
7301 
7302 	/* Extract ports in net byte order */
7303 	dstport = htons(ntohl(ports) & 0xFFFF);
7304 	srcport = htons(ntohl(ports) >> 16);
7305 	dst = ipha->ipha_dst;
7306 	src = ipha->ipha_src;
7307 
7308 	unlabeled = B_FALSE;
7309 	if (is_system_labeled())
7310 		/* Cred cannot be null on IPv4 */
7311 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7312 		    TSLF_UNLABELED) != 0;
7313 	shared_addr = (zoneid == ALL_ZONES);
7314 	if (shared_addr) {
7315 		/*
7316 		 * No need to handle exclusive-stack zones since ALL_ZONES
7317 		 * only applies to the shared stack.
7318 		 */
7319 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7320 		/*
7321 		 * If no shared MLP is found, tsol_mlp_findzone returns
7322 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7323 		 * search for the zone based on the packet label.
7324 		 *
7325 		 * If there is such a zone, we prefer to find a
7326 		 * connection in it.  Otherwise, we look for a
7327 		 * MAC-exempt connection in any zone whose label
7328 		 * dominates the default label on the packet.
7329 		 */
7330 		if (zoneid == ALL_ZONES)
7331 			zoneid = tsol_packet_to_zoneid(mp);
7332 		else
7333 			unlabeled = B_FALSE;
7334 	}
7335 
7336 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7337 	mutex_enter(&connfp->connf_lock);
7338 	connp = connfp->connf_head;
7339 	if (!broadcast && !CLASSD(dst)) {
7340 		/*
7341 		 * Not broadcast or multicast. Send to the one (first)
7342 		 * client we find. No need to check conn_wantpacket()
7343 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7344 		 * IPv4 unicast packets.
7345 		 */
7346 		while ((connp != NULL) &&
7347 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7348 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7349 		    !(unlabeled && connp->conn_mac_exempt && shared_addr)))) {
7350 			/*
7351 			 * We keep searching since the conn did not match,
7352 			 * or its zone did not match and it is not either
7353 			 * an allzones conn or a mac exempt conn (if the
7354 			 * sender is unlabeled.)
7355 			 */
7356 			connp = connp->conn_next;
7357 		}
7358 
7359 		if (connp == NULL ||
7360 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7361 			goto notfound;
7362 
7363 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7364 
7365 		if (is_system_labeled() &&
7366 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7367 		    connp))
7368 			goto notfound;
7369 
7370 		CONN_INC_REF(connp);
7371 		mutex_exit(&connfp->connf_lock);
7372 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7373 		    flags, recv_ill, ip_policy);
7374 		IP_STAT(ipst, ip_udp_fannorm);
7375 		CONN_DEC_REF(connp);
7376 		return;
7377 	}
7378 
7379 	/*
7380 	 * Broadcast and multicast case
7381 	 *
7382 	 * Need to check conn_wantpacket().
7383 	 * If SO_REUSEADDR has been set on the first we send the
7384 	 * packet to all clients that have joined the group and
7385 	 * match the port.
7386 	 */
7387 
7388 	while (connp != NULL) {
7389 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7390 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7391 		    (!is_system_labeled() ||
7392 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7393 		    connp)))
7394 			break;
7395 		connp = connp->conn_next;
7396 	}
7397 
7398 	if (connp == NULL ||
7399 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7400 		goto notfound;
7401 
7402 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7403 
7404 	first_connp = connp;
7405 	/*
7406 	 * When SO_REUSEADDR is not set, send the packet only to the first
7407 	 * matching connection in its zone by keeping track of the zoneid.
7408 	 */
7409 	reuseaddr = first_connp->conn_reuseaddr;
7410 	last_zoneid = first_connp->conn_zoneid;
7411 
7412 	CONN_INC_REF(connp);
7413 	connp = connp->conn_next;
7414 	for (;;) {
7415 		while (connp != NULL) {
7416 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7417 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7418 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7419 			    (!is_system_labeled() ||
7420 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7421 			    shared_addr, connp)))
7422 				break;
7423 			connp = connp->conn_next;
7424 		}
7425 		/*
7426 		 * Just copy the data part alone. The mctl part is
7427 		 * needed just for verifying policy and it is never
7428 		 * sent up.
7429 		 */
7430 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7431 		    ((mp1 = copymsg(mp)) == NULL))) {
7432 			/*
7433 			 * No more interested clients or memory
7434 			 * allocation failed
7435 			 */
7436 			connp = first_connp;
7437 			break;
7438 		}
7439 		if (connp->conn_zoneid != last_zoneid) {
7440 			/*
7441 			 * Update the zoneid so that the packet isn't sent to
7442 			 * any more conns in the same zone unless SO_REUSEADDR
7443 			 * is set.
7444 			 */
7445 			reuseaddr = connp->conn_reuseaddr;
7446 			last_zoneid = connp->conn_zoneid;
7447 		}
7448 		if (first_mp != NULL) {
7449 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7450 			    ipsec_info_type == IPSEC_IN);
7451 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7452 			    ipst->ips_netstack);
7453 			if (first_mp1 == NULL) {
7454 				freemsg(mp1);
7455 				connp = first_connp;
7456 				break;
7457 			}
7458 		} else {
7459 			first_mp1 = NULL;
7460 		}
7461 		CONN_INC_REF(connp);
7462 		mutex_exit(&connfp->connf_lock);
7463 		/*
7464 		 * IPQoS notes: We don't send the packet for policy
7465 		 * processing here, will do it for the last one (below).
7466 		 * i.e. we do it per-packet now, but if we do policy
7467 		 * processing per-conn, then we would need to do it
7468 		 * here too.
7469 		 */
7470 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7471 		    ipha, flags, recv_ill, B_FALSE);
7472 		mutex_enter(&connfp->connf_lock);
7473 		/* Follow the next pointer before releasing the conn. */
7474 		next_connp = connp->conn_next;
7475 		IP_STAT(ipst, ip_udp_fanmb);
7476 		CONN_DEC_REF(connp);
7477 		connp = next_connp;
7478 	}
7479 
7480 	/* Last one.  Send it upstream. */
7481 	mutex_exit(&connfp->connf_lock);
7482 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7483 	    recv_ill, ip_policy);
7484 	IP_STAT(ipst, ip_udp_fanmb);
7485 	CONN_DEC_REF(connp);
7486 	return;
7487 
7488 notfound:
7489 
7490 	mutex_exit(&connfp->connf_lock);
7491 	IP_STAT(ipst, ip_udp_fanothers);
7492 	/*
7493 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7494 	 * have already been matched above, since they live in the IPv4
7495 	 * fanout tables. This implies we only need to
7496 	 * check for IPv6 in6addr_any endpoints here.
7497 	 * Thus we compare using ipv6_all_zeros instead of the destination
7498 	 * address, except for the multicast group membership lookup which
7499 	 * uses the IPv4 destination.
7500 	 */
7501 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7502 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7503 	mutex_enter(&connfp->connf_lock);
7504 	connp = connfp->connf_head;
7505 	if (!broadcast && !CLASSD(dst)) {
7506 		while (connp != NULL) {
7507 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7508 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7509 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7510 			    !connp->conn_ipv6_v6only)
7511 				break;
7512 			connp = connp->conn_next;
7513 		}
7514 
7515 		if (connp != NULL && is_system_labeled() &&
7516 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7517 		    connp))
7518 			connp = NULL;
7519 
7520 		if (connp == NULL ||
7521 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7522 			/*
7523 			 * No one bound to this port.  Is
7524 			 * there a client that wants all
7525 			 * unclaimed datagrams?
7526 			 */
7527 			mutex_exit(&connfp->connf_lock);
7528 
7529 			if (mctl_present)
7530 				first_mp->b_cont = mp;
7531 			else
7532 				first_mp = mp;
7533 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7534 			    connf_head != NULL) {
7535 				ip_fanout_proto(q, first_mp, ill, ipha,
7536 				    flags | IP_FF_RAWIP, mctl_present,
7537 				    ip_policy, recv_ill, zoneid);
7538 			} else {
7539 				if (ip_fanout_send_icmp(q, first_mp, flags,
7540 				    ICMP_DEST_UNREACHABLE,
7541 				    ICMP_PORT_UNREACHABLE,
7542 				    mctl_present, zoneid, ipst)) {
7543 					BUMP_MIB(ill->ill_ip_mib,
7544 					    udpIfStatsNoPorts);
7545 				}
7546 			}
7547 			return;
7548 		}
7549 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7550 
7551 		CONN_INC_REF(connp);
7552 		mutex_exit(&connfp->connf_lock);
7553 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7554 		    flags, recv_ill, ip_policy);
7555 		CONN_DEC_REF(connp);
7556 		return;
7557 	}
7558 	/*
7559 	 * IPv4 multicast packet being delivered to an AF_INET6
7560 	 * in6addr_any endpoint.
7561 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7562 	 * and not conn_wantpacket_v6() since any multicast membership is
7563 	 * for an IPv4-mapped multicast address.
7564 	 * The packet is sent to all clients in all zones that have joined the
7565 	 * group and match the port.
7566 	 */
7567 	while (connp != NULL) {
7568 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7569 		    srcport, v6src) &&
7570 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7571 		    (!is_system_labeled() ||
7572 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7573 		    connp)))
7574 			break;
7575 		connp = connp->conn_next;
7576 	}
7577 
7578 	if (connp == NULL ||
7579 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7580 		/*
7581 		 * No one bound to this port.  Is
7582 		 * there a client that wants all
7583 		 * unclaimed datagrams?
7584 		 */
7585 		mutex_exit(&connfp->connf_lock);
7586 
7587 		if (mctl_present)
7588 			first_mp->b_cont = mp;
7589 		else
7590 			first_mp = mp;
7591 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7592 		    NULL) {
7593 			ip_fanout_proto(q, first_mp, ill, ipha,
7594 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7595 			    recv_ill, zoneid);
7596 		} else {
7597 			/*
7598 			 * We used to attempt to send an icmp error here, but
7599 			 * since this is known to be a multicast packet
7600 			 * and we don't send icmp errors in response to
7601 			 * multicast, just drop the packet and give up sooner.
7602 			 */
7603 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7604 			freemsg(first_mp);
7605 		}
7606 		return;
7607 	}
7608 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7609 
7610 	first_connp = connp;
7611 
7612 	CONN_INC_REF(connp);
7613 	connp = connp->conn_next;
7614 	for (;;) {
7615 		while (connp != NULL) {
7616 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7617 			    ipv6_all_zeros, srcport, v6src) &&
7618 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7619 			    (!is_system_labeled() ||
7620 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7621 			    shared_addr, connp)))
7622 				break;
7623 			connp = connp->conn_next;
7624 		}
7625 		/*
7626 		 * Just copy the data part alone. The mctl part is
7627 		 * needed just for verifying policy and it is never
7628 		 * sent up.
7629 		 */
7630 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7631 		    ((mp1 = copymsg(mp)) == NULL))) {
7632 			/*
7633 			 * No more intested clients or memory
7634 			 * allocation failed
7635 			 */
7636 			connp = first_connp;
7637 			break;
7638 		}
7639 		if (first_mp != NULL) {
7640 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7641 			    ipsec_info_type == IPSEC_IN);
7642 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7643 			    ipst->ips_netstack);
7644 			if (first_mp1 == NULL) {
7645 				freemsg(mp1);
7646 				connp = first_connp;
7647 				break;
7648 			}
7649 		} else {
7650 			first_mp1 = NULL;
7651 		}
7652 		CONN_INC_REF(connp);
7653 		mutex_exit(&connfp->connf_lock);
7654 		/*
7655 		 * IPQoS notes: We don't send the packet for policy
7656 		 * processing here, will do it for the last one (below).
7657 		 * i.e. we do it per-packet now, but if we do policy
7658 		 * processing per-conn, then we would need to do it
7659 		 * here too.
7660 		 */
7661 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7662 		    ipha, flags, recv_ill, B_FALSE);
7663 		mutex_enter(&connfp->connf_lock);
7664 		/* Follow the next pointer before releasing the conn. */
7665 		next_connp = connp->conn_next;
7666 		CONN_DEC_REF(connp);
7667 		connp = next_connp;
7668 	}
7669 
7670 	/* Last one.  Send it upstream. */
7671 	mutex_exit(&connfp->connf_lock);
7672 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7673 	    recv_ill, ip_policy);
7674 	CONN_DEC_REF(connp);
7675 }
7676 
7677 /*
7678  * Complete the ip_wput header so that it
7679  * is possible to generate ICMP
7680  * errors.
7681  */
7682 int
7683 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7684 {
7685 	ire_t *ire;
7686 
7687 	if (ipha->ipha_src == INADDR_ANY) {
7688 		ire = ire_lookup_local(zoneid, ipst);
7689 		if (ire == NULL) {
7690 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7691 			return (1);
7692 		}
7693 		ipha->ipha_src = ire->ire_addr;
7694 		ire_refrele(ire);
7695 	}
7696 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7697 	ipha->ipha_hdr_checksum = 0;
7698 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7699 	return (0);
7700 }
7701 
7702 /*
7703  * Nobody should be sending
7704  * packets up this stream
7705  */
7706 static void
7707 ip_lrput(queue_t *q, mblk_t *mp)
7708 {
7709 	mblk_t *mp1;
7710 
7711 	switch (mp->b_datap->db_type) {
7712 	case M_FLUSH:
7713 		/* Turn around */
7714 		if (*mp->b_rptr & FLUSHW) {
7715 			*mp->b_rptr &= ~FLUSHR;
7716 			qreply(q, mp);
7717 			return;
7718 		}
7719 		break;
7720 	}
7721 	/* Could receive messages that passed through ar_rput */
7722 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7723 		mp1->b_prev = mp1->b_next = NULL;
7724 	freemsg(mp);
7725 }
7726 
7727 /* Nobody should be sending packets down this stream */
7728 /* ARGSUSED */
7729 void
7730 ip_lwput(queue_t *q, mblk_t *mp)
7731 {
7732 	freemsg(mp);
7733 }
7734 
7735 /*
7736  * Move the first hop in any source route to ipha_dst and remove that part of
7737  * the source route.  Called by other protocols.  Errors in option formatting
7738  * are ignored - will be handled by ip_wput_options Return the final
7739  * destination (either ipha_dst or the last entry in a source route.)
7740  */
7741 ipaddr_t
7742 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7743 {
7744 	ipoptp_t	opts;
7745 	uchar_t		*opt;
7746 	uint8_t		optval;
7747 	uint8_t		optlen;
7748 	ipaddr_t	dst;
7749 	int		i;
7750 	ire_t		*ire;
7751 	ip_stack_t	*ipst = ns->netstack_ip;
7752 
7753 	ip2dbg(("ip_massage_options\n"));
7754 	dst = ipha->ipha_dst;
7755 	for (optval = ipoptp_first(&opts, ipha);
7756 	    optval != IPOPT_EOL;
7757 	    optval = ipoptp_next(&opts)) {
7758 		opt = opts.ipoptp_cur;
7759 		switch (optval) {
7760 			uint8_t off;
7761 		case IPOPT_SSRR:
7762 		case IPOPT_LSRR:
7763 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7764 				ip1dbg(("ip_massage_options: bad src route\n"));
7765 				break;
7766 			}
7767 			optlen = opts.ipoptp_len;
7768 			off = opt[IPOPT_OFFSET];
7769 			off--;
7770 		redo_srr:
7771 			if (optlen < IP_ADDR_LEN ||
7772 			    off > optlen - IP_ADDR_LEN) {
7773 				/* End of source route */
7774 				ip1dbg(("ip_massage_options: end of SR\n"));
7775 				break;
7776 			}
7777 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7778 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7779 			    ntohl(dst)));
7780 			/*
7781 			 * Check if our address is present more than
7782 			 * once as consecutive hops in source route.
7783 			 * XXX verify per-interface ip_forwarding
7784 			 * for source route?
7785 			 */
7786 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7787 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7788 			if (ire != NULL) {
7789 				ire_refrele(ire);
7790 				off += IP_ADDR_LEN;
7791 				goto redo_srr;
7792 			}
7793 			if (dst == htonl(INADDR_LOOPBACK)) {
7794 				ip1dbg(("ip_massage_options: loopback addr in "
7795 				    "source route!\n"));
7796 				break;
7797 			}
7798 			/*
7799 			 * Update ipha_dst to be the first hop and remove the
7800 			 * first hop from the source route (by overwriting
7801 			 * part of the option with NOP options).
7802 			 */
7803 			ipha->ipha_dst = dst;
7804 			/* Put the last entry in dst */
7805 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7806 			    3;
7807 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7808 
7809 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7810 			    ntohl(dst)));
7811 			/* Move down and overwrite */
7812 			opt[IP_ADDR_LEN] = opt[0];
7813 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7814 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7815 			for (i = 0; i < IP_ADDR_LEN; i++)
7816 				opt[i] = IPOPT_NOP;
7817 			break;
7818 		}
7819 	}
7820 	return (dst);
7821 }
7822 
7823 /*
7824  * Return the network mask
7825  * associated with the specified address.
7826  */
7827 ipaddr_t
7828 ip_net_mask(ipaddr_t addr)
7829 {
7830 	uchar_t	*up = (uchar_t *)&addr;
7831 	ipaddr_t mask = 0;
7832 	uchar_t	*maskp = (uchar_t *)&mask;
7833 
7834 #if defined(__i386) || defined(__amd64)
7835 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7836 #endif
7837 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7838 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7839 #endif
7840 	if (CLASSD(addr)) {
7841 		maskp[0] = 0xF0;
7842 		return (mask);
7843 	}
7844 
7845 	/* We assume Class E default netmask to be 32 */
7846 	if (CLASSE(addr))
7847 		return (0xffffffffU);
7848 
7849 	if (addr == 0)
7850 		return (0);
7851 	maskp[0] = 0xFF;
7852 	if ((up[0] & 0x80) == 0)
7853 		return (mask);
7854 
7855 	maskp[1] = 0xFF;
7856 	if ((up[0] & 0xC0) == 0x80)
7857 		return (mask);
7858 
7859 	maskp[2] = 0xFF;
7860 	if ((up[0] & 0xE0) == 0xC0)
7861 		return (mask);
7862 
7863 	/* Otherwise return no mask */
7864 	return ((ipaddr_t)0);
7865 }
7866 
7867 /*
7868  * Helper ill lookup function used by IPsec.
7869  */
7870 ill_t *
7871 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7872 {
7873 	ill_t *ret_ill;
7874 
7875 	ASSERT(ifindex != 0);
7876 
7877 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7878 	    ipst);
7879 	if (ret_ill == NULL) {
7880 		if (isv6) {
7881 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7882 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7883 			    ifindex));
7884 		} else {
7885 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7886 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7887 			    ifindex));
7888 		}
7889 		freemsg(first_mp);
7890 		return (NULL);
7891 	}
7892 	return (ret_ill);
7893 }
7894 
7895 /*
7896  * IPv4 -
7897  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7898  * out a packet to a destination address for which we do not have specific
7899  * (or sufficient) routing information.
7900  *
7901  * NOTE : These are the scopes of some of the variables that point at IRE,
7902  *	  which needs to be followed while making any future modifications
7903  *	  to avoid memory leaks.
7904  *
7905  *	- ire and sire are the entries looked up initially by
7906  *	  ire_ftable_lookup.
7907  *	- ipif_ire is used to hold the interface ire associated with
7908  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7909  *	  it before branching out to error paths.
7910  *	- save_ire is initialized before ire_create, so that ire returned
7911  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7912  *	  before breaking out of the switch.
7913  *
7914  *	Thus on failures, we have to REFRELE only ire and sire, if they
7915  *	are not NULL.
7916  */
7917 void
7918 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7919     zoneid_t zoneid, ip_stack_t *ipst)
7920 {
7921 	areq_t	*areq;
7922 	ipaddr_t gw = 0;
7923 	ire_t	*ire = NULL;
7924 	mblk_t	*res_mp;
7925 	ipaddr_t *addrp;
7926 	ipaddr_t nexthop_addr;
7927 	ipif_t  *src_ipif = NULL;
7928 	ill_t	*dst_ill = NULL;
7929 	ipha_t  *ipha;
7930 	ire_t	*sire = NULL;
7931 	mblk_t	*first_mp;
7932 	ire_t	*save_ire;
7933 	ushort_t ire_marks = 0;
7934 	boolean_t mctl_present;
7935 	ipsec_out_t *io;
7936 	mblk_t	*saved_mp;
7937 	mblk_t	*copy_mp = NULL;
7938 	mblk_t	*xmit_mp = NULL;
7939 	ipaddr_t save_dst;
7940 	uint32_t multirt_flags =
7941 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7942 	boolean_t multirt_is_resolvable;
7943 	boolean_t multirt_resolve_next;
7944 	boolean_t unspec_src;
7945 	boolean_t ip_nexthop = B_FALSE;
7946 	tsol_ire_gw_secattr_t *attrp = NULL;
7947 	tsol_gcgrp_t *gcgrp = NULL;
7948 	tsol_gcgrp_addr_t ga;
7949 	int multirt_res_failures = 0;
7950 	int multirt_res_attempts = 0;
7951 	int multirt_already_resolved = 0;
7952 	boolean_t multirt_no_icmp_error = B_FALSE;
7953 
7954 	if (ip_debug > 2) {
7955 		/* ip1dbg */
7956 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7957 	}
7958 
7959 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7960 	if (mctl_present) {
7961 		io = (ipsec_out_t *)first_mp->b_rptr;
7962 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7963 		ASSERT(zoneid == io->ipsec_out_zoneid);
7964 		ASSERT(zoneid != ALL_ZONES);
7965 	}
7966 
7967 	ipha = (ipha_t *)mp->b_rptr;
7968 
7969 	/* All multicast lookups come through ip_newroute_ipif() */
7970 	if (CLASSD(dst)) {
7971 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7972 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7973 		freemsg(first_mp);
7974 		return;
7975 	}
7976 
7977 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7978 		ip_nexthop = B_TRUE;
7979 		nexthop_addr = io->ipsec_out_nexthop_addr;
7980 	}
7981 	/*
7982 	 * If this IRE is created for forwarding or it is not for
7983 	 * traffic for congestion controlled protocols, mark it as temporary.
7984 	 */
7985 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7986 		ire_marks |= IRE_MARK_TEMPORARY;
7987 
7988 	/*
7989 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7990 	 * chain until it gets the most specific information available.
7991 	 * For example, we know that there is no IRE_CACHE for this dest,
7992 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7993 	 * ire_ftable_lookup will look up the gateway, etc.
7994 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7995 	 * to the destination, of equal netmask length in the forward table,
7996 	 * will be recursively explored. If no information is available
7997 	 * for the final gateway of that route, we force the returned ire
7998 	 * to be equal to sire using MATCH_IRE_PARENT.
7999 	 * At least, in this case we have a starting point (in the buckets)
8000 	 * to look for other routes to the destination in the forward table.
8001 	 * This is actually used only for multirouting, where a list
8002 	 * of routes has to be processed in sequence.
8003 	 *
8004 	 * In the process of coming up with the most specific information,
8005 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8006 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8007 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8008 	 * Two caveats when handling incomplete ire's in ip_newroute:
8009 	 * - we should be careful when accessing its ire_nce (specifically
8010 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8011 	 * - not all legacy code path callers are prepared to handle
8012 	 *   incomplete ire's, so we should not create/add incomplete
8013 	 *   ire_cache entries here. (See discussion about temporary solution
8014 	 *   further below).
8015 	 *
8016 	 * In order to minimize packet dropping, and to preserve existing
8017 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8018 	 * gateway, and instead use the IF_RESOLVER ire to send out
8019 	 * another request to ARP (this is achieved by passing the
8020 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8021 	 * arp response comes back in ip_wput_nondata, we will create
8022 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8023 	 *
8024 	 * Note that this is a temporary solution; the correct solution is
8025 	 * to create an incomplete  per-dst ire_cache entry, and send the
8026 	 * packet out when the gw's nce is resolved. In order to achieve this,
8027 	 * all packet processing must have been completed prior to calling
8028 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8029 	 * to be modified to accomodate this solution.
8030 	 */
8031 	if (ip_nexthop) {
8032 		/*
8033 		 * The first time we come here, we look for an IRE_INTERFACE
8034 		 * entry for the specified nexthop, set the dst to be the
8035 		 * nexthop address and create an IRE_CACHE entry for the
8036 		 * nexthop. The next time around, we are able to find an
8037 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8038 		 * nexthop address and create an IRE_CACHE entry for the
8039 		 * destination address via the specified nexthop.
8040 		 */
8041 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8042 		    msg_getlabel(mp), ipst);
8043 		if (ire != NULL) {
8044 			gw = nexthop_addr;
8045 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8046 		} else {
8047 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8048 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8049 			    msg_getlabel(mp),
8050 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8051 			    ipst);
8052 			if (ire != NULL) {
8053 				dst = nexthop_addr;
8054 			}
8055 		}
8056 	} else {
8057 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8058 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
8059 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8060 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8061 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8062 		    ipst);
8063 	}
8064 
8065 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8066 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8067 
8068 	/*
8069 	 * This loop is run only once in most cases.
8070 	 * We loop to resolve further routes only when the destination
8071 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8072 	 */
8073 	do {
8074 		/* Clear the previous iteration's values */
8075 		if (src_ipif != NULL) {
8076 			ipif_refrele(src_ipif);
8077 			src_ipif = NULL;
8078 		}
8079 		if (dst_ill != NULL) {
8080 			ill_refrele(dst_ill);
8081 			dst_ill = NULL;
8082 		}
8083 
8084 		multirt_resolve_next = B_FALSE;
8085 		/*
8086 		 * We check if packets have to be multirouted.
8087 		 * In this case, given the current <ire, sire> couple,
8088 		 * we look for the next suitable <ire, sire>.
8089 		 * This check is done in ire_multirt_lookup(),
8090 		 * which applies various criteria to find the next route
8091 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8092 		 * unchanged if it detects it has not been tried yet.
8093 		 */
8094 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8095 			ip3dbg(("ip_newroute: starting next_resolution "
8096 			    "with first_mp %p, tag %d\n",
8097 			    (void *)first_mp,
8098 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8099 
8100 			ASSERT(sire != NULL);
8101 			multirt_is_resolvable =
8102 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8103 			    &multirt_already_resolved, msg_getlabel(mp), ipst);
8104 
8105 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8106 			    "multirt_already_resolved %d, "
8107 			    "multirt_res_attempts %d, multirt_res_failures %d, "
8108 			    "ire %p, sire %p\n", multirt_is_resolvable,
8109 			    multirt_already_resolved, multirt_res_attempts,
8110 			    multirt_res_failures, (void *)ire, (void *)sire));
8111 
8112 			if (!multirt_is_resolvable) {
8113 				/*
8114 				 * No more multirt route to resolve; give up
8115 				 * (all routes resolved or no more
8116 				 * resolvable routes).
8117 				 */
8118 				if (ire != NULL) {
8119 					ire_refrele(ire);
8120 					ire = NULL;
8121 				}
8122 				/*
8123 				 * Generate ICMP error only if all attempts to
8124 				 * resolve multirt route failed and there is no
8125 				 * already resolved one.  Don't generate ICMP
8126 				 * error when:
8127 				 *
8128 				 *  1) there was no attempt to resolve
8129 				 *  2) at least one attempt passed
8130 				 *  3) a multirt route is already resolved
8131 				 *
8132 				 *  Case 1) may occur due to multiple
8133 				 *    resolution attempts during single
8134 				 *    ip_multirt_resolution_interval.
8135 				 *
8136 				 *  Case 2-3) means that CGTP destination is
8137 				 *    reachable via one link so we don't want to
8138 				 *    generate ICMP host unreachable error.
8139 				 */
8140 				if (multirt_res_attempts == 0 ||
8141 				    multirt_res_failures <
8142 				    multirt_res_attempts ||
8143 				    multirt_already_resolved > 0)
8144 					multirt_no_icmp_error = B_TRUE;
8145 			} else {
8146 				ASSERT(sire != NULL);
8147 				ASSERT(ire != NULL);
8148 
8149 				multirt_res_attempts++;
8150 			}
8151 		}
8152 
8153 		if (ire == NULL) {
8154 			if (ip_debug > 3) {
8155 				/* ip2dbg */
8156 				pr_addr_dbg("ip_newroute: "
8157 				    "can't resolve %s\n", AF_INET, &dst);
8158 			}
8159 			ip3dbg(("ip_newroute: "
8160 			    "ire %p, sire %p, multirt_no_icmp_error %d\n",
8161 			    (void *)ire, (void *)sire,
8162 			    (int)multirt_no_icmp_error));
8163 
8164 			if (sire != NULL) {
8165 				ire_refrele(sire);
8166 				sire = NULL;
8167 			}
8168 
8169 			if (multirt_no_icmp_error) {
8170 				/* There is no need to report an ICMP error. */
8171 				MULTIRT_DEBUG_UNTAG(first_mp);
8172 				freemsg(first_mp);
8173 				return;
8174 			}
8175 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8176 			    RTA_DST, ipst);
8177 			goto icmp_err_ret;
8178 		}
8179 
8180 		/*
8181 		 * Verify that the returned IRE does not have either
8182 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8183 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8184 		 */
8185 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8186 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8187 			goto icmp_err_ret;
8188 		}
8189 		/*
8190 		 * Increment the ire_ob_pkt_count field for ire if it is an
8191 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8192 		 * increment the same for the parent IRE, sire, if it is some
8193 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8194 		 */
8195 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8196 			UPDATE_OB_PKT_COUNT(ire);
8197 			ire->ire_last_used_time = lbolt;
8198 		}
8199 
8200 		if (sire != NULL) {
8201 			gw = sire->ire_gateway_addr;
8202 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8203 			    IRE_INTERFACE)) == 0);
8204 			UPDATE_OB_PKT_COUNT(sire);
8205 			sire->ire_last_used_time = lbolt;
8206 		}
8207 		/*
8208 		 * We have a route to reach the destination.  Find the
8209 		 * appropriate ill, then get a source address using
8210 		 * ipif_select_source().
8211 		 *
8212 		 * If we are here trying to create an IRE_CACHE for an offlink
8213 		 * destination and have an IRE_CACHE entry for VNI, then use
8214 		 * ire_stq instead since VNI's queue is a black hole.
8215 		 */
8216 		if ((ire->ire_type == IRE_CACHE) &&
8217 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8218 			dst_ill = ire->ire_stq->q_ptr;
8219 			ill_refhold(dst_ill);
8220 		} else {
8221 			ill_t *ill = ire->ire_ipif->ipif_ill;
8222 
8223 			if (IS_IPMP(ill)) {
8224 				dst_ill =
8225 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8226 			} else {
8227 				dst_ill = ill;
8228 				ill_refhold(dst_ill);
8229 			}
8230 		}
8231 
8232 		if (dst_ill == NULL) {
8233 			if (ip_debug > 2) {
8234 				pr_addr_dbg("ip_newroute: no dst "
8235 				    "ill for dst %s\n", AF_INET, &dst);
8236 			}
8237 			goto icmp_err_ret;
8238 		}
8239 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8240 
8241 		/*
8242 		 * Pick the best source address from dst_ill.
8243 		 *
8244 		 * 1) Try to pick the source address from the destination
8245 		 *    route. Clustering assumes that when we have multiple
8246 		 *    prefixes hosted on an interface, the prefix of the
8247 		 *    source address matches the prefix of the destination
8248 		 *    route. We do this only if the address is not
8249 		 *    DEPRECATED.
8250 		 *
8251 		 * 2) If the conn is in a different zone than the ire, we
8252 		 *    need to pick a source address from the right zone.
8253 		 */
8254 		ASSERT(src_ipif == NULL);
8255 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8256 			/*
8257 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8258 			 * Check that the ipif matching the requested source
8259 			 * address still exists.
8260 			 */
8261 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8262 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8263 		}
8264 
8265 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8266 
8267 		if (src_ipif == NULL &&
8268 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8269 			ire_marks |= IRE_MARK_USESRC_CHECK;
8270 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8271 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8272 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8273 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8274 			    ire->ire_zoneid != ALL_ZONES) ||
8275 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8276 				/*
8277 				 * If the destination is reachable via a
8278 				 * given gateway, the selected source address
8279 				 * should be in the same subnet as the gateway.
8280 				 * Otherwise, the destination is not reachable.
8281 				 *
8282 				 * If there are no interfaces on the same subnet
8283 				 * as the destination, ipif_select_source gives
8284 				 * first non-deprecated interface which might be
8285 				 * on a different subnet than the gateway.
8286 				 * This is not desirable. Hence pass the dst_ire
8287 				 * source address to ipif_select_source.
8288 				 * It is sure that the destination is reachable
8289 				 * with the dst_ire source address subnet.
8290 				 * So passing dst_ire source address to
8291 				 * ipif_select_source will make sure that the
8292 				 * selected source will be on the same subnet
8293 				 * as dst_ire source address.
8294 				 */
8295 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8296 
8297 				src_ipif = ipif_select_source(dst_ill, saddr,
8298 				    zoneid);
8299 				if (src_ipif == NULL) {
8300 					/*
8301 					 * In the case of multirouting, it may
8302 					 * happen that ipif_select_source fails
8303 					 * as DAD may disallow use of the
8304 					 * particular source interface.  Anyway,
8305 					 * we need to continue and attempt to
8306 					 * resolve other multirt routes.
8307 					 */
8308 					if ((sire != NULL) &&
8309 					    (sire->ire_flags & RTF_MULTIRT)) {
8310 						ire_refrele(ire);
8311 						ire = NULL;
8312 						multirt_resolve_next = B_TRUE;
8313 						multirt_res_failures++;
8314 						continue;
8315 					}
8316 
8317 					if (ip_debug > 2) {
8318 						pr_addr_dbg("ip_newroute: "
8319 						    "no src for dst %s ",
8320 						    AF_INET, &dst);
8321 						printf("on interface %s\n",
8322 						    dst_ill->ill_name);
8323 					}
8324 					goto icmp_err_ret;
8325 				}
8326 			} else {
8327 				src_ipif = ire->ire_ipif;
8328 				ASSERT(src_ipif != NULL);
8329 				/* hold src_ipif for uniformity */
8330 				ipif_refhold(src_ipif);
8331 			}
8332 		}
8333 
8334 		/*
8335 		 * Assign a source address while we have the conn.
8336 		 * We can't have ip_wput_ire pick a source address when the
8337 		 * packet returns from arp since we need to look at
8338 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8339 		 * going through arp.
8340 		 *
8341 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8342 		 *	  it uses ip6i to store this information.
8343 		 */
8344 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8345 			ipha->ipha_src = src_ipif->ipif_src_addr;
8346 
8347 		if (ip_debug > 3) {
8348 			/* ip2dbg */
8349 			pr_addr_dbg("ip_newroute: first hop %s\n",
8350 			    AF_INET, &gw);
8351 		}
8352 		ip2dbg(("\tire type %s (%d)\n",
8353 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8354 
8355 		/*
8356 		 * The TTL of multirouted packets is bounded by the
8357 		 * ip_multirt_ttl ndd variable.
8358 		 */
8359 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8360 			/* Force TTL of multirouted packets */
8361 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8362 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8363 				ip2dbg(("ip_newroute: forcing multirt TTL "
8364 				    "to %d (was %d), dst 0x%08x\n",
8365 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8366 				    ntohl(sire->ire_addr)));
8367 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8368 			}
8369 		}
8370 		/*
8371 		 * At this point in ip_newroute(), ire is either the
8372 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8373 		 * destination or an IRE_INTERFACE type that should be used
8374 		 * to resolve an on-subnet destination or an on-subnet
8375 		 * next-hop gateway.
8376 		 *
8377 		 * In the IRE_CACHE case, we have the following :
8378 		 *
8379 		 * 1) src_ipif - used for getting a source address.
8380 		 *
8381 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8382 		 *    means packets using this IRE_CACHE will go out on
8383 		 *    dst_ill.
8384 		 *
8385 		 * 3) The IRE sire will point to the prefix that is the
8386 		 *    longest  matching route for the destination. These
8387 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8388 		 *
8389 		 *    The newly created IRE_CACHE entry for the off-subnet
8390 		 *    destination is tied to both the prefix route and the
8391 		 *    interface route used to resolve the next-hop gateway
8392 		 *    via the ire_phandle and ire_ihandle fields,
8393 		 *    respectively.
8394 		 *
8395 		 * In the IRE_INTERFACE case, we have the following :
8396 		 *
8397 		 * 1) src_ipif - used for getting a source address.
8398 		 *
8399 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8400 		 *    means packets using the IRE_CACHE that we will build
8401 		 *    here will go out on dst_ill.
8402 		 *
8403 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8404 		 *    to be created will only be tied to the IRE_INTERFACE
8405 		 *    that was derived from the ire_ihandle field.
8406 		 *
8407 		 *    If sire is non-NULL, it means the destination is
8408 		 *    off-link and we will first create the IRE_CACHE for the
8409 		 *    gateway. Next time through ip_newroute, we will create
8410 		 *    the IRE_CACHE for the final destination as described
8411 		 *    above.
8412 		 *
8413 		 * In both cases, after the current resolution has been
8414 		 * completed (or possibly initialised, in the IRE_INTERFACE
8415 		 * case), the loop may be re-entered to attempt the resolution
8416 		 * of another RTF_MULTIRT route.
8417 		 *
8418 		 * When an IRE_CACHE entry for the off-subnet destination is
8419 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8420 		 * for further processing in emission loops.
8421 		 */
8422 		save_ire = ire;
8423 		switch (ire->ire_type) {
8424 		case IRE_CACHE: {
8425 			ire_t	*ipif_ire;
8426 
8427 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8428 			if (gw == 0)
8429 				gw = ire->ire_gateway_addr;
8430 			/*
8431 			 * We need 3 ire's to create a new cache ire for an
8432 			 * off-link destination from the cache ire of the
8433 			 * gateway.
8434 			 *
8435 			 *	1. The prefix ire 'sire' (Note that this does
8436 			 *	   not apply to the conn_nexthop_set case)
8437 			 *	2. The cache ire of the gateway 'ire'
8438 			 *	3. The interface ire 'ipif_ire'
8439 			 *
8440 			 * We have (1) and (2). We lookup (3) below.
8441 			 *
8442 			 * If there is no interface route to the gateway,
8443 			 * it is a race condition, where we found the cache
8444 			 * but the interface route has been deleted.
8445 			 */
8446 			if (ip_nexthop) {
8447 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8448 			} else {
8449 				ipif_ire =
8450 				    ire_ihandle_lookup_offlink(ire, sire);
8451 			}
8452 			if (ipif_ire == NULL) {
8453 				ip1dbg(("ip_newroute: "
8454 				    "ire_ihandle_lookup_offlink failed\n"));
8455 				goto icmp_err_ret;
8456 			}
8457 
8458 			/*
8459 			 * Check cached gateway IRE for any security
8460 			 * attributes; if found, associate the gateway
8461 			 * credentials group to the destination IRE.
8462 			 */
8463 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8464 				mutex_enter(&attrp->igsa_lock);
8465 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8466 					GCGRP_REFHOLD(gcgrp);
8467 				mutex_exit(&attrp->igsa_lock);
8468 			}
8469 
8470 			/*
8471 			 * XXX For the source of the resolver mp,
8472 			 * we are using the same DL_UNITDATA_REQ
8473 			 * (from save_ire->ire_nce->nce_res_mp)
8474 			 * though the save_ire is not pointing at the same ill.
8475 			 * This is incorrect. We need to send it up to the
8476 			 * resolver to get the right res_mp. For ethernets
8477 			 * this may be okay (ill_type == DL_ETHER).
8478 			 */
8479 
8480 			ire = ire_create(
8481 			    (uchar_t *)&dst,		/* dest address */
8482 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8483 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8484 			    (uchar_t *)&gw,		/* gateway address */
8485 			    &save_ire->ire_max_frag,
8486 			    save_ire->ire_nce,		/* src nce */
8487 			    dst_ill->ill_rq,		/* recv-from queue */
8488 			    dst_ill->ill_wq,		/* send-to queue */
8489 			    IRE_CACHE,			/* IRE type */
8490 			    src_ipif,
8491 			    (sire != NULL) ?
8492 			    sire->ire_mask : 0, 	/* Parent mask */
8493 			    (sire != NULL) ?
8494 			    sire->ire_phandle : 0,	/* Parent handle */
8495 			    ipif_ire->ire_ihandle,	/* Interface handle */
8496 			    (sire != NULL) ? (sire->ire_flags &
8497 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8498 			    (sire != NULL) ?
8499 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8500 			    NULL,
8501 			    gcgrp,
8502 			    ipst);
8503 
8504 			if (ire == NULL) {
8505 				if (gcgrp != NULL) {
8506 					GCGRP_REFRELE(gcgrp);
8507 					gcgrp = NULL;
8508 				}
8509 				ire_refrele(ipif_ire);
8510 				ire_refrele(save_ire);
8511 				break;
8512 			}
8513 
8514 			/* reference now held by IRE */
8515 			gcgrp = NULL;
8516 
8517 			ire->ire_marks |= ire_marks;
8518 
8519 			/*
8520 			 * Prevent sire and ipif_ire from getting deleted.
8521 			 * The newly created ire is tied to both of them via
8522 			 * the phandle and ihandle respectively.
8523 			 */
8524 			if (sire != NULL) {
8525 				IRB_REFHOLD(sire->ire_bucket);
8526 				/* Has it been removed already ? */
8527 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8528 					IRB_REFRELE(sire->ire_bucket);
8529 					ire_refrele(ipif_ire);
8530 					ire_refrele(save_ire);
8531 					break;
8532 				}
8533 			}
8534 
8535 			IRB_REFHOLD(ipif_ire->ire_bucket);
8536 			/* Has it been removed already ? */
8537 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8538 				IRB_REFRELE(ipif_ire->ire_bucket);
8539 				if (sire != NULL)
8540 					IRB_REFRELE(sire->ire_bucket);
8541 				ire_refrele(ipif_ire);
8542 				ire_refrele(save_ire);
8543 				break;
8544 			}
8545 
8546 			xmit_mp = first_mp;
8547 			/*
8548 			 * In the case of multirouting, a copy
8549 			 * of the packet is done before its sending.
8550 			 * The copy is used to attempt another
8551 			 * route resolution, in a next loop.
8552 			 */
8553 			if (ire->ire_flags & RTF_MULTIRT) {
8554 				copy_mp = copymsg(first_mp);
8555 				if (copy_mp != NULL) {
8556 					xmit_mp = copy_mp;
8557 					MULTIRT_DEBUG_TAG(first_mp);
8558 				}
8559 			}
8560 
8561 			ire_add_then_send(q, ire, xmit_mp);
8562 			ire_refrele(save_ire);
8563 
8564 			/* Assert that sire is not deleted yet. */
8565 			if (sire != NULL) {
8566 				ASSERT(sire->ire_ptpn != NULL);
8567 				IRB_REFRELE(sire->ire_bucket);
8568 			}
8569 
8570 			/* Assert that ipif_ire is not deleted yet. */
8571 			ASSERT(ipif_ire->ire_ptpn != NULL);
8572 			IRB_REFRELE(ipif_ire->ire_bucket);
8573 			ire_refrele(ipif_ire);
8574 
8575 			/*
8576 			 * If copy_mp is not NULL, multirouting was
8577 			 * requested. We loop to initiate a next
8578 			 * route resolution attempt, starting from sire.
8579 			 */
8580 			if (copy_mp != NULL) {
8581 				/*
8582 				 * Search for the next unresolved
8583 				 * multirt route.
8584 				 */
8585 				copy_mp = NULL;
8586 				ipif_ire = NULL;
8587 				ire = NULL;
8588 				multirt_resolve_next = B_TRUE;
8589 				continue;
8590 			}
8591 			if (sire != NULL)
8592 				ire_refrele(sire);
8593 			ipif_refrele(src_ipif);
8594 			ill_refrele(dst_ill);
8595 			return;
8596 		}
8597 		case IRE_IF_NORESOLVER: {
8598 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8599 			    dst_ill->ill_resolver_mp == NULL) {
8600 				ip1dbg(("ip_newroute: dst_ill %p "
8601 				    "for IRE_IF_NORESOLVER ire %p has "
8602 				    "no ill_resolver_mp\n",
8603 				    (void *)dst_ill, (void *)ire));
8604 				break;
8605 			}
8606 
8607 			/*
8608 			 * TSol note: We are creating the ire cache for the
8609 			 * destination 'dst'. If 'dst' is offlink, going
8610 			 * through the first hop 'gw', the security attributes
8611 			 * of 'dst' must be set to point to the gateway
8612 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8613 			 * is possible that 'dst' is a potential gateway that is
8614 			 * referenced by some route that has some security
8615 			 * attributes. Thus in the former case, we need to do a
8616 			 * gcgrp_lookup of 'gw' while in the latter case we
8617 			 * need to do gcgrp_lookup of 'dst' itself.
8618 			 */
8619 			ga.ga_af = AF_INET;
8620 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8621 			    &ga.ga_addr);
8622 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8623 
8624 			ire = ire_create(
8625 			    (uchar_t *)&dst,		/* dest address */
8626 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8627 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8628 			    (uchar_t *)&gw,		/* gateway address */
8629 			    &save_ire->ire_max_frag,
8630 			    NULL,			/* no src nce */
8631 			    dst_ill->ill_rq,		/* recv-from queue */
8632 			    dst_ill->ill_wq,		/* send-to queue */
8633 			    IRE_CACHE,
8634 			    src_ipif,
8635 			    save_ire->ire_mask,		/* Parent mask */
8636 			    (sire != NULL) ?		/* Parent handle */
8637 			    sire->ire_phandle : 0,
8638 			    save_ire->ire_ihandle,	/* Interface handle */
8639 			    (sire != NULL) ? sire->ire_flags &
8640 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8641 			    &(save_ire->ire_uinfo),
8642 			    NULL,
8643 			    gcgrp,
8644 			    ipst);
8645 
8646 			if (ire == NULL) {
8647 				if (gcgrp != NULL) {
8648 					GCGRP_REFRELE(gcgrp);
8649 					gcgrp = NULL;
8650 				}
8651 				ire_refrele(save_ire);
8652 				break;
8653 			}
8654 
8655 			/* reference now held by IRE */
8656 			gcgrp = NULL;
8657 
8658 			ire->ire_marks |= ire_marks;
8659 
8660 			/* Prevent save_ire from getting deleted */
8661 			IRB_REFHOLD(save_ire->ire_bucket);
8662 			/* Has it been removed already ? */
8663 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8664 				IRB_REFRELE(save_ire->ire_bucket);
8665 				ire_refrele(save_ire);
8666 				break;
8667 			}
8668 
8669 			/*
8670 			 * In the case of multirouting, a copy
8671 			 * of the packet is made before it is sent.
8672 			 * The copy is used in the next
8673 			 * loop to attempt another resolution.
8674 			 */
8675 			xmit_mp = first_mp;
8676 			if ((sire != NULL) &&
8677 			    (sire->ire_flags & RTF_MULTIRT)) {
8678 				copy_mp = copymsg(first_mp);
8679 				if (copy_mp != NULL) {
8680 					xmit_mp = copy_mp;
8681 					MULTIRT_DEBUG_TAG(first_mp);
8682 				}
8683 			}
8684 			ire_add_then_send(q, ire, xmit_mp);
8685 
8686 			/* Assert that it is not deleted yet. */
8687 			ASSERT(save_ire->ire_ptpn != NULL);
8688 			IRB_REFRELE(save_ire->ire_bucket);
8689 			ire_refrele(save_ire);
8690 
8691 			if (copy_mp != NULL) {
8692 				/*
8693 				 * If we found a (no)resolver, we ignore any
8694 				 * trailing top priority IRE_CACHE in further
8695 				 * loops. This ensures that we do not omit any
8696 				 * (no)resolver.
8697 				 * This IRE_CACHE, if any, will be processed
8698 				 * by another thread entering ip_newroute().
8699 				 * IRE_CACHE entries, if any, will be processed
8700 				 * by another thread entering ip_newroute(),
8701 				 * (upon resolver response, for instance).
8702 				 * This aims to force parallel multirt
8703 				 * resolutions as soon as a packet must be sent.
8704 				 * In the best case, after the tx of only one
8705 				 * packet, all reachable routes are resolved.
8706 				 * Otherwise, the resolution of all RTF_MULTIRT
8707 				 * routes would require several emissions.
8708 				 */
8709 				multirt_flags &= ~MULTIRT_CACHEGW;
8710 
8711 				/*
8712 				 * Search for the next unresolved multirt
8713 				 * route.
8714 				 */
8715 				copy_mp = NULL;
8716 				save_ire = NULL;
8717 				ire = NULL;
8718 				multirt_resolve_next = B_TRUE;
8719 				continue;
8720 			}
8721 
8722 			/*
8723 			 * Don't need sire anymore
8724 			 */
8725 			if (sire != NULL)
8726 				ire_refrele(sire);
8727 
8728 			ipif_refrele(src_ipif);
8729 			ill_refrele(dst_ill);
8730 			return;
8731 		}
8732 		case IRE_IF_RESOLVER:
8733 			/*
8734 			 * We can't build an IRE_CACHE yet, but at least we
8735 			 * found a resolver that can help.
8736 			 */
8737 			res_mp = dst_ill->ill_resolver_mp;
8738 			if (!OK_RESOLVER_MP(res_mp))
8739 				break;
8740 
8741 			/*
8742 			 * To be at this point in the code with a non-zero gw
8743 			 * means that dst is reachable through a gateway that
8744 			 * we have never resolved.  By changing dst to the gw
8745 			 * addr we resolve the gateway first.
8746 			 * When ire_add_then_send() tries to put the IP dg
8747 			 * to dst, it will reenter ip_newroute() at which
8748 			 * time we will find the IRE_CACHE for the gw and
8749 			 * create another IRE_CACHE in case IRE_CACHE above.
8750 			 */
8751 			if (gw != INADDR_ANY) {
8752 				/*
8753 				 * The source ipif that was determined above was
8754 				 * relative to the destination address, not the
8755 				 * gateway's. If src_ipif was not taken out of
8756 				 * the IRE_IF_RESOLVER entry, we'll need to call
8757 				 * ipif_select_source() again.
8758 				 */
8759 				if (src_ipif != ire->ire_ipif) {
8760 					ipif_refrele(src_ipif);
8761 					src_ipif = ipif_select_source(dst_ill,
8762 					    gw, zoneid);
8763 					/*
8764 					 * In the case of multirouting, it may
8765 					 * happen that ipif_select_source fails
8766 					 * as DAD may disallow use of the
8767 					 * particular source interface.  Anyway,
8768 					 * we need to continue and attempt to
8769 					 * resolve other multirt routes.
8770 					 */
8771 					if (src_ipif == NULL) {
8772 						if (sire != NULL &&
8773 						    (sire->ire_flags &
8774 						    RTF_MULTIRT)) {
8775 							ire_refrele(ire);
8776 							ire = NULL;
8777 							multirt_resolve_next =
8778 							    B_TRUE;
8779 							multirt_res_failures++;
8780 							continue;
8781 						}
8782 						if (ip_debug > 2) {
8783 							pr_addr_dbg(
8784 							    "ip_newroute: no "
8785 							    "src for gw %s ",
8786 							    AF_INET, &gw);
8787 							printf("on "
8788 							    "interface %s\n",
8789 							    dst_ill->ill_name);
8790 						}
8791 						goto icmp_err_ret;
8792 					}
8793 				}
8794 				save_dst = dst;
8795 				dst = gw;
8796 				gw = INADDR_ANY;
8797 			}
8798 
8799 			/*
8800 			 * We obtain a partial IRE_CACHE which we will pass
8801 			 * along with the resolver query.  When the response
8802 			 * comes back it will be there ready for us to add.
8803 			 * The ire_max_frag is atomically set under the
8804 			 * irebucket lock in ire_add_v[46].
8805 			 */
8806 
8807 			ire = ire_create_mp(
8808 			    (uchar_t *)&dst,		/* dest address */
8809 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8810 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8811 			    (uchar_t *)&gw,		/* gateway address */
8812 			    NULL,			/* ire_max_frag */
8813 			    NULL,			/* no src nce */
8814 			    dst_ill->ill_rq,		/* recv-from queue */
8815 			    dst_ill->ill_wq,		/* send-to queue */
8816 			    IRE_CACHE,
8817 			    src_ipif,			/* Interface ipif */
8818 			    save_ire->ire_mask,		/* Parent mask */
8819 			    0,
8820 			    save_ire->ire_ihandle,	/* Interface handle */
8821 			    0,				/* flags if any */
8822 			    &(save_ire->ire_uinfo),
8823 			    NULL,
8824 			    NULL,
8825 			    ipst);
8826 
8827 			if (ire == NULL) {
8828 				ire_refrele(save_ire);
8829 				break;
8830 			}
8831 
8832 			if ((sire != NULL) &&
8833 			    (sire->ire_flags & RTF_MULTIRT)) {
8834 				copy_mp = copymsg(first_mp);
8835 				if (copy_mp != NULL)
8836 					MULTIRT_DEBUG_TAG(copy_mp);
8837 			}
8838 
8839 			ire->ire_marks |= ire_marks;
8840 
8841 			/*
8842 			 * Construct message chain for the resolver
8843 			 * of the form:
8844 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8845 			 * Packet could contain a IPSEC_OUT mp.
8846 			 *
8847 			 * NOTE : ire will be added later when the response
8848 			 * comes back from ARP. If the response does not
8849 			 * come back, ARP frees the packet. For this reason,
8850 			 * we can't REFHOLD the bucket of save_ire to prevent
8851 			 * deletions. We may not be able to REFRELE the bucket
8852 			 * if the response never comes back. Thus, before
8853 			 * adding the ire, ire_add_v4 will make sure that the
8854 			 * interface route does not get deleted. This is the
8855 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8856 			 * where we can always prevent deletions because of
8857 			 * the synchronous nature of adding IRES i.e
8858 			 * ire_add_then_send is called after creating the IRE.
8859 			 */
8860 			ASSERT(ire->ire_mp != NULL);
8861 			ire->ire_mp->b_cont = first_mp;
8862 			/* Have saved_mp handy, for cleanup if canput fails */
8863 			saved_mp = mp;
8864 			mp = copyb(res_mp);
8865 			if (mp == NULL) {
8866 				/* Prepare for cleanup */
8867 				mp = saved_mp; /* pkt */
8868 				ire_delete(ire); /* ire_mp */
8869 				ire = NULL;
8870 				ire_refrele(save_ire);
8871 				if (copy_mp != NULL) {
8872 					MULTIRT_DEBUG_UNTAG(copy_mp);
8873 					freemsg(copy_mp);
8874 					copy_mp = NULL;
8875 				}
8876 				break;
8877 			}
8878 			linkb(mp, ire->ire_mp);
8879 
8880 			/*
8881 			 * Fill in the source and dest addrs for the resolver.
8882 			 * NOTE: this depends on memory layouts imposed by
8883 			 * ill_init().
8884 			 */
8885 			areq = (areq_t *)mp->b_rptr;
8886 			addrp = (ipaddr_t *)((char *)areq +
8887 			    areq->areq_sender_addr_offset);
8888 			*addrp = save_ire->ire_src_addr;
8889 
8890 			ire_refrele(save_ire);
8891 			addrp = (ipaddr_t *)((char *)areq +
8892 			    areq->areq_target_addr_offset);
8893 			*addrp = dst;
8894 			/* Up to the resolver. */
8895 			if (canputnext(dst_ill->ill_rq) &&
8896 			    !(dst_ill->ill_arp_closing)) {
8897 				putnext(dst_ill->ill_rq, mp);
8898 				ire = NULL;
8899 				if (copy_mp != NULL) {
8900 					/*
8901 					 * If we found a resolver, we ignore
8902 					 * any trailing top priority IRE_CACHE
8903 					 * in the further loops. This ensures
8904 					 * that we do not omit any resolver.
8905 					 * IRE_CACHE entries, if any, will be
8906 					 * processed next time we enter
8907 					 * ip_newroute().
8908 					 */
8909 					multirt_flags &= ~MULTIRT_CACHEGW;
8910 					/*
8911 					 * Search for the next unresolved
8912 					 * multirt route.
8913 					 */
8914 					first_mp = copy_mp;
8915 					copy_mp = NULL;
8916 					/* Prepare the next resolution loop. */
8917 					mp = first_mp;
8918 					EXTRACT_PKT_MP(mp, first_mp,
8919 					    mctl_present);
8920 					if (mctl_present)
8921 						io = (ipsec_out_t *)
8922 						    first_mp->b_rptr;
8923 					ipha = (ipha_t *)mp->b_rptr;
8924 
8925 					ASSERT(sire != NULL);
8926 
8927 					dst = save_dst;
8928 					multirt_resolve_next = B_TRUE;
8929 					continue;
8930 				}
8931 
8932 				if (sire != NULL)
8933 					ire_refrele(sire);
8934 
8935 				/*
8936 				 * The response will come back in ip_wput
8937 				 * with db_type IRE_DB_TYPE.
8938 				 */
8939 				ipif_refrele(src_ipif);
8940 				ill_refrele(dst_ill);
8941 				return;
8942 			} else {
8943 				/* Prepare for cleanup */
8944 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8945 				    mp);
8946 				mp->b_cont = NULL;
8947 				freeb(mp); /* areq */
8948 				/*
8949 				 * this is an ire that is not added to the
8950 				 * cache. ire_freemblk will handle the release
8951 				 * of any resources associated with the ire.
8952 				 */
8953 				ire_delete(ire); /* ire_mp */
8954 				mp = saved_mp; /* pkt */
8955 				ire = NULL;
8956 				if (copy_mp != NULL) {
8957 					MULTIRT_DEBUG_UNTAG(copy_mp);
8958 					freemsg(copy_mp);
8959 					copy_mp = NULL;
8960 				}
8961 				break;
8962 			}
8963 		default:
8964 			break;
8965 		}
8966 	} while (multirt_resolve_next);
8967 
8968 	ip1dbg(("ip_newroute: dropped\n"));
8969 	/* Did this packet originate externally? */
8970 	if (mp->b_prev) {
8971 		mp->b_next = NULL;
8972 		mp->b_prev = NULL;
8973 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8974 	} else {
8975 		if (dst_ill != NULL) {
8976 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8977 		} else {
8978 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8979 		}
8980 	}
8981 	ASSERT(copy_mp == NULL);
8982 	MULTIRT_DEBUG_UNTAG(first_mp);
8983 	freemsg(first_mp);
8984 	if (ire != NULL)
8985 		ire_refrele(ire);
8986 	if (sire != NULL)
8987 		ire_refrele(sire);
8988 	if (src_ipif != NULL)
8989 		ipif_refrele(src_ipif);
8990 	if (dst_ill != NULL)
8991 		ill_refrele(dst_ill);
8992 	return;
8993 
8994 icmp_err_ret:
8995 	ip1dbg(("ip_newroute: no route\n"));
8996 	if (src_ipif != NULL)
8997 		ipif_refrele(src_ipif);
8998 	if (dst_ill != NULL)
8999 		ill_refrele(dst_ill);
9000 	if (sire != NULL)
9001 		ire_refrele(sire);
9002 	/* Did this packet originate externally? */
9003 	if (mp->b_prev) {
9004 		mp->b_next = NULL;
9005 		mp->b_prev = NULL;
9006 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9007 		q = WR(q);
9008 	} else {
9009 		/*
9010 		 * There is no outgoing ill, so just increment the
9011 		 * system MIB.
9012 		 */
9013 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9014 		/*
9015 		 * Since ip_wput() isn't close to finished, we fill
9016 		 * in enough of the header for credible error reporting.
9017 		 */
9018 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9019 			/* Failed */
9020 			MULTIRT_DEBUG_UNTAG(first_mp);
9021 			freemsg(first_mp);
9022 			if (ire != NULL)
9023 				ire_refrele(ire);
9024 			return;
9025 		}
9026 	}
9027 
9028 	/*
9029 	 * At this point we will have ire only if RTF_BLACKHOLE
9030 	 * or RTF_REJECT flags are set on the IRE. It will not
9031 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9032 	 */
9033 	if (ire != NULL) {
9034 		if (ire->ire_flags & RTF_BLACKHOLE) {
9035 			ire_refrele(ire);
9036 			MULTIRT_DEBUG_UNTAG(first_mp);
9037 			freemsg(first_mp);
9038 			return;
9039 		}
9040 		ire_refrele(ire);
9041 	}
9042 	if (ip_source_routed(ipha, ipst)) {
9043 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9044 		    zoneid, ipst);
9045 		return;
9046 	}
9047 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9048 }
9049 
9050 ip_opt_info_t zero_info;
9051 
9052 /*
9053  * IPv4 -
9054  * ip_newroute_ipif is called by ip_wput_multicast and
9055  * ip_rput_forward_multicast whenever we need to send
9056  * out a packet to a destination address for which we do not have specific
9057  * routing information. It is used when the packet will be sent out
9058  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
9059  * socket option is set or icmp error message wants to go out on a particular
9060  * interface for a unicast packet.
9061  *
9062  * In most cases, the destination address is resolved thanks to the ipif
9063  * intrinsic resolver. However, there are some cases where the call to
9064  * ip_newroute_ipif must take into account the potential presence of
9065  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9066  * that uses the interface. This is specified through flags,
9067  * which can be a combination of:
9068  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9069  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9070  *   and flags. Additionally, the packet source address has to be set to
9071  *   the specified address. The caller is thus expected to set this flag
9072  *   if the packet has no specific source address yet.
9073  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9074  *   flag, the resulting ire will inherit the flag. All unresolved routes
9075  *   to the destination must be explored in the same call to
9076  *   ip_newroute_ipif().
9077  */
9078 static void
9079 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9080     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9081 {
9082 	areq_t	*areq;
9083 	ire_t	*ire = NULL;
9084 	mblk_t	*res_mp;
9085 	ipaddr_t *addrp;
9086 	mblk_t *first_mp;
9087 	ire_t	*save_ire = NULL;
9088 	ipif_t	*src_ipif = NULL;
9089 	ushort_t ire_marks = 0;
9090 	ill_t	*dst_ill = NULL;
9091 	ipha_t *ipha;
9092 	mblk_t	*saved_mp;
9093 	ire_t   *fire = NULL;
9094 	mblk_t  *copy_mp = NULL;
9095 	boolean_t multirt_resolve_next;
9096 	boolean_t unspec_src;
9097 	ipaddr_t ipha_dst;
9098 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9099 
9100 	/*
9101 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9102 	 * here for uniformity
9103 	 */
9104 	ipif_refhold(ipif);
9105 
9106 	/*
9107 	 * This loop is run only once in most cases.
9108 	 * We loop to resolve further routes only when the destination
9109 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9110 	 */
9111 	do {
9112 		if (dst_ill != NULL) {
9113 			ill_refrele(dst_ill);
9114 			dst_ill = NULL;
9115 		}
9116 		if (src_ipif != NULL) {
9117 			ipif_refrele(src_ipif);
9118 			src_ipif = NULL;
9119 		}
9120 		multirt_resolve_next = B_FALSE;
9121 
9122 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9123 		    ipif->ipif_ill->ill_name));
9124 
9125 		first_mp = mp;
9126 		if (DB_TYPE(mp) == M_CTL)
9127 			mp = mp->b_cont;
9128 		ipha = (ipha_t *)mp->b_rptr;
9129 
9130 		/*
9131 		 * Save the packet destination address, we may need it after
9132 		 * the packet has been consumed.
9133 		 */
9134 		ipha_dst = ipha->ipha_dst;
9135 
9136 		/*
9137 		 * If the interface is a pt-pt interface we look for an
9138 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9139 		 * local_address and the pt-pt destination address. Otherwise
9140 		 * we just match the local address.
9141 		 * NOTE: dst could be different than ipha->ipha_dst in case
9142 		 * of sending igmp multicast packets over a point-to-point
9143 		 * connection.
9144 		 * Thus we must be careful enough to check ipha_dst to be a
9145 		 * multicast address, otherwise it will take xmit_if path for
9146 		 * multicast packets resulting into kernel stack overflow by
9147 		 * repeated calls to ip_newroute_ipif from ire_send().
9148 		 */
9149 		if (CLASSD(ipha_dst) &&
9150 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9151 			goto err_ret;
9152 		}
9153 
9154 		/*
9155 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9156 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9157 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9158 		 * propagate its flags to the new ire.
9159 		 */
9160 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9161 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9162 			ip2dbg(("ip_newroute_ipif: "
9163 			    "ipif_lookup_multi_ire("
9164 			    "ipif %p, dst %08x) = fire %p\n",
9165 			    (void *)ipif, ntohl(dst), (void *)fire));
9166 		}
9167 
9168 		/*
9169 		 * Note: While we pick a dst_ill we are really only
9170 		 * interested in the ill for load spreading. The source
9171 		 * ipif is determined by source address selection below.
9172 		 */
9173 		if (IS_IPMP(ipif->ipif_ill)) {
9174 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9175 
9176 			if (CLASSD(ipha_dst))
9177 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9178 			else
9179 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9180 		} else {
9181 			dst_ill = ipif->ipif_ill;
9182 			ill_refhold(dst_ill);
9183 		}
9184 
9185 		if (dst_ill == NULL) {
9186 			if (ip_debug > 2) {
9187 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9188 				    "for dst %s\n", AF_INET, &dst);
9189 			}
9190 			goto err_ret;
9191 		}
9192 
9193 		/*
9194 		 * Pick a source address preferring non-deprecated ones.
9195 		 * Unlike ip_newroute, we don't do any source address
9196 		 * selection here since for multicast it really does not help
9197 		 * in inbound load spreading as in the unicast case.
9198 		 */
9199 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9200 		    (fire->ire_flags & RTF_SETSRC)) {
9201 			/*
9202 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9203 			 * on that interface. This ire has RTF_SETSRC flag, so
9204 			 * the source address of the packet must be changed.
9205 			 * Check that the ipif matching the requested source
9206 			 * address still exists.
9207 			 */
9208 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9209 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9210 		}
9211 
9212 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9213 
9214 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9215 		    (IS_IPMP(ipif->ipif_ill) ||
9216 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9217 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9218 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9219 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9220 		    (src_ipif == NULL) &&
9221 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9222 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9223 			if (src_ipif == NULL) {
9224 				if (ip_debug > 2) {
9225 					/* ip1dbg */
9226 					pr_addr_dbg("ip_newroute_ipif: "
9227 					    "no src for dst %s",
9228 					    AF_INET, &dst);
9229 				}
9230 				ip1dbg((" on interface %s\n",
9231 				    dst_ill->ill_name));
9232 				goto err_ret;
9233 			}
9234 			ipif_refrele(ipif);
9235 			ipif = src_ipif;
9236 			ipif_refhold(ipif);
9237 		}
9238 		if (src_ipif == NULL) {
9239 			src_ipif = ipif;
9240 			ipif_refhold(src_ipif);
9241 		}
9242 
9243 		/*
9244 		 * Assign a source address while we have the conn.
9245 		 * We can't have ip_wput_ire pick a source address when the
9246 		 * packet returns from arp since conn_unspec_src might be set
9247 		 * and we lose the conn when going through arp.
9248 		 */
9249 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9250 			ipha->ipha_src = src_ipif->ipif_src_addr;
9251 
9252 		/*
9253 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9254 		 * that the outgoing interface does not have an interface ire.
9255 		 */
9256 		if (CLASSD(ipha_dst) && (connp == NULL ||
9257 		    connp->conn_outgoing_ill == NULL) &&
9258 		    infop->ip_opt_ill_index == 0) {
9259 			/* ipif_to_ire returns an held ire */
9260 			ire = ipif_to_ire(ipif);
9261 			if (ire == NULL)
9262 				goto err_ret;
9263 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9264 				goto err_ret;
9265 			save_ire = ire;
9266 
9267 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9268 			    "flags %04x\n",
9269 			    (void *)ire, (void *)ipif, flags));
9270 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9271 			    (fire->ire_flags & RTF_MULTIRT)) {
9272 				/*
9273 				 * As requested by flags, an IRE_OFFSUBNET was
9274 				 * looked up on that interface. This ire has
9275 				 * RTF_MULTIRT flag, so the resolution loop will
9276 				 * be re-entered to resolve additional routes on
9277 				 * other interfaces. For that purpose, a copy of
9278 				 * the packet is performed at this point.
9279 				 */
9280 				fire->ire_last_used_time = lbolt;
9281 				copy_mp = copymsg(first_mp);
9282 				if (copy_mp) {
9283 					MULTIRT_DEBUG_TAG(copy_mp);
9284 				}
9285 			}
9286 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9287 			    (fire->ire_flags & RTF_SETSRC)) {
9288 				/*
9289 				 * As requested by flags, an IRE_OFFSUBET was
9290 				 * looked up on that interface. This ire has
9291 				 * RTF_SETSRC flag, so the source address of the
9292 				 * packet must be changed.
9293 				 */
9294 				ipha->ipha_src = fire->ire_src_addr;
9295 			}
9296 		} else {
9297 			/*
9298 			 * The only ways we can come here are:
9299 			 * 1) IP_BOUND_IF socket option is set
9300 			 * 2) SO_DONTROUTE socket option is set
9301 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9302 			 * In all cases, the new ire will not be added
9303 			 * into cache table.
9304 			 */
9305 			ASSERT(connp == NULL || connp->conn_dontroute ||
9306 			    connp->conn_outgoing_ill != NULL ||
9307 			    infop->ip_opt_ill_index != 0);
9308 			ire_marks |= IRE_MARK_NOADD;
9309 		}
9310 
9311 		switch (ipif->ipif_net_type) {
9312 		case IRE_IF_NORESOLVER: {
9313 			/* We have what we need to build an IRE_CACHE. */
9314 
9315 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9316 			    (dst_ill->ill_resolver_mp == NULL)) {
9317 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9318 				    "for IRE_IF_NORESOLVER ire %p has "
9319 				    "no ill_resolver_mp\n",
9320 				    (void *)dst_ill, (void *)ire));
9321 				break;
9322 			}
9323 
9324 			/*
9325 			 * The new ire inherits the IRE_OFFSUBNET flags
9326 			 * and source address, if this was requested.
9327 			 */
9328 			ire = ire_create(
9329 			    (uchar_t *)&dst,		/* dest address */
9330 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9331 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9332 			    NULL,			/* gateway address */
9333 			    &ipif->ipif_mtu,
9334 			    NULL,			/* no src nce */
9335 			    dst_ill->ill_rq,		/* recv-from queue */
9336 			    dst_ill->ill_wq,		/* send-to queue */
9337 			    IRE_CACHE,
9338 			    src_ipif,
9339 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9340 			    (fire != NULL) ?		/* Parent handle */
9341 			    fire->ire_phandle : 0,
9342 			    (save_ire != NULL) ?	/* Interface handle */
9343 			    save_ire->ire_ihandle : 0,
9344 			    (fire != NULL) ?
9345 			    (fire->ire_flags &
9346 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9347 			    (save_ire == NULL ? &ire_uinfo_null :
9348 			    &save_ire->ire_uinfo),
9349 			    NULL,
9350 			    NULL,
9351 			    ipst);
9352 
9353 			if (ire == NULL) {
9354 				if (save_ire != NULL)
9355 					ire_refrele(save_ire);
9356 				break;
9357 			}
9358 
9359 			ire->ire_marks |= ire_marks;
9360 
9361 			/*
9362 			 * If IRE_MARK_NOADD is set then we need to convert
9363 			 * the max_fragp to a useable value now. This is
9364 			 * normally done in ire_add_v[46]. We also need to
9365 			 * associate the ire with an nce (normally would be
9366 			 * done in ip_wput_nondata()).
9367 			 *
9368 			 * Note that IRE_MARK_NOADD packets created here
9369 			 * do not have a non-null ire_mp pointer. The null
9370 			 * value of ire_bucket indicates that they were
9371 			 * never added.
9372 			 */
9373 			if (ire->ire_marks & IRE_MARK_NOADD) {
9374 				uint_t  max_frag;
9375 
9376 				max_frag = *ire->ire_max_fragp;
9377 				ire->ire_max_fragp = NULL;
9378 				ire->ire_max_frag = max_frag;
9379 
9380 				if ((ire->ire_nce = ndp_lookup_v4(
9381 				    ire_to_ill(ire),
9382 				    (ire->ire_gateway_addr != INADDR_ANY ?
9383 				    &ire->ire_gateway_addr : &ire->ire_addr),
9384 				    B_FALSE)) == NULL) {
9385 					if (save_ire != NULL)
9386 						ire_refrele(save_ire);
9387 					break;
9388 				}
9389 				ASSERT(ire->ire_nce->nce_state ==
9390 				    ND_REACHABLE);
9391 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9392 			}
9393 
9394 			/* Prevent save_ire from getting deleted */
9395 			if (save_ire != NULL) {
9396 				IRB_REFHOLD(save_ire->ire_bucket);
9397 				/* Has it been removed already ? */
9398 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9399 					IRB_REFRELE(save_ire->ire_bucket);
9400 					ire_refrele(save_ire);
9401 					break;
9402 				}
9403 			}
9404 
9405 			ire_add_then_send(q, ire, first_mp);
9406 
9407 			/* Assert that save_ire is not deleted yet. */
9408 			if (save_ire != NULL) {
9409 				ASSERT(save_ire->ire_ptpn != NULL);
9410 				IRB_REFRELE(save_ire->ire_bucket);
9411 				ire_refrele(save_ire);
9412 				save_ire = NULL;
9413 			}
9414 			if (fire != NULL) {
9415 				ire_refrele(fire);
9416 				fire = NULL;
9417 			}
9418 
9419 			/*
9420 			 * the resolution loop is re-entered if this
9421 			 * was requested through flags and if we
9422 			 * actually are in a multirouting case.
9423 			 */
9424 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9425 				boolean_t need_resolve =
9426 				    ire_multirt_need_resolve(ipha_dst,
9427 				    msg_getlabel(copy_mp), ipst);
9428 				if (!need_resolve) {
9429 					MULTIRT_DEBUG_UNTAG(copy_mp);
9430 					freemsg(copy_mp);
9431 					copy_mp = NULL;
9432 				} else {
9433 					/*
9434 					 * ipif_lookup_group() calls
9435 					 * ire_lookup_multi() that uses
9436 					 * ire_ftable_lookup() to find
9437 					 * an IRE_INTERFACE for the group.
9438 					 * In the multirt case,
9439 					 * ire_lookup_multi() then invokes
9440 					 * ire_multirt_lookup() to find
9441 					 * the next resolvable ire.
9442 					 * As a result, we obtain an new
9443 					 * interface, derived from the
9444 					 * next ire.
9445 					 */
9446 					ipif_refrele(ipif);
9447 					ipif = ipif_lookup_group(ipha_dst,
9448 					    zoneid, ipst);
9449 					ip2dbg(("ip_newroute_ipif: "
9450 					    "multirt dst %08x, ipif %p\n",
9451 					    htonl(dst), (void *)ipif));
9452 					if (ipif != NULL) {
9453 						mp = copy_mp;
9454 						copy_mp = NULL;
9455 						multirt_resolve_next = B_TRUE;
9456 						continue;
9457 					} else {
9458 						freemsg(copy_mp);
9459 					}
9460 				}
9461 			}
9462 			if (ipif != NULL)
9463 				ipif_refrele(ipif);
9464 			ill_refrele(dst_ill);
9465 			ipif_refrele(src_ipif);
9466 			return;
9467 		}
9468 		case IRE_IF_RESOLVER:
9469 			/*
9470 			 * We can't build an IRE_CACHE yet, but at least
9471 			 * we found a resolver that can help.
9472 			 */
9473 			res_mp = dst_ill->ill_resolver_mp;
9474 			if (!OK_RESOLVER_MP(res_mp))
9475 				break;
9476 
9477 			/*
9478 			 * We obtain a partial IRE_CACHE which we will pass
9479 			 * along with the resolver query.  When the response
9480 			 * comes back it will be there ready for us to add.
9481 			 * The new ire inherits the IRE_OFFSUBNET flags
9482 			 * and source address, if this was requested.
9483 			 * The ire_max_frag is atomically set under the
9484 			 * irebucket lock in ire_add_v[46]. Only in the
9485 			 * case of IRE_MARK_NOADD, we set it here itself.
9486 			 */
9487 			ire = ire_create_mp(
9488 			    (uchar_t *)&dst,		/* dest address */
9489 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9490 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9491 			    NULL,			/* gateway address */
9492 			    (ire_marks & IRE_MARK_NOADD) ?
9493 			    ipif->ipif_mtu : 0,		/* max_frag */
9494 			    NULL,			/* no src nce */
9495 			    dst_ill->ill_rq,		/* recv-from queue */
9496 			    dst_ill->ill_wq,		/* send-to queue */
9497 			    IRE_CACHE,
9498 			    src_ipif,
9499 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9500 			    (fire != NULL) ?		/* Parent handle */
9501 			    fire->ire_phandle : 0,
9502 			    (save_ire != NULL) ?	/* Interface handle */
9503 			    save_ire->ire_ihandle : 0,
9504 			    (fire != NULL) ?		/* flags if any */
9505 			    (fire->ire_flags &
9506 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9507 			    (save_ire == NULL ? &ire_uinfo_null :
9508 			    &save_ire->ire_uinfo),
9509 			    NULL,
9510 			    NULL,
9511 			    ipst);
9512 
9513 			if (save_ire != NULL) {
9514 				ire_refrele(save_ire);
9515 				save_ire = NULL;
9516 			}
9517 			if (ire == NULL)
9518 				break;
9519 
9520 			ire->ire_marks |= ire_marks;
9521 			/*
9522 			 * Construct message chain for the resolver of the
9523 			 * form:
9524 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9525 			 *
9526 			 * NOTE : ire will be added later when the response
9527 			 * comes back from ARP. If the response does not
9528 			 * come back, ARP frees the packet. For this reason,
9529 			 * we can't REFHOLD the bucket of save_ire to prevent
9530 			 * deletions. We may not be able to REFRELE the
9531 			 * bucket if the response never comes back.
9532 			 * Thus, before adding the ire, ire_add_v4 will make
9533 			 * sure that the interface route does not get deleted.
9534 			 * This is the only case unlike ip_newroute_v6,
9535 			 * ip_newroute_ipif_v6 where we can always prevent
9536 			 * deletions because ire_add_then_send is called after
9537 			 * creating the IRE.
9538 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9539 			 * does not add this IRE into the IRE CACHE.
9540 			 */
9541 			ASSERT(ire->ire_mp != NULL);
9542 			ire->ire_mp->b_cont = first_mp;
9543 			/* Have saved_mp handy, for cleanup if canput fails */
9544 			saved_mp = mp;
9545 			mp = copyb(res_mp);
9546 			if (mp == NULL) {
9547 				/* Prepare for cleanup */
9548 				mp = saved_mp; /* pkt */
9549 				ire_delete(ire); /* ire_mp */
9550 				ire = NULL;
9551 				if (copy_mp != NULL) {
9552 					MULTIRT_DEBUG_UNTAG(copy_mp);
9553 					freemsg(copy_mp);
9554 					copy_mp = NULL;
9555 				}
9556 				break;
9557 			}
9558 			linkb(mp, ire->ire_mp);
9559 
9560 			/*
9561 			 * Fill in the source and dest addrs for the resolver.
9562 			 * NOTE: this depends on memory layouts imposed by
9563 			 * ill_init().  There are corner cases above where we
9564 			 * might've created the IRE with an INADDR_ANY source
9565 			 * address (e.g., if the zeroth ipif on an underlying
9566 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9567 			 * on the ill has a usable test address).  If so, tell
9568 			 * ARP to use ipha_src as its sender address.
9569 			 */
9570 			areq = (areq_t *)mp->b_rptr;
9571 			addrp = (ipaddr_t *)((char *)areq +
9572 			    areq->areq_sender_addr_offset);
9573 			if (ire->ire_src_addr != INADDR_ANY)
9574 				*addrp = ire->ire_src_addr;
9575 			else
9576 				*addrp = ipha->ipha_src;
9577 			addrp = (ipaddr_t *)((char *)areq +
9578 			    areq->areq_target_addr_offset);
9579 			*addrp = dst;
9580 			/* Up to the resolver. */
9581 			if (canputnext(dst_ill->ill_rq) &&
9582 			    !(dst_ill->ill_arp_closing)) {
9583 				putnext(dst_ill->ill_rq, mp);
9584 				/*
9585 				 * The response will come back in ip_wput
9586 				 * with db_type IRE_DB_TYPE.
9587 				 */
9588 			} else {
9589 				mp->b_cont = NULL;
9590 				freeb(mp); /* areq */
9591 				ire_delete(ire); /* ire_mp */
9592 				saved_mp->b_next = NULL;
9593 				saved_mp->b_prev = NULL;
9594 				freemsg(first_mp); /* pkt */
9595 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9596 			}
9597 
9598 			if (fire != NULL) {
9599 				ire_refrele(fire);
9600 				fire = NULL;
9601 			}
9602 
9603 			/*
9604 			 * The resolution loop is re-entered if this was
9605 			 * requested through flags and we actually are
9606 			 * in a multirouting case.
9607 			 */
9608 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9609 				boolean_t need_resolve =
9610 				    ire_multirt_need_resolve(ipha_dst,
9611 				    msg_getlabel(copy_mp), ipst);
9612 				if (!need_resolve) {
9613 					MULTIRT_DEBUG_UNTAG(copy_mp);
9614 					freemsg(copy_mp);
9615 					copy_mp = NULL;
9616 				} else {
9617 					/*
9618 					 * ipif_lookup_group() calls
9619 					 * ire_lookup_multi() that uses
9620 					 * ire_ftable_lookup() to find
9621 					 * an IRE_INTERFACE for the group.
9622 					 * In the multirt case,
9623 					 * ire_lookup_multi() then invokes
9624 					 * ire_multirt_lookup() to find
9625 					 * the next resolvable ire.
9626 					 * As a result, we obtain an new
9627 					 * interface, derived from the
9628 					 * next ire.
9629 					 */
9630 					ipif_refrele(ipif);
9631 					ipif = ipif_lookup_group(ipha_dst,
9632 					    zoneid, ipst);
9633 					if (ipif != NULL) {
9634 						mp = copy_mp;
9635 						copy_mp = NULL;
9636 						multirt_resolve_next = B_TRUE;
9637 						continue;
9638 					} else {
9639 						freemsg(copy_mp);
9640 					}
9641 				}
9642 			}
9643 			if (ipif != NULL)
9644 				ipif_refrele(ipif);
9645 			ill_refrele(dst_ill);
9646 			ipif_refrele(src_ipif);
9647 			return;
9648 		default:
9649 			break;
9650 		}
9651 	} while (multirt_resolve_next);
9652 
9653 err_ret:
9654 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9655 	if (fire != NULL)
9656 		ire_refrele(fire);
9657 	ipif_refrele(ipif);
9658 	/* Did this packet originate externally? */
9659 	if (dst_ill != NULL)
9660 		ill_refrele(dst_ill);
9661 	if (src_ipif != NULL)
9662 		ipif_refrele(src_ipif);
9663 	if (mp->b_prev || mp->b_next) {
9664 		mp->b_next = NULL;
9665 		mp->b_prev = NULL;
9666 	} else {
9667 		/*
9668 		 * Since ip_wput() isn't close to finished, we fill
9669 		 * in enough of the header for credible error reporting.
9670 		 */
9671 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9672 			/* Failed */
9673 			freemsg(first_mp);
9674 			if (ire != NULL)
9675 				ire_refrele(ire);
9676 			return;
9677 		}
9678 	}
9679 	/*
9680 	 * At this point we will have ire only if RTF_BLACKHOLE
9681 	 * or RTF_REJECT flags are set on the IRE. It will not
9682 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9683 	 */
9684 	if (ire != NULL) {
9685 		if (ire->ire_flags & RTF_BLACKHOLE) {
9686 			ire_refrele(ire);
9687 			freemsg(first_mp);
9688 			return;
9689 		}
9690 		ire_refrele(ire);
9691 	}
9692 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9693 }
9694 
9695 /* Name/Value Table Lookup Routine */
9696 char *
9697 ip_nv_lookup(nv_t *nv, int value)
9698 {
9699 	if (!nv)
9700 		return (NULL);
9701 	for (; nv->nv_name; nv++) {
9702 		if (nv->nv_value == value)
9703 			return (nv->nv_name);
9704 	}
9705 	return ("unknown");
9706 }
9707 
9708 /*
9709  * This is a module open, i.e. this is a control stream for access
9710  * to a DLPI device.  We allocate an ill_t as the instance data in
9711  * this case.
9712  */
9713 int
9714 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9715 {
9716 	ill_t	*ill;
9717 	int	err;
9718 	zoneid_t zoneid;
9719 	netstack_t *ns;
9720 	ip_stack_t *ipst;
9721 
9722 	/*
9723 	 * Prevent unprivileged processes from pushing IP so that
9724 	 * they can't send raw IP.
9725 	 */
9726 	if (secpolicy_net_rawaccess(credp) != 0)
9727 		return (EPERM);
9728 
9729 	ns = netstack_find_by_cred(credp);
9730 	ASSERT(ns != NULL);
9731 	ipst = ns->netstack_ip;
9732 	ASSERT(ipst != NULL);
9733 
9734 	/*
9735 	 * For exclusive stacks we set the zoneid to zero
9736 	 * to make IP operate as if in the global zone.
9737 	 */
9738 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9739 		zoneid = GLOBAL_ZONEID;
9740 	else
9741 		zoneid = crgetzoneid(credp);
9742 
9743 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9744 	q->q_ptr = WR(q)->q_ptr = ill;
9745 	ill->ill_ipst = ipst;
9746 	ill->ill_zoneid = zoneid;
9747 
9748 	/*
9749 	 * ill_init initializes the ill fields and then sends down
9750 	 * down a DL_INFO_REQ after calling qprocson.
9751 	 */
9752 	err = ill_init(q, ill);
9753 	if (err != 0) {
9754 		mi_free(ill);
9755 		netstack_rele(ipst->ips_netstack);
9756 		q->q_ptr = NULL;
9757 		WR(q)->q_ptr = NULL;
9758 		return (err);
9759 	}
9760 
9761 	/* ill_init initializes the ipsq marking this thread as writer */
9762 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9763 	/* Wait for the DL_INFO_ACK */
9764 	mutex_enter(&ill->ill_lock);
9765 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9766 		/*
9767 		 * Return value of 0 indicates a pending signal.
9768 		 */
9769 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9770 		if (err == 0) {
9771 			mutex_exit(&ill->ill_lock);
9772 			(void) ip_close(q, 0);
9773 			return (EINTR);
9774 		}
9775 	}
9776 	mutex_exit(&ill->ill_lock);
9777 
9778 	/*
9779 	 * ip_rput_other could have set an error  in ill_error on
9780 	 * receipt of M_ERROR.
9781 	 */
9782 
9783 	err = ill->ill_error;
9784 	if (err != 0) {
9785 		(void) ip_close(q, 0);
9786 		return (err);
9787 	}
9788 
9789 	ill->ill_credp = credp;
9790 	crhold(credp);
9791 
9792 	mutex_enter(&ipst->ips_ip_mi_lock);
9793 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9794 	    credp);
9795 	mutex_exit(&ipst->ips_ip_mi_lock);
9796 	if (err) {
9797 		(void) ip_close(q, 0);
9798 		return (err);
9799 	}
9800 	return (0);
9801 }
9802 
9803 /* For /dev/ip aka AF_INET open */
9804 int
9805 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9806 {
9807 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9808 }
9809 
9810 /* For /dev/ip6 aka AF_INET6 open */
9811 int
9812 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9813 {
9814 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9815 }
9816 
9817 /* IP open routine. */
9818 int
9819 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9820     boolean_t isv6)
9821 {
9822 	conn_t 		*connp;
9823 	major_t		maj;
9824 	zoneid_t	zoneid;
9825 	netstack_t	*ns;
9826 	ip_stack_t	*ipst;
9827 
9828 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9829 
9830 	/* Allow reopen. */
9831 	if (q->q_ptr != NULL)
9832 		return (0);
9833 
9834 	if (sflag & MODOPEN) {
9835 		/* This is a module open */
9836 		return (ip_modopen(q, devp, flag, sflag, credp));
9837 	}
9838 
9839 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9840 		/*
9841 		 * Non streams based socket looking for a stream
9842 		 * to access IP
9843 		 */
9844 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9845 		    credp, isv6));
9846 	}
9847 
9848 	ns = netstack_find_by_cred(credp);
9849 	ASSERT(ns != NULL);
9850 	ipst = ns->netstack_ip;
9851 	ASSERT(ipst != NULL);
9852 
9853 	/*
9854 	 * For exclusive stacks we set the zoneid to zero
9855 	 * to make IP operate as if in the global zone.
9856 	 */
9857 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9858 		zoneid = GLOBAL_ZONEID;
9859 	else
9860 		zoneid = crgetzoneid(credp);
9861 
9862 	/*
9863 	 * We are opening as a device. This is an IP client stream, and we
9864 	 * allocate an conn_t as the instance data.
9865 	 */
9866 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9867 
9868 	/*
9869 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9870 	 * done by netstack_find_by_cred()
9871 	 */
9872 	netstack_rele(ipst->ips_netstack);
9873 
9874 	connp->conn_zoneid = zoneid;
9875 	connp->conn_sqp = NULL;
9876 	connp->conn_initial_sqp = NULL;
9877 	connp->conn_final_sqp = NULL;
9878 
9879 	connp->conn_upq = q;
9880 	q->q_ptr = WR(q)->q_ptr = connp;
9881 
9882 	if (flag & SO_SOCKSTR)
9883 		connp->conn_flags |= IPCL_SOCKET;
9884 
9885 	/* Minor tells us which /dev entry was opened */
9886 	if (isv6) {
9887 		connp->conn_flags |= IPCL_ISV6;
9888 		connp->conn_af_isv6 = B_TRUE;
9889 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9890 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9891 	} else {
9892 		connp->conn_af_isv6 = B_FALSE;
9893 		connp->conn_pkt_isv6 = B_FALSE;
9894 	}
9895 
9896 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9897 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9898 		connp->conn_minor_arena = ip_minor_arena_la;
9899 	} else {
9900 		/*
9901 		 * Either minor numbers in the large arena were exhausted
9902 		 * or a non socket application is doing the open.
9903 		 * Try to allocate from the small arena.
9904 		 */
9905 		if ((connp->conn_dev =
9906 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9907 			/* CONN_DEC_REF takes care of netstack_rele() */
9908 			q->q_ptr = WR(q)->q_ptr = NULL;
9909 			CONN_DEC_REF(connp);
9910 			return (EBUSY);
9911 		}
9912 		connp->conn_minor_arena = ip_minor_arena_sa;
9913 	}
9914 
9915 	maj = getemajor(*devp);
9916 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9917 
9918 	/*
9919 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9920 	 */
9921 	connp->conn_cred = credp;
9922 
9923 	/*
9924 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9925 	 */
9926 	connp->conn_recv = ip_conn_input;
9927 
9928 	crhold(connp->conn_cred);
9929 
9930 	/*
9931 	 * If the caller has the process-wide flag set, then default to MAC
9932 	 * exempt mode.  This allows read-down to unlabeled hosts.
9933 	 */
9934 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9935 		connp->conn_mac_exempt = B_TRUE;
9936 
9937 	connp->conn_rq = q;
9938 	connp->conn_wq = WR(q);
9939 
9940 	/* Non-zero default values */
9941 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9942 
9943 	/*
9944 	 * Make the conn globally visible to walkers
9945 	 */
9946 	ASSERT(connp->conn_ref == 1);
9947 	mutex_enter(&connp->conn_lock);
9948 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9949 	mutex_exit(&connp->conn_lock);
9950 
9951 	qprocson(q);
9952 
9953 	return (0);
9954 }
9955 
9956 /*
9957  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9958  * Note that there is no race since either ip_output function works - it
9959  * is just an optimization to enter the best ip_output routine directly.
9960  */
9961 void
9962 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9963     ip_stack_t *ipst)
9964 {
9965 	if (isv6)  {
9966 		if (bump_mib) {
9967 			BUMP_MIB(&ipst->ips_ip6_mib,
9968 			    ipIfStatsOutSwitchIPVersion);
9969 		}
9970 		connp->conn_send = ip_output_v6;
9971 		connp->conn_pkt_isv6 = B_TRUE;
9972 	} else {
9973 		if (bump_mib) {
9974 			BUMP_MIB(&ipst->ips_ip_mib,
9975 			    ipIfStatsOutSwitchIPVersion);
9976 		}
9977 		connp->conn_send = ip_output;
9978 		connp->conn_pkt_isv6 = B_FALSE;
9979 	}
9980 
9981 }
9982 
9983 /*
9984  * See if IPsec needs loading because of the options in mp.
9985  */
9986 static boolean_t
9987 ipsec_opt_present(mblk_t *mp)
9988 {
9989 	uint8_t *optcp, *next_optcp, *opt_endcp;
9990 	struct opthdr *opt;
9991 	struct T_opthdr *topt;
9992 	int opthdr_len;
9993 	t_uscalar_t optname, optlevel;
9994 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9995 	ipsec_req_t *ipsr;
9996 
9997 	/*
9998 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9999 	 * return TRUE.
10000 	 */
10001 
10002 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10003 	opt_endcp = optcp + tor->OPT_length;
10004 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10005 		opthdr_len = sizeof (struct T_opthdr);
10006 	} else {		/* O_OPTMGMT_REQ */
10007 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10008 		opthdr_len = sizeof (struct opthdr);
10009 	}
10010 	for (; optcp < opt_endcp; optcp = next_optcp) {
10011 		if (optcp + opthdr_len > opt_endcp)
10012 			return (B_FALSE);	/* Not enough option header. */
10013 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10014 			topt = (struct T_opthdr *)optcp;
10015 			optlevel = topt->level;
10016 			optname = topt->name;
10017 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10018 		} else {
10019 			opt = (struct opthdr *)optcp;
10020 			optlevel = opt->level;
10021 			optname = opt->name;
10022 			next_optcp = optcp + opthdr_len +
10023 			    _TPI_ALIGN_OPT(opt->len);
10024 		}
10025 		if ((next_optcp < optcp) || /* wraparound pointer space */
10026 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10027 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10028 			return (B_FALSE); /* bad option buffer */
10029 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10030 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10031 			/*
10032 			 * Check to see if it's an all-bypass or all-zeroes
10033 			 * IPsec request.  Don't bother loading IPsec if
10034 			 * the socket doesn't want to use it.  (A good example
10035 			 * is a bypass request.)
10036 			 *
10037 			 * Basically, if any of the non-NEVER bits are set,
10038 			 * load IPsec.
10039 			 */
10040 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10041 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10042 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10043 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10044 			    != 0)
10045 				return (B_TRUE);
10046 		}
10047 	}
10048 	return (B_FALSE);
10049 }
10050 
10051 /*
10052  * If conn is is waiting for ipsec to finish loading, kick it.
10053  */
10054 /* ARGSUSED */
10055 static void
10056 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10057 {
10058 	t_scalar_t	optreq_prim;
10059 	mblk_t		*mp;
10060 	cred_t		*cr;
10061 	int		err = 0;
10062 
10063 	/*
10064 	 * This function is called, after ipsec loading is complete.
10065 	 * Since IP checks exclusively and atomically (i.e it prevents
10066 	 * ipsec load from completing until ip_optcom_req completes)
10067 	 * whether ipsec load is complete, there cannot be a race with IP
10068 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10069 	 */
10070 	mutex_enter(&connp->conn_lock);
10071 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10072 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10073 		mp = connp->conn_ipsec_opt_mp;
10074 		connp->conn_ipsec_opt_mp = NULL;
10075 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10076 		mutex_exit(&connp->conn_lock);
10077 
10078 		/*
10079 		 * All Solaris components should pass a db_credp
10080 		 * for this TPI message, hence we ASSERT.
10081 		 * But in case there is some other M_PROTO that looks
10082 		 * like a TPI message sent by some other kernel
10083 		 * component, we check and return an error.
10084 		 */
10085 		cr = msg_getcred(mp, NULL);
10086 		ASSERT(cr != NULL);
10087 		if (cr == NULL) {
10088 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
10089 			if (mp != NULL)
10090 				qreply(connp->conn_wq, mp);
10091 			return;
10092 		}
10093 
10094 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10095 
10096 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10097 		if (optreq_prim == T_OPTMGMT_REQ) {
10098 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10099 			    &ip_opt_obj, B_FALSE);
10100 		} else {
10101 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10102 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10103 			    &ip_opt_obj, B_FALSE);
10104 		}
10105 		if (err != EINPROGRESS)
10106 			CONN_OPER_PENDING_DONE(connp);
10107 		return;
10108 	}
10109 	mutex_exit(&connp->conn_lock);
10110 }
10111 
10112 /*
10113  * Called from the ipsec_loader thread, outside any perimeter, to tell
10114  * ip qenable any of the queues waiting for the ipsec loader to
10115  * complete.
10116  */
10117 void
10118 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10119 {
10120 	netstack_t *ns = ipss->ipsec_netstack;
10121 
10122 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10123 }
10124 
10125 /*
10126  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10127  * determines the grp on which it has to become exclusive, queues the mp
10128  * and IPSQ draining restarts the optmgmt
10129  */
10130 static boolean_t
10131 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10132 {
10133 	conn_t *connp = Q_TO_CONN(q);
10134 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10135 
10136 	/*
10137 	 * Take IPsec requests and treat them special.
10138 	 */
10139 	if (ipsec_opt_present(mp)) {
10140 		/* First check if IPsec is loaded. */
10141 		mutex_enter(&ipss->ipsec_loader_lock);
10142 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10143 			mutex_exit(&ipss->ipsec_loader_lock);
10144 			return (B_FALSE);
10145 		}
10146 		mutex_enter(&connp->conn_lock);
10147 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10148 
10149 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10150 		connp->conn_ipsec_opt_mp = mp;
10151 		mutex_exit(&connp->conn_lock);
10152 		mutex_exit(&ipss->ipsec_loader_lock);
10153 
10154 		ipsec_loader_loadnow(ipss);
10155 		return (B_TRUE);
10156 	}
10157 	return (B_FALSE);
10158 }
10159 
10160 /*
10161  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10162  * all of them are copied to the conn_t. If the req is "zero", the policy is
10163  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10164  * fields.
10165  * We keep only the latest setting of the policy and thus policy setting
10166  * is not incremental/cumulative.
10167  *
10168  * Requests to set policies with multiple alternative actions will
10169  * go through a different API.
10170  */
10171 int
10172 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10173 {
10174 	uint_t ah_req = 0;
10175 	uint_t esp_req = 0;
10176 	uint_t se_req = 0;
10177 	ipsec_selkey_t sel;
10178 	ipsec_act_t *actp = NULL;
10179 	uint_t nact;
10180 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10181 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10182 	ipsec_policy_root_t *pr;
10183 	ipsec_policy_head_t *ph;
10184 	int fam;
10185 	boolean_t is_pol_reset;
10186 	int error = 0;
10187 	netstack_t	*ns = connp->conn_netstack;
10188 	ip_stack_t	*ipst = ns->netstack_ip;
10189 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10190 
10191 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10192 
10193 	/*
10194 	 * The IP_SEC_OPT option does not allow variable length parameters,
10195 	 * hence a request cannot be NULL.
10196 	 */
10197 	if (req == NULL)
10198 		return (EINVAL);
10199 
10200 	ah_req = req->ipsr_ah_req;
10201 	esp_req = req->ipsr_esp_req;
10202 	se_req = req->ipsr_self_encap_req;
10203 
10204 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10205 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10206 		return (EINVAL);
10207 
10208 	/*
10209 	 * Are we dealing with a request to reset the policy (i.e.
10210 	 * zero requests).
10211 	 */
10212 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10213 	    (esp_req & REQ_MASK) == 0 &&
10214 	    (se_req & REQ_MASK) == 0);
10215 
10216 	if (!is_pol_reset) {
10217 		/*
10218 		 * If we couldn't load IPsec, fail with "protocol
10219 		 * not supported".
10220 		 * IPsec may not have been loaded for a request with zero
10221 		 * policies, so we don't fail in this case.
10222 		 */
10223 		mutex_enter(&ipss->ipsec_loader_lock);
10224 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10225 			mutex_exit(&ipss->ipsec_loader_lock);
10226 			return (EPROTONOSUPPORT);
10227 		}
10228 		mutex_exit(&ipss->ipsec_loader_lock);
10229 
10230 		/*
10231 		 * Test for valid requests. Invalid algorithms
10232 		 * need to be tested by IPsec code because new
10233 		 * algorithms can be added dynamically.
10234 		 */
10235 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10236 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10237 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10238 			return (EINVAL);
10239 		}
10240 
10241 		/*
10242 		 * Only privileged users can issue these
10243 		 * requests.
10244 		 */
10245 		if (((ah_req & IPSEC_PREF_NEVER) ||
10246 		    (esp_req & IPSEC_PREF_NEVER) ||
10247 		    (se_req & IPSEC_PREF_NEVER)) &&
10248 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10249 			return (EPERM);
10250 		}
10251 
10252 		/*
10253 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10254 		 * are mutually exclusive.
10255 		 */
10256 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10257 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10258 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10259 			/* Both of them are set */
10260 			return (EINVAL);
10261 		}
10262 	}
10263 
10264 	mutex_enter(&connp->conn_lock);
10265 
10266 	/*
10267 	 * If we have already cached policies in ip_bind_connected*(), don't
10268 	 * let them change now. We cache policies for connections
10269 	 * whose src,dst [addr, port] is known.
10270 	 */
10271 	if (connp->conn_policy_cached) {
10272 		mutex_exit(&connp->conn_lock);
10273 		return (EINVAL);
10274 	}
10275 
10276 	/*
10277 	 * We have a zero policies, reset the connection policy if already
10278 	 * set. This will cause the connection to inherit the
10279 	 * global policy, if any.
10280 	 */
10281 	if (is_pol_reset) {
10282 		if (connp->conn_policy != NULL) {
10283 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10284 			connp->conn_policy = NULL;
10285 		}
10286 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10287 		connp->conn_in_enforce_policy = B_FALSE;
10288 		connp->conn_out_enforce_policy = B_FALSE;
10289 		mutex_exit(&connp->conn_lock);
10290 		return (0);
10291 	}
10292 
10293 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10294 	    ipst->ips_netstack);
10295 	if (ph == NULL)
10296 		goto enomem;
10297 
10298 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10299 	if (actp == NULL)
10300 		goto enomem;
10301 
10302 	/*
10303 	 * Always allocate IPv4 policy entries, since they can also
10304 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10305 	 */
10306 	bzero(&sel, sizeof (sel));
10307 	sel.ipsl_valid = IPSL_IPV4;
10308 
10309 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10310 	    ipst->ips_netstack);
10311 	if (pin4 == NULL)
10312 		goto enomem;
10313 
10314 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10315 	    ipst->ips_netstack);
10316 	if (pout4 == NULL)
10317 		goto enomem;
10318 
10319 	if (connp->conn_af_isv6) {
10320 		/*
10321 		 * We're looking at a v6 socket, also allocate the
10322 		 * v6-specific entries...
10323 		 */
10324 		sel.ipsl_valid = IPSL_IPV6;
10325 		pin6 = ipsec_policy_create(&sel, actp, nact,
10326 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10327 		if (pin6 == NULL)
10328 			goto enomem;
10329 
10330 		pout6 = ipsec_policy_create(&sel, actp, nact,
10331 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10332 		if (pout6 == NULL)
10333 			goto enomem;
10334 
10335 		/*
10336 		 * .. and file them away in the right place.
10337 		 */
10338 		fam = IPSEC_AF_V6;
10339 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10340 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10341 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10342 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10343 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10344 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10345 	}
10346 
10347 	ipsec_actvec_free(actp, nact);
10348 
10349 	/*
10350 	 * File the v4 policies.
10351 	 */
10352 	fam = IPSEC_AF_V4;
10353 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10354 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10355 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10356 
10357 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10358 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10359 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10360 
10361 	/*
10362 	 * If the requests need security, set enforce_policy.
10363 	 * If the requests are IPSEC_PREF_NEVER, one should
10364 	 * still set conn_out_enforce_policy so that an ipsec_out
10365 	 * gets attached in ip_wput. This is needed so that
10366 	 * for connections that we don't cache policy in ip_bind,
10367 	 * if global policy matches in ip_wput_attach_policy, we
10368 	 * don't wrongly inherit global policy. Similarly, we need
10369 	 * to set conn_in_enforce_policy also so that we don't verify
10370 	 * policy wrongly.
10371 	 */
10372 	if ((ah_req & REQ_MASK) != 0 ||
10373 	    (esp_req & REQ_MASK) != 0 ||
10374 	    (se_req & REQ_MASK) != 0) {
10375 		connp->conn_in_enforce_policy = B_TRUE;
10376 		connp->conn_out_enforce_policy = B_TRUE;
10377 		connp->conn_flags |= IPCL_CHECK_POLICY;
10378 	}
10379 
10380 	mutex_exit(&connp->conn_lock);
10381 	return (error);
10382 #undef REQ_MASK
10383 
10384 	/*
10385 	 * Common memory-allocation-failure exit path.
10386 	 */
10387 enomem:
10388 	mutex_exit(&connp->conn_lock);
10389 	if (actp != NULL)
10390 		ipsec_actvec_free(actp, nact);
10391 	if (pin4 != NULL)
10392 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10393 	if (pout4 != NULL)
10394 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10395 	if (pin6 != NULL)
10396 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10397 	if (pout6 != NULL)
10398 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10399 	return (ENOMEM);
10400 }
10401 
10402 /*
10403  * Only for options that pass in an IP addr. Currently only V4 options
10404  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10405  * So this function assumes level is IPPROTO_IP
10406  */
10407 int
10408 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10409     mblk_t *first_mp)
10410 {
10411 	ipif_t *ipif = NULL;
10412 	int error;
10413 	ill_t *ill;
10414 	int zoneid;
10415 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10416 
10417 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10418 
10419 	if (addr != INADDR_ANY || checkonly) {
10420 		ASSERT(connp != NULL);
10421 		zoneid = IPCL_ZONEID(connp);
10422 		if (option == IP_NEXTHOP) {
10423 			ipif = ipif_lookup_onlink_addr(addr,
10424 			    connp->conn_zoneid, ipst);
10425 		} else {
10426 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10427 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10428 			    &error, ipst);
10429 		}
10430 		if (ipif == NULL) {
10431 			if (error == EINPROGRESS)
10432 				return (error);
10433 			if ((option == IP_MULTICAST_IF) ||
10434 			    (option == IP_NEXTHOP))
10435 				return (EHOSTUNREACH);
10436 			else
10437 				return (EINVAL);
10438 		} else if (checkonly) {
10439 			if (option == IP_MULTICAST_IF) {
10440 				ill = ipif->ipif_ill;
10441 				/* not supported by the virtual network iface */
10442 				if (IS_VNI(ill)) {
10443 					ipif_refrele(ipif);
10444 					return (EINVAL);
10445 				}
10446 			}
10447 			ipif_refrele(ipif);
10448 			return (0);
10449 		}
10450 		ill = ipif->ipif_ill;
10451 		mutex_enter(&connp->conn_lock);
10452 		mutex_enter(&ill->ill_lock);
10453 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10454 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10455 			mutex_exit(&ill->ill_lock);
10456 			mutex_exit(&connp->conn_lock);
10457 			ipif_refrele(ipif);
10458 			return (option == IP_MULTICAST_IF ?
10459 			    EHOSTUNREACH : EINVAL);
10460 		}
10461 	} else {
10462 		mutex_enter(&connp->conn_lock);
10463 	}
10464 
10465 	/* None of the options below are supported on the VNI */
10466 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10467 		mutex_exit(&ill->ill_lock);
10468 		mutex_exit(&connp->conn_lock);
10469 		ipif_refrele(ipif);
10470 		return (EINVAL);
10471 	}
10472 
10473 	switch (option) {
10474 	case IP_MULTICAST_IF:
10475 		connp->conn_multicast_ipif = ipif;
10476 		break;
10477 	case IP_NEXTHOP:
10478 		connp->conn_nexthop_v4 = addr;
10479 		connp->conn_nexthop_set = B_TRUE;
10480 		break;
10481 	}
10482 
10483 	if (ipif != NULL) {
10484 		mutex_exit(&ill->ill_lock);
10485 		mutex_exit(&connp->conn_lock);
10486 		ipif_refrele(ipif);
10487 		return (0);
10488 	}
10489 	mutex_exit(&connp->conn_lock);
10490 	/* We succeded in cleared the option */
10491 	return (0);
10492 }
10493 
10494 /*
10495  * For options that pass in an ifindex specifying the ill. V6 options always
10496  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10497  */
10498 int
10499 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10500     int level, int option, mblk_t *first_mp)
10501 {
10502 	ill_t *ill = NULL;
10503 	int error = 0;
10504 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10505 
10506 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10507 	if (ifindex != 0) {
10508 		ASSERT(connp != NULL);
10509 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10510 		    first_mp, ip_restart_optmgmt, &error, ipst);
10511 		if (ill != NULL) {
10512 			if (checkonly) {
10513 				/* not supported by the virtual network iface */
10514 				if (IS_VNI(ill)) {
10515 					ill_refrele(ill);
10516 					return (EINVAL);
10517 				}
10518 				ill_refrele(ill);
10519 				return (0);
10520 			}
10521 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10522 			    0, NULL)) {
10523 				ill_refrele(ill);
10524 				ill = NULL;
10525 				mutex_enter(&connp->conn_lock);
10526 				goto setit;
10527 			}
10528 			mutex_enter(&connp->conn_lock);
10529 			mutex_enter(&ill->ill_lock);
10530 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10531 				mutex_exit(&ill->ill_lock);
10532 				mutex_exit(&connp->conn_lock);
10533 				ill_refrele(ill);
10534 				ill = NULL;
10535 				mutex_enter(&connp->conn_lock);
10536 			}
10537 			goto setit;
10538 		} else if (error == EINPROGRESS) {
10539 			return (error);
10540 		} else {
10541 			error = 0;
10542 		}
10543 	}
10544 	mutex_enter(&connp->conn_lock);
10545 setit:
10546 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10547 
10548 	/*
10549 	 * The options below assume that the ILL (if any) transmits and/or
10550 	 * receives traffic. Neither of which is true for the virtual network
10551 	 * interface, so fail setting these on a VNI.
10552 	 */
10553 	if (IS_VNI(ill)) {
10554 		ASSERT(ill != NULL);
10555 		mutex_exit(&ill->ill_lock);
10556 		mutex_exit(&connp->conn_lock);
10557 		ill_refrele(ill);
10558 		return (EINVAL);
10559 	}
10560 
10561 	if (level == IPPROTO_IP) {
10562 		switch (option) {
10563 		case IP_BOUND_IF:
10564 			connp->conn_incoming_ill = ill;
10565 			connp->conn_outgoing_ill = ill;
10566 			break;
10567 
10568 		case IP_MULTICAST_IF:
10569 			/*
10570 			 * This option is an internal special. The socket
10571 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10572 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10573 			 * specifies an ifindex and we try first on V6 ill's.
10574 			 * If we don't find one, we they try using on v4 ill's
10575 			 * intenally and we come here.
10576 			 */
10577 			if (!checkonly && ill != NULL) {
10578 				ipif_t	*ipif;
10579 				ipif = ill->ill_ipif;
10580 
10581 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10582 					mutex_exit(&ill->ill_lock);
10583 					mutex_exit(&connp->conn_lock);
10584 					ill_refrele(ill);
10585 					ill = NULL;
10586 					mutex_enter(&connp->conn_lock);
10587 				} else {
10588 					connp->conn_multicast_ipif = ipif;
10589 				}
10590 			}
10591 			break;
10592 
10593 		case IP_DHCPINIT_IF:
10594 			if (connp->conn_dhcpinit_ill != NULL) {
10595 				/*
10596 				 * We've locked the conn so conn_cleanup_ill()
10597 				 * cannot clear conn_dhcpinit_ill -- so it's
10598 				 * safe to access the ill.
10599 				 */
10600 				ill_t *oill = connp->conn_dhcpinit_ill;
10601 
10602 				ASSERT(oill->ill_dhcpinit != 0);
10603 				atomic_dec_32(&oill->ill_dhcpinit);
10604 				connp->conn_dhcpinit_ill = NULL;
10605 			}
10606 
10607 			if (ill != NULL) {
10608 				connp->conn_dhcpinit_ill = ill;
10609 				atomic_inc_32(&ill->ill_dhcpinit);
10610 			}
10611 			break;
10612 		}
10613 	} else {
10614 		switch (option) {
10615 		case IPV6_BOUND_IF:
10616 			connp->conn_incoming_ill = ill;
10617 			connp->conn_outgoing_ill = ill;
10618 			break;
10619 
10620 		case IPV6_MULTICAST_IF:
10621 			/*
10622 			 * Set conn_multicast_ill to be the IPv6 ill.
10623 			 * Set conn_multicast_ipif to be an IPv4 ipif
10624 			 * for ifindex to make IPv4 mapped addresses
10625 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10626 			 * Even if no IPv6 ill exists for the ifindex
10627 			 * we need to check for an IPv4 ifindex in order
10628 			 * for this to work with mapped addresses. In that
10629 			 * case only set conn_multicast_ipif.
10630 			 */
10631 			if (!checkonly) {
10632 				if (ifindex == 0) {
10633 					connp->conn_multicast_ill = NULL;
10634 					connp->conn_multicast_ipif = NULL;
10635 				} else if (ill != NULL) {
10636 					connp->conn_multicast_ill = ill;
10637 				}
10638 			}
10639 			break;
10640 		}
10641 	}
10642 
10643 	if (ill != NULL) {
10644 		mutex_exit(&ill->ill_lock);
10645 		mutex_exit(&connp->conn_lock);
10646 		ill_refrele(ill);
10647 		return (0);
10648 	}
10649 	mutex_exit(&connp->conn_lock);
10650 	/*
10651 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10652 	 * locate the ill and could not set the option (ifindex != 0)
10653 	 */
10654 	return (ifindex == 0 ? 0 : EINVAL);
10655 }
10656 
10657 /* This routine sets socket options. */
10658 /* ARGSUSED */
10659 int
10660 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10661     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10662     void *dummy, cred_t *cr, mblk_t *first_mp)
10663 {
10664 	int		*i1 = (int *)invalp;
10665 	conn_t		*connp = Q_TO_CONN(q);
10666 	int		error = 0;
10667 	boolean_t	checkonly;
10668 	ire_t		*ire;
10669 	boolean_t	found;
10670 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10671 
10672 	switch (optset_context) {
10673 
10674 	case SETFN_OPTCOM_CHECKONLY:
10675 		checkonly = B_TRUE;
10676 		/*
10677 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10678 		 * inlen != 0 implies value supplied and
10679 		 * 	we have to "pretend" to set it.
10680 		 * inlen == 0 implies that there is no
10681 		 * 	value part in T_CHECK request and just validation
10682 		 * done elsewhere should be enough, we just return here.
10683 		 */
10684 		if (inlen == 0) {
10685 			*outlenp = 0;
10686 			return (0);
10687 		}
10688 		break;
10689 	case SETFN_OPTCOM_NEGOTIATE:
10690 	case SETFN_UD_NEGOTIATE:
10691 	case SETFN_CONN_NEGOTIATE:
10692 		checkonly = B_FALSE;
10693 		break;
10694 	default:
10695 		/*
10696 		 * We should never get here
10697 		 */
10698 		*outlenp = 0;
10699 		return (EINVAL);
10700 	}
10701 
10702 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10703 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10704 
10705 	/*
10706 	 * For fixed length options, no sanity check
10707 	 * of passed in length is done. It is assumed *_optcom_req()
10708 	 * routines do the right thing.
10709 	 */
10710 
10711 	switch (level) {
10712 	case SOL_SOCKET:
10713 		/*
10714 		 * conn_lock protects the bitfields, and is used to
10715 		 * set the fields atomically.
10716 		 */
10717 		switch (name) {
10718 		case SO_BROADCAST:
10719 			if (!checkonly) {
10720 				/* TODO: use value someplace? */
10721 				mutex_enter(&connp->conn_lock);
10722 				connp->conn_broadcast = *i1 ? 1 : 0;
10723 				mutex_exit(&connp->conn_lock);
10724 			}
10725 			break;	/* goto sizeof (int) option return */
10726 		case SO_USELOOPBACK:
10727 			if (!checkonly) {
10728 				/* TODO: use value someplace? */
10729 				mutex_enter(&connp->conn_lock);
10730 				connp->conn_loopback = *i1 ? 1 : 0;
10731 				mutex_exit(&connp->conn_lock);
10732 			}
10733 			break;	/* goto sizeof (int) option return */
10734 		case SO_DONTROUTE:
10735 			if (!checkonly) {
10736 				mutex_enter(&connp->conn_lock);
10737 				connp->conn_dontroute = *i1 ? 1 : 0;
10738 				mutex_exit(&connp->conn_lock);
10739 			}
10740 			break;	/* goto sizeof (int) option return */
10741 		case SO_REUSEADDR:
10742 			if (!checkonly) {
10743 				mutex_enter(&connp->conn_lock);
10744 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10745 				mutex_exit(&connp->conn_lock);
10746 			}
10747 			break;	/* goto sizeof (int) option return */
10748 		case SO_PROTOTYPE:
10749 			if (!checkonly) {
10750 				mutex_enter(&connp->conn_lock);
10751 				connp->conn_proto = *i1;
10752 				mutex_exit(&connp->conn_lock);
10753 			}
10754 			break;	/* goto sizeof (int) option return */
10755 		case SO_ALLZONES:
10756 			if (!checkonly) {
10757 				mutex_enter(&connp->conn_lock);
10758 				if (IPCL_IS_BOUND(connp)) {
10759 					mutex_exit(&connp->conn_lock);
10760 					return (EINVAL);
10761 				}
10762 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10763 				mutex_exit(&connp->conn_lock);
10764 			}
10765 			break;	/* goto sizeof (int) option return */
10766 		case SO_ANON_MLP:
10767 			if (!checkonly) {
10768 				mutex_enter(&connp->conn_lock);
10769 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10770 				mutex_exit(&connp->conn_lock);
10771 			}
10772 			break;	/* goto sizeof (int) option return */
10773 		case SO_MAC_EXEMPT:
10774 			if (secpolicy_net_mac_aware(cr) != 0 ||
10775 			    IPCL_IS_BOUND(connp))
10776 				return (EACCES);
10777 			if (!checkonly) {
10778 				mutex_enter(&connp->conn_lock);
10779 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10780 				mutex_exit(&connp->conn_lock);
10781 			}
10782 			break;	/* goto sizeof (int) option return */
10783 		default:
10784 			/*
10785 			 * "soft" error (negative)
10786 			 * option not handled at this level
10787 			 * Note: Do not modify *outlenp
10788 			 */
10789 			return (-EINVAL);
10790 		}
10791 		break;
10792 	case IPPROTO_IP:
10793 		switch (name) {
10794 		case IP_NEXTHOP:
10795 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10796 				return (EPERM);
10797 			/* FALLTHRU */
10798 		case IP_MULTICAST_IF: {
10799 			ipaddr_t addr = *i1;
10800 
10801 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10802 			    first_mp);
10803 			if (error != 0)
10804 				return (error);
10805 			break;	/* goto sizeof (int) option return */
10806 		}
10807 
10808 		case IP_MULTICAST_TTL:
10809 			/* Recorded in transport above IP */
10810 			*outvalp = *invalp;
10811 			*outlenp = sizeof (uchar_t);
10812 			return (0);
10813 		case IP_MULTICAST_LOOP:
10814 			if (!checkonly) {
10815 				mutex_enter(&connp->conn_lock);
10816 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10817 				mutex_exit(&connp->conn_lock);
10818 			}
10819 			*outvalp = *invalp;
10820 			*outlenp = sizeof (uchar_t);
10821 			return (0);
10822 		case IP_ADD_MEMBERSHIP:
10823 		case MCAST_JOIN_GROUP:
10824 		case IP_DROP_MEMBERSHIP:
10825 		case MCAST_LEAVE_GROUP: {
10826 			struct ip_mreq *mreqp;
10827 			struct group_req *greqp;
10828 			ire_t *ire;
10829 			boolean_t done = B_FALSE;
10830 			ipaddr_t group, ifaddr;
10831 			struct sockaddr_in *sin;
10832 			uint32_t *ifindexp;
10833 			boolean_t mcast_opt = B_TRUE;
10834 			mcast_record_t fmode;
10835 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10836 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10837 
10838 			switch (name) {
10839 			case IP_ADD_MEMBERSHIP:
10840 				mcast_opt = B_FALSE;
10841 				/* FALLTHRU */
10842 			case MCAST_JOIN_GROUP:
10843 				fmode = MODE_IS_EXCLUDE;
10844 				optfn = ip_opt_add_group;
10845 				break;
10846 
10847 			case IP_DROP_MEMBERSHIP:
10848 				mcast_opt = B_FALSE;
10849 				/* FALLTHRU */
10850 			case MCAST_LEAVE_GROUP:
10851 				fmode = MODE_IS_INCLUDE;
10852 				optfn = ip_opt_delete_group;
10853 				break;
10854 			}
10855 
10856 			if (mcast_opt) {
10857 				greqp = (struct group_req *)i1;
10858 				sin = (struct sockaddr_in *)&greqp->gr_group;
10859 				if (sin->sin_family != AF_INET) {
10860 					*outlenp = 0;
10861 					return (ENOPROTOOPT);
10862 				}
10863 				group = (ipaddr_t)sin->sin_addr.s_addr;
10864 				ifaddr = INADDR_ANY;
10865 				ifindexp = &greqp->gr_interface;
10866 			} else {
10867 				mreqp = (struct ip_mreq *)i1;
10868 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10869 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10870 				ifindexp = NULL;
10871 			}
10872 
10873 			/*
10874 			 * In the multirouting case, we need to replicate
10875 			 * the request on all interfaces that will take part
10876 			 * in replication.  We do so because multirouting is
10877 			 * reflective, thus we will probably receive multi-
10878 			 * casts on those interfaces.
10879 			 * The ip_multirt_apply_membership() succeeds if the
10880 			 * operation succeeds on at least one interface.
10881 			 */
10882 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10883 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10884 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10885 			if (ire != NULL) {
10886 				if (ire->ire_flags & RTF_MULTIRT) {
10887 					error = ip_multirt_apply_membership(
10888 					    optfn, ire, connp, checkonly, group,
10889 					    fmode, INADDR_ANY, first_mp);
10890 					done = B_TRUE;
10891 				}
10892 				ire_refrele(ire);
10893 			}
10894 			if (!done) {
10895 				error = optfn(connp, checkonly, group, ifaddr,
10896 				    ifindexp, fmode, INADDR_ANY, first_mp);
10897 			}
10898 			if (error) {
10899 				/*
10900 				 * EINPROGRESS is a soft error, needs retry
10901 				 * so don't make *outlenp zero.
10902 				 */
10903 				if (error != EINPROGRESS)
10904 					*outlenp = 0;
10905 				return (error);
10906 			}
10907 			/* OK return - copy input buffer into output buffer */
10908 			if (invalp != outvalp) {
10909 				/* don't trust bcopy for identical src/dst */
10910 				bcopy(invalp, outvalp, inlen);
10911 			}
10912 			*outlenp = inlen;
10913 			return (0);
10914 		}
10915 		case IP_BLOCK_SOURCE:
10916 		case IP_UNBLOCK_SOURCE:
10917 		case IP_ADD_SOURCE_MEMBERSHIP:
10918 		case IP_DROP_SOURCE_MEMBERSHIP:
10919 		case MCAST_BLOCK_SOURCE:
10920 		case MCAST_UNBLOCK_SOURCE:
10921 		case MCAST_JOIN_SOURCE_GROUP:
10922 		case MCAST_LEAVE_SOURCE_GROUP: {
10923 			struct ip_mreq_source *imreqp;
10924 			struct group_source_req *gsreqp;
10925 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10926 			uint32_t ifindex = 0;
10927 			mcast_record_t fmode;
10928 			struct sockaddr_in *sin;
10929 			ire_t *ire;
10930 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10931 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10932 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10933 
10934 			switch (name) {
10935 			case IP_BLOCK_SOURCE:
10936 				mcast_opt = B_FALSE;
10937 				/* FALLTHRU */
10938 			case MCAST_BLOCK_SOURCE:
10939 				fmode = MODE_IS_EXCLUDE;
10940 				optfn = ip_opt_add_group;
10941 				break;
10942 
10943 			case IP_UNBLOCK_SOURCE:
10944 				mcast_opt = B_FALSE;
10945 				/* FALLTHRU */
10946 			case MCAST_UNBLOCK_SOURCE:
10947 				fmode = MODE_IS_EXCLUDE;
10948 				optfn = ip_opt_delete_group;
10949 				break;
10950 
10951 			case IP_ADD_SOURCE_MEMBERSHIP:
10952 				mcast_opt = B_FALSE;
10953 				/* FALLTHRU */
10954 			case MCAST_JOIN_SOURCE_GROUP:
10955 				fmode = MODE_IS_INCLUDE;
10956 				optfn = ip_opt_add_group;
10957 				break;
10958 
10959 			case IP_DROP_SOURCE_MEMBERSHIP:
10960 				mcast_opt = B_FALSE;
10961 				/* FALLTHRU */
10962 			case MCAST_LEAVE_SOURCE_GROUP:
10963 				fmode = MODE_IS_INCLUDE;
10964 				optfn = ip_opt_delete_group;
10965 				break;
10966 			}
10967 
10968 			if (mcast_opt) {
10969 				gsreqp = (struct group_source_req *)i1;
10970 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10971 					*outlenp = 0;
10972 					return (ENOPROTOOPT);
10973 				}
10974 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10975 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10976 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10977 				src = (ipaddr_t)sin->sin_addr.s_addr;
10978 				ifindex = gsreqp->gsr_interface;
10979 			} else {
10980 				imreqp = (struct ip_mreq_source *)i1;
10981 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10982 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10983 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10984 			}
10985 
10986 			/*
10987 			 * In the multirouting case, we need to replicate
10988 			 * the request as noted in the mcast cases above.
10989 			 */
10990 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10991 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10992 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10993 			if (ire != NULL) {
10994 				if (ire->ire_flags & RTF_MULTIRT) {
10995 					error = ip_multirt_apply_membership(
10996 					    optfn, ire, connp, checkonly, grp,
10997 					    fmode, src, first_mp);
10998 					done = B_TRUE;
10999 				}
11000 				ire_refrele(ire);
11001 			}
11002 			if (!done) {
11003 				error = optfn(connp, checkonly, grp, ifaddr,
11004 				    &ifindex, fmode, src, first_mp);
11005 			}
11006 			if (error != 0) {
11007 				/*
11008 				 * EINPROGRESS is a soft error, needs retry
11009 				 * so don't make *outlenp zero.
11010 				 */
11011 				if (error != EINPROGRESS)
11012 					*outlenp = 0;
11013 				return (error);
11014 			}
11015 			/* OK return - copy input buffer into output buffer */
11016 			if (invalp != outvalp) {
11017 				bcopy(invalp, outvalp, inlen);
11018 			}
11019 			*outlenp = inlen;
11020 			return (0);
11021 		}
11022 		case IP_SEC_OPT:
11023 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11024 			if (error != 0) {
11025 				*outlenp = 0;
11026 				return (error);
11027 			}
11028 			break;
11029 		case IP_HDRINCL:
11030 		case IP_OPTIONS:
11031 		case T_IP_OPTIONS:
11032 		case IP_TOS:
11033 		case T_IP_TOS:
11034 		case IP_TTL:
11035 		case IP_RECVDSTADDR:
11036 		case IP_RECVOPTS:
11037 			/* OK return - copy input buffer into output buffer */
11038 			if (invalp != outvalp) {
11039 				/* don't trust bcopy for identical src/dst */
11040 				bcopy(invalp, outvalp, inlen);
11041 			}
11042 			*outlenp = inlen;
11043 			return (0);
11044 		case IP_RECVIF:
11045 			/* Retrieve the inbound interface index */
11046 			if (!checkonly) {
11047 				mutex_enter(&connp->conn_lock);
11048 				connp->conn_recvif = *i1 ? 1 : 0;
11049 				mutex_exit(&connp->conn_lock);
11050 			}
11051 			break;	/* goto sizeof (int) option return */
11052 		case IP_RECVPKTINFO:
11053 			if (!checkonly) {
11054 				mutex_enter(&connp->conn_lock);
11055 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11056 				mutex_exit(&connp->conn_lock);
11057 			}
11058 			break;	/* goto sizeof (int) option return */
11059 		case IP_RECVSLLA:
11060 			/* Retrieve the source link layer address */
11061 			if (!checkonly) {
11062 				mutex_enter(&connp->conn_lock);
11063 				connp->conn_recvslla = *i1 ? 1 : 0;
11064 				mutex_exit(&connp->conn_lock);
11065 			}
11066 			break;	/* goto sizeof (int) option return */
11067 		case MRT_INIT:
11068 		case MRT_DONE:
11069 		case MRT_ADD_VIF:
11070 		case MRT_DEL_VIF:
11071 		case MRT_ADD_MFC:
11072 		case MRT_DEL_MFC:
11073 		case MRT_ASSERT:
11074 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11075 				*outlenp = 0;
11076 				return (error);
11077 			}
11078 			error = ip_mrouter_set((int)name, q, checkonly,
11079 			    (uchar_t *)invalp, inlen, first_mp);
11080 			if (error) {
11081 				*outlenp = 0;
11082 				return (error);
11083 			}
11084 			/* OK return - copy input buffer into output buffer */
11085 			if (invalp != outvalp) {
11086 				/* don't trust bcopy for identical src/dst */
11087 				bcopy(invalp, outvalp, inlen);
11088 			}
11089 			*outlenp = inlen;
11090 			return (0);
11091 		case IP_BOUND_IF:
11092 		case IP_DHCPINIT_IF:
11093 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11094 			    level, name, first_mp);
11095 			if (error != 0)
11096 				return (error);
11097 			break; 		/* goto sizeof (int) option return */
11098 
11099 		case IP_UNSPEC_SRC:
11100 			/* Allow sending with a zero source address */
11101 			if (!checkonly) {
11102 				mutex_enter(&connp->conn_lock);
11103 				connp->conn_unspec_src = *i1 ? 1 : 0;
11104 				mutex_exit(&connp->conn_lock);
11105 			}
11106 			break;	/* goto sizeof (int) option return */
11107 		default:
11108 			/*
11109 			 * "soft" error (negative)
11110 			 * option not handled at this level
11111 			 * Note: Do not modify *outlenp
11112 			 */
11113 			return (-EINVAL);
11114 		}
11115 		break;
11116 	case IPPROTO_IPV6:
11117 		switch (name) {
11118 		case IPV6_BOUND_IF:
11119 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11120 			    level, name, first_mp);
11121 			if (error != 0)
11122 				return (error);
11123 			break; 		/* goto sizeof (int) option return */
11124 
11125 		case IPV6_MULTICAST_IF:
11126 			/*
11127 			 * The only possible errors are EINPROGRESS and
11128 			 * EINVAL. EINPROGRESS will be restarted and is not
11129 			 * a hard error. We call this option on both V4 and V6
11130 			 * If both return EINVAL, then this call returns
11131 			 * EINVAL. If at least one of them succeeds we
11132 			 * return success.
11133 			 */
11134 			found = B_FALSE;
11135 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11136 			    level, name, first_mp);
11137 			if (error == EINPROGRESS)
11138 				return (error);
11139 			if (error == 0)
11140 				found = B_TRUE;
11141 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11142 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11143 			if (error == 0)
11144 				found = B_TRUE;
11145 			if (!found)
11146 				return (error);
11147 			break; 		/* goto sizeof (int) option return */
11148 
11149 		case IPV6_MULTICAST_HOPS:
11150 			/* Recorded in transport above IP */
11151 			break;	/* goto sizeof (int) option return */
11152 		case IPV6_MULTICAST_LOOP:
11153 			if (!checkonly) {
11154 				mutex_enter(&connp->conn_lock);
11155 				connp->conn_multicast_loop = *i1;
11156 				mutex_exit(&connp->conn_lock);
11157 			}
11158 			break;	/* goto sizeof (int) option return */
11159 		case IPV6_JOIN_GROUP:
11160 		case MCAST_JOIN_GROUP:
11161 		case IPV6_LEAVE_GROUP:
11162 		case MCAST_LEAVE_GROUP: {
11163 			struct ipv6_mreq *ip_mreqp;
11164 			struct group_req *greqp;
11165 			ire_t *ire;
11166 			boolean_t done = B_FALSE;
11167 			in6_addr_t groupv6;
11168 			uint32_t ifindex;
11169 			boolean_t mcast_opt = B_TRUE;
11170 			mcast_record_t fmode;
11171 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11172 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11173 
11174 			switch (name) {
11175 			case IPV6_JOIN_GROUP:
11176 				mcast_opt = B_FALSE;
11177 				/* FALLTHRU */
11178 			case MCAST_JOIN_GROUP:
11179 				fmode = MODE_IS_EXCLUDE;
11180 				optfn = ip_opt_add_group_v6;
11181 				break;
11182 
11183 			case IPV6_LEAVE_GROUP:
11184 				mcast_opt = B_FALSE;
11185 				/* FALLTHRU */
11186 			case MCAST_LEAVE_GROUP:
11187 				fmode = MODE_IS_INCLUDE;
11188 				optfn = ip_opt_delete_group_v6;
11189 				break;
11190 			}
11191 
11192 			if (mcast_opt) {
11193 				struct sockaddr_in *sin;
11194 				struct sockaddr_in6 *sin6;
11195 				greqp = (struct group_req *)i1;
11196 				if (greqp->gr_group.ss_family == AF_INET) {
11197 					sin = (struct sockaddr_in *)
11198 					    &(greqp->gr_group);
11199 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11200 					    &groupv6);
11201 				} else {
11202 					sin6 = (struct sockaddr_in6 *)
11203 					    &(greqp->gr_group);
11204 					groupv6 = sin6->sin6_addr;
11205 				}
11206 				ifindex = greqp->gr_interface;
11207 			} else {
11208 				ip_mreqp = (struct ipv6_mreq *)i1;
11209 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11210 				ifindex = ip_mreqp->ipv6mr_interface;
11211 			}
11212 			/*
11213 			 * In the multirouting case, we need to replicate
11214 			 * the request on all interfaces that will take part
11215 			 * in replication.  We do so because multirouting is
11216 			 * reflective, thus we will probably receive multi-
11217 			 * casts on those interfaces.
11218 			 * The ip_multirt_apply_membership_v6() succeeds if
11219 			 * the operation succeeds on at least one interface.
11220 			 */
11221 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11222 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11223 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11224 			if (ire != NULL) {
11225 				if (ire->ire_flags & RTF_MULTIRT) {
11226 					error = ip_multirt_apply_membership_v6(
11227 					    optfn, ire, connp, checkonly,
11228 					    &groupv6, fmode, &ipv6_all_zeros,
11229 					    first_mp);
11230 					done = B_TRUE;
11231 				}
11232 				ire_refrele(ire);
11233 			}
11234 			if (!done) {
11235 				error = optfn(connp, checkonly, &groupv6,
11236 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11237 			}
11238 			if (error) {
11239 				/*
11240 				 * EINPROGRESS is a soft error, needs retry
11241 				 * so don't make *outlenp zero.
11242 				 */
11243 				if (error != EINPROGRESS)
11244 					*outlenp = 0;
11245 				return (error);
11246 			}
11247 			/* OK return - copy input buffer into output buffer */
11248 			if (invalp != outvalp) {
11249 				/* don't trust bcopy for identical src/dst */
11250 				bcopy(invalp, outvalp, inlen);
11251 			}
11252 			*outlenp = inlen;
11253 			return (0);
11254 		}
11255 		case MCAST_BLOCK_SOURCE:
11256 		case MCAST_UNBLOCK_SOURCE:
11257 		case MCAST_JOIN_SOURCE_GROUP:
11258 		case MCAST_LEAVE_SOURCE_GROUP: {
11259 			struct group_source_req *gsreqp;
11260 			in6_addr_t v6grp, v6src;
11261 			uint32_t ifindex;
11262 			mcast_record_t fmode;
11263 			ire_t *ire;
11264 			boolean_t done = B_FALSE;
11265 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11266 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11267 
11268 			switch (name) {
11269 			case MCAST_BLOCK_SOURCE:
11270 				fmode = MODE_IS_EXCLUDE;
11271 				optfn = ip_opt_add_group_v6;
11272 				break;
11273 			case MCAST_UNBLOCK_SOURCE:
11274 				fmode = MODE_IS_EXCLUDE;
11275 				optfn = ip_opt_delete_group_v6;
11276 				break;
11277 			case MCAST_JOIN_SOURCE_GROUP:
11278 				fmode = MODE_IS_INCLUDE;
11279 				optfn = ip_opt_add_group_v6;
11280 				break;
11281 			case MCAST_LEAVE_SOURCE_GROUP:
11282 				fmode = MODE_IS_INCLUDE;
11283 				optfn = ip_opt_delete_group_v6;
11284 				break;
11285 			}
11286 
11287 			gsreqp = (struct group_source_req *)i1;
11288 			ifindex = gsreqp->gsr_interface;
11289 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11290 				struct sockaddr_in *s;
11291 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11292 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11293 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11294 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11295 			} else {
11296 				struct sockaddr_in6 *s6;
11297 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11298 				v6grp = s6->sin6_addr;
11299 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11300 				v6src = s6->sin6_addr;
11301 			}
11302 
11303 			/*
11304 			 * In the multirouting case, we need to replicate
11305 			 * the request as noted in the mcast cases above.
11306 			 */
11307 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11308 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11309 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11310 			if (ire != NULL) {
11311 				if (ire->ire_flags & RTF_MULTIRT) {
11312 					error = ip_multirt_apply_membership_v6(
11313 					    optfn, ire, connp, checkonly,
11314 					    &v6grp, fmode, &v6src, first_mp);
11315 					done = B_TRUE;
11316 				}
11317 				ire_refrele(ire);
11318 			}
11319 			if (!done) {
11320 				error = optfn(connp, checkonly, &v6grp,
11321 				    ifindex, fmode, &v6src, first_mp);
11322 			}
11323 			if (error != 0) {
11324 				/*
11325 				 * EINPROGRESS is a soft error, needs retry
11326 				 * so don't make *outlenp zero.
11327 				 */
11328 				if (error != EINPROGRESS)
11329 					*outlenp = 0;
11330 				return (error);
11331 			}
11332 			/* OK return - copy input buffer into output buffer */
11333 			if (invalp != outvalp) {
11334 				bcopy(invalp, outvalp, inlen);
11335 			}
11336 			*outlenp = inlen;
11337 			return (0);
11338 		}
11339 		case IPV6_UNICAST_HOPS:
11340 			/* Recorded in transport above IP */
11341 			break;	/* goto sizeof (int) option return */
11342 		case IPV6_UNSPEC_SRC:
11343 			/* Allow sending with a zero source address */
11344 			if (!checkonly) {
11345 				mutex_enter(&connp->conn_lock);
11346 				connp->conn_unspec_src = *i1 ? 1 : 0;
11347 				mutex_exit(&connp->conn_lock);
11348 			}
11349 			break;	/* goto sizeof (int) option return */
11350 		case IPV6_RECVPKTINFO:
11351 			if (!checkonly) {
11352 				mutex_enter(&connp->conn_lock);
11353 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11354 				mutex_exit(&connp->conn_lock);
11355 			}
11356 			break;	/* goto sizeof (int) option return */
11357 		case IPV6_RECVTCLASS:
11358 			if (!checkonly) {
11359 				if (*i1 < 0 || *i1 > 1) {
11360 					return (EINVAL);
11361 				}
11362 				mutex_enter(&connp->conn_lock);
11363 				connp->conn_ipv6_recvtclass = *i1;
11364 				mutex_exit(&connp->conn_lock);
11365 			}
11366 			break;
11367 		case IPV6_RECVPATHMTU:
11368 			if (!checkonly) {
11369 				if (*i1 < 0 || *i1 > 1) {
11370 					return (EINVAL);
11371 				}
11372 				mutex_enter(&connp->conn_lock);
11373 				connp->conn_ipv6_recvpathmtu = *i1;
11374 				mutex_exit(&connp->conn_lock);
11375 			}
11376 			break;
11377 		case IPV6_RECVHOPLIMIT:
11378 			if (!checkonly) {
11379 				mutex_enter(&connp->conn_lock);
11380 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11381 				mutex_exit(&connp->conn_lock);
11382 			}
11383 			break;	/* goto sizeof (int) option return */
11384 		case IPV6_RECVHOPOPTS:
11385 			if (!checkonly) {
11386 				mutex_enter(&connp->conn_lock);
11387 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11388 				mutex_exit(&connp->conn_lock);
11389 			}
11390 			break;	/* goto sizeof (int) option return */
11391 		case IPV6_RECVDSTOPTS:
11392 			if (!checkonly) {
11393 				mutex_enter(&connp->conn_lock);
11394 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11395 				mutex_exit(&connp->conn_lock);
11396 			}
11397 			break;	/* goto sizeof (int) option return */
11398 		case IPV6_RECVRTHDR:
11399 			if (!checkonly) {
11400 				mutex_enter(&connp->conn_lock);
11401 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11402 				mutex_exit(&connp->conn_lock);
11403 			}
11404 			break;	/* goto sizeof (int) option return */
11405 		case IPV6_RECVRTHDRDSTOPTS:
11406 			if (!checkonly) {
11407 				mutex_enter(&connp->conn_lock);
11408 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11409 				mutex_exit(&connp->conn_lock);
11410 			}
11411 			break;	/* goto sizeof (int) option return */
11412 		case IPV6_PKTINFO:
11413 			if (inlen == 0)
11414 				return (-EINVAL);	/* clearing option */
11415 			error = ip6_set_pktinfo(cr, connp,
11416 			    (struct in6_pktinfo *)invalp);
11417 			if (error != 0)
11418 				*outlenp = 0;
11419 			else
11420 				*outlenp = inlen;
11421 			return (error);
11422 		case IPV6_NEXTHOP: {
11423 			struct sockaddr_in6 *sin6;
11424 
11425 			/* Verify that the nexthop is reachable */
11426 			if (inlen == 0)
11427 				return (-EINVAL);	/* clearing option */
11428 
11429 			sin6 = (struct sockaddr_in6 *)invalp;
11430 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11431 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11432 			    NULL, MATCH_IRE_DEFAULT, ipst);
11433 
11434 			if (ire == NULL) {
11435 				*outlenp = 0;
11436 				return (EHOSTUNREACH);
11437 			}
11438 			ire_refrele(ire);
11439 			return (-EINVAL);
11440 		}
11441 		case IPV6_SEC_OPT:
11442 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11443 			if (error != 0) {
11444 				*outlenp = 0;
11445 				return (error);
11446 			}
11447 			break;
11448 		case IPV6_SRC_PREFERENCES: {
11449 			/*
11450 			 * This is implemented strictly in the ip module
11451 			 * (here and in tcp_opt_*() to accomodate tcp
11452 			 * sockets).  Modules above ip pass this option
11453 			 * down here since ip is the only one that needs to
11454 			 * be aware of source address preferences.
11455 			 *
11456 			 * This socket option only affects connected
11457 			 * sockets that haven't already bound to a specific
11458 			 * IPv6 address.  In other words, sockets that
11459 			 * don't call bind() with an address other than the
11460 			 * unspecified address and that call connect().
11461 			 * ip_bind_connected_v6() passes these preferences
11462 			 * to the ipif_select_source_v6() function.
11463 			 */
11464 			if (inlen != sizeof (uint32_t))
11465 				return (EINVAL);
11466 			error = ip6_set_src_preferences(connp,
11467 			    *(uint32_t *)invalp);
11468 			if (error != 0) {
11469 				*outlenp = 0;
11470 				return (error);
11471 			} else {
11472 				*outlenp = sizeof (uint32_t);
11473 			}
11474 			break;
11475 		}
11476 		case IPV6_V6ONLY:
11477 			if (*i1 < 0 || *i1 > 1) {
11478 				return (EINVAL);
11479 			}
11480 			mutex_enter(&connp->conn_lock);
11481 			connp->conn_ipv6_v6only = *i1;
11482 			mutex_exit(&connp->conn_lock);
11483 			break;
11484 		default:
11485 			return (-EINVAL);
11486 		}
11487 		break;
11488 	default:
11489 		/*
11490 		 * "soft" error (negative)
11491 		 * option not handled at this level
11492 		 * Note: Do not modify *outlenp
11493 		 */
11494 		return (-EINVAL);
11495 	}
11496 	/*
11497 	 * Common case of return from an option that is sizeof (int)
11498 	 */
11499 	*(int *)outvalp = *i1;
11500 	*outlenp = sizeof (int);
11501 	return (0);
11502 }
11503 
11504 /*
11505  * This routine gets default values of certain options whose default
11506  * values are maintained by protocol specific code
11507  */
11508 /* ARGSUSED */
11509 int
11510 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11511 {
11512 	int *i1 = (int *)ptr;
11513 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11514 
11515 	switch (level) {
11516 	case IPPROTO_IP:
11517 		switch (name) {
11518 		case IP_MULTICAST_TTL:
11519 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11520 			return (sizeof (uchar_t));
11521 		case IP_MULTICAST_LOOP:
11522 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11523 			return (sizeof (uchar_t));
11524 		default:
11525 			return (-1);
11526 		}
11527 	case IPPROTO_IPV6:
11528 		switch (name) {
11529 		case IPV6_UNICAST_HOPS:
11530 			*i1 = ipst->ips_ipv6_def_hops;
11531 			return (sizeof (int));
11532 		case IPV6_MULTICAST_HOPS:
11533 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11534 			return (sizeof (int));
11535 		case IPV6_MULTICAST_LOOP:
11536 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11537 			return (sizeof (int));
11538 		case IPV6_V6ONLY:
11539 			*i1 = 1;
11540 			return (sizeof (int));
11541 		default:
11542 			return (-1);
11543 		}
11544 	default:
11545 		return (-1);
11546 	}
11547 	/* NOTREACHED */
11548 }
11549 
11550 /*
11551  * Given a destination address and a pointer to where to put the information
11552  * this routine fills in the mtuinfo.
11553  */
11554 int
11555 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11556     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11557 {
11558 	ire_t *ire;
11559 	ip_stack_t	*ipst = ns->netstack_ip;
11560 
11561 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11562 		return (-1);
11563 
11564 	bzero(mtuinfo, sizeof (*mtuinfo));
11565 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11566 	mtuinfo->ip6m_addr.sin6_port = port;
11567 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11568 
11569 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11570 	if (ire != NULL) {
11571 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11572 		ire_refrele(ire);
11573 	} else {
11574 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11575 	}
11576 	return (sizeof (struct ip6_mtuinfo));
11577 }
11578 
11579 /*
11580  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11581  * checking of cred and that ip_g_mrouter is set should be done and
11582  * isn't.  This doesn't matter as the error checking is done properly for the
11583  * other MRT options coming in through ip_opt_set.
11584  */
11585 int
11586 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11587 {
11588 	conn_t		*connp = Q_TO_CONN(q);
11589 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11590 
11591 	switch (level) {
11592 	case IPPROTO_IP:
11593 		switch (name) {
11594 		case MRT_VERSION:
11595 		case MRT_ASSERT:
11596 			(void) ip_mrouter_get(name, q, ptr);
11597 			return (sizeof (int));
11598 		case IP_SEC_OPT:
11599 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11600 		case IP_NEXTHOP:
11601 			if (connp->conn_nexthop_set) {
11602 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11603 				return (sizeof (ipaddr_t));
11604 			} else
11605 				return (0);
11606 		case IP_RECVPKTINFO:
11607 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11608 			return (sizeof (int));
11609 		default:
11610 			break;
11611 		}
11612 		break;
11613 	case IPPROTO_IPV6:
11614 		switch (name) {
11615 		case IPV6_SEC_OPT:
11616 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11617 		case IPV6_SRC_PREFERENCES: {
11618 			return (ip6_get_src_preferences(connp,
11619 			    (uint32_t *)ptr));
11620 		}
11621 		case IPV6_V6ONLY:
11622 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11623 			return (sizeof (int));
11624 		case IPV6_PATHMTU:
11625 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11626 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11627 		default:
11628 			break;
11629 		}
11630 		break;
11631 	default:
11632 		break;
11633 	}
11634 	return (-1);
11635 }
11636 /* Named Dispatch routine to get a current value out of our parameter table. */
11637 /* ARGSUSED */
11638 static int
11639 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11640 {
11641 	ipparam_t *ippa = (ipparam_t *)cp;
11642 
11643 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11644 	return (0);
11645 }
11646 
11647 /* ARGSUSED */
11648 static int
11649 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11650 {
11651 
11652 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11653 	return (0);
11654 }
11655 
11656 /*
11657  * Set ip{,6}_forwarding values.  This means walking through all of the
11658  * ill's and toggling their forwarding values.
11659  */
11660 /* ARGSUSED */
11661 static int
11662 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11663 {
11664 	long new_value;
11665 	int *forwarding_value = (int *)cp;
11666 	ill_t *ill;
11667 	boolean_t isv6;
11668 	ill_walk_context_t ctx;
11669 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11670 
11671 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11672 
11673 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11674 	    new_value < 0 || new_value > 1) {
11675 		return (EINVAL);
11676 	}
11677 
11678 	*forwarding_value = new_value;
11679 
11680 	/*
11681 	 * Regardless of the current value of ip_forwarding, set all per-ill
11682 	 * values of ip_forwarding to the value being set.
11683 	 *
11684 	 * Bring all the ill's up to date with the new global value.
11685 	 */
11686 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11687 
11688 	if (isv6)
11689 		ill = ILL_START_WALK_V6(&ctx, ipst);
11690 	else
11691 		ill = ILL_START_WALK_V4(&ctx, ipst);
11692 
11693 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11694 		(void) ill_forward_set(ill, new_value != 0);
11695 
11696 	rw_exit(&ipst->ips_ill_g_lock);
11697 	return (0);
11698 }
11699 
11700 /*
11701  * Walk through the param array specified registering each element with the
11702  * Named Dispatch handler. This is called only during init. So it is ok
11703  * not to acquire any locks
11704  */
11705 static boolean_t
11706 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11707     ipndp_t *ipnd, size_t ipnd_cnt)
11708 {
11709 	for (; ippa_cnt-- > 0; ippa++) {
11710 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11711 			if (!nd_load(ndp, ippa->ip_param_name,
11712 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11713 				nd_free(ndp);
11714 				return (B_FALSE);
11715 			}
11716 		}
11717 	}
11718 
11719 	for (; ipnd_cnt-- > 0; ipnd++) {
11720 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11721 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11722 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11723 			    ipnd->ip_ndp_data)) {
11724 				nd_free(ndp);
11725 				return (B_FALSE);
11726 			}
11727 		}
11728 	}
11729 
11730 	return (B_TRUE);
11731 }
11732 
11733 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11734 /* ARGSUSED */
11735 static int
11736 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11737 {
11738 	long		new_value;
11739 	ipparam_t	*ippa = (ipparam_t *)cp;
11740 
11741 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11742 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11743 		return (EINVAL);
11744 	}
11745 	ippa->ip_param_value = new_value;
11746 	return (0);
11747 }
11748 
11749 /*
11750  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11751  * When an ipf is passed here for the first time, if
11752  * we already have in-order fragments on the queue, we convert from the fast-
11753  * path reassembly scheme to the hard-case scheme.  From then on, additional
11754  * fragments are reassembled here.  We keep track of the start and end offsets
11755  * of each piece, and the number of holes in the chain.  When the hole count
11756  * goes to zero, we are done!
11757  *
11758  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11759  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11760  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11761  * after the call to ip_reassemble().
11762  */
11763 int
11764 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11765     size_t msg_len)
11766 {
11767 	uint_t	end;
11768 	mblk_t	*next_mp;
11769 	mblk_t	*mp1;
11770 	uint_t	offset;
11771 	boolean_t incr_dups = B_TRUE;
11772 	boolean_t offset_zero_seen = B_FALSE;
11773 	boolean_t pkt_boundary_checked = B_FALSE;
11774 
11775 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11776 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11777 
11778 	/* Add in byte count */
11779 	ipf->ipf_count += msg_len;
11780 	if (ipf->ipf_end) {
11781 		/*
11782 		 * We were part way through in-order reassembly, but now there
11783 		 * is a hole.  We walk through messages already queued, and
11784 		 * mark them for hard case reassembly.  We know that up till
11785 		 * now they were in order starting from offset zero.
11786 		 */
11787 		offset = 0;
11788 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11789 			IP_REASS_SET_START(mp1, offset);
11790 			if (offset == 0) {
11791 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11792 				offset = -ipf->ipf_nf_hdr_len;
11793 			}
11794 			offset += mp1->b_wptr - mp1->b_rptr;
11795 			IP_REASS_SET_END(mp1, offset);
11796 		}
11797 		/* One hole at the end. */
11798 		ipf->ipf_hole_cnt = 1;
11799 		/* Brand it as a hard case, forever. */
11800 		ipf->ipf_end = 0;
11801 	}
11802 	/* Walk through all the new pieces. */
11803 	do {
11804 		end = start + (mp->b_wptr - mp->b_rptr);
11805 		/*
11806 		 * If start is 0, decrease 'end' only for the first mblk of
11807 		 * the fragment. Otherwise 'end' can get wrong value in the
11808 		 * second pass of the loop if first mblk is exactly the
11809 		 * size of ipf_nf_hdr_len.
11810 		 */
11811 		if (start == 0 && !offset_zero_seen) {
11812 			/* First segment */
11813 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11814 			end -= ipf->ipf_nf_hdr_len;
11815 			offset_zero_seen = B_TRUE;
11816 		}
11817 		next_mp = mp->b_cont;
11818 		/*
11819 		 * We are checking to see if there is any interesing data
11820 		 * to process.  If there isn't and the mblk isn't the
11821 		 * one which carries the unfragmentable header then we
11822 		 * drop it.  It's possible to have just the unfragmentable
11823 		 * header come through without any data.  That needs to be
11824 		 * saved.
11825 		 *
11826 		 * If the assert at the top of this function holds then the
11827 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11828 		 * is infrequently traveled enough that the test is left in
11829 		 * to protect against future code changes which break that
11830 		 * invariant.
11831 		 */
11832 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11833 			/* Empty.  Blast it. */
11834 			IP_REASS_SET_START(mp, 0);
11835 			IP_REASS_SET_END(mp, 0);
11836 			/*
11837 			 * If the ipf points to the mblk we are about to free,
11838 			 * update ipf to point to the next mblk (or NULL
11839 			 * if none).
11840 			 */
11841 			if (ipf->ipf_mp->b_cont == mp)
11842 				ipf->ipf_mp->b_cont = next_mp;
11843 			freeb(mp);
11844 			continue;
11845 		}
11846 		mp->b_cont = NULL;
11847 		IP_REASS_SET_START(mp, start);
11848 		IP_REASS_SET_END(mp, end);
11849 		if (!ipf->ipf_tail_mp) {
11850 			ipf->ipf_tail_mp = mp;
11851 			ipf->ipf_mp->b_cont = mp;
11852 			if (start == 0 || !more) {
11853 				ipf->ipf_hole_cnt = 1;
11854 				/*
11855 				 * if the first fragment comes in more than one
11856 				 * mblk, this loop will be executed for each
11857 				 * mblk. Need to adjust hole count so exiting
11858 				 * this routine will leave hole count at 1.
11859 				 */
11860 				if (next_mp)
11861 					ipf->ipf_hole_cnt++;
11862 			} else
11863 				ipf->ipf_hole_cnt = 2;
11864 			continue;
11865 		} else if (ipf->ipf_last_frag_seen && !more &&
11866 		    !pkt_boundary_checked) {
11867 			/*
11868 			 * We check datagram boundary only if this fragment
11869 			 * claims to be the last fragment and we have seen a
11870 			 * last fragment in the past too. We do this only
11871 			 * once for a given fragment.
11872 			 *
11873 			 * start cannot be 0 here as fragments with start=0
11874 			 * and MF=0 gets handled as a complete packet. These
11875 			 * fragments should not reach here.
11876 			 */
11877 
11878 			if (start + msgdsize(mp) !=
11879 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11880 				/*
11881 				 * We have two fragments both of which claim
11882 				 * to be the last fragment but gives conflicting
11883 				 * information about the whole datagram size.
11884 				 * Something fishy is going on. Drop the
11885 				 * fragment and free up the reassembly list.
11886 				 */
11887 				return (IP_REASS_FAILED);
11888 			}
11889 
11890 			/*
11891 			 * We shouldn't come to this code block again for this
11892 			 * particular fragment.
11893 			 */
11894 			pkt_boundary_checked = B_TRUE;
11895 		}
11896 
11897 		/* New stuff at or beyond tail? */
11898 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11899 		if (start >= offset) {
11900 			if (ipf->ipf_last_frag_seen) {
11901 				/* current fragment is beyond last fragment */
11902 				return (IP_REASS_FAILED);
11903 			}
11904 			/* Link it on end. */
11905 			ipf->ipf_tail_mp->b_cont = mp;
11906 			ipf->ipf_tail_mp = mp;
11907 			if (more) {
11908 				if (start != offset)
11909 					ipf->ipf_hole_cnt++;
11910 			} else if (start == offset && next_mp == NULL)
11911 					ipf->ipf_hole_cnt--;
11912 			continue;
11913 		}
11914 		mp1 = ipf->ipf_mp->b_cont;
11915 		offset = IP_REASS_START(mp1);
11916 		/* New stuff at the front? */
11917 		if (start < offset) {
11918 			if (start == 0) {
11919 				if (end >= offset) {
11920 					/* Nailed the hole at the begining. */
11921 					ipf->ipf_hole_cnt--;
11922 				}
11923 			} else if (end < offset) {
11924 				/*
11925 				 * A hole, stuff, and a hole where there used
11926 				 * to be just a hole.
11927 				 */
11928 				ipf->ipf_hole_cnt++;
11929 			}
11930 			mp->b_cont = mp1;
11931 			/* Check for overlap. */
11932 			while (end > offset) {
11933 				if (end < IP_REASS_END(mp1)) {
11934 					mp->b_wptr -= end - offset;
11935 					IP_REASS_SET_END(mp, offset);
11936 					BUMP_MIB(ill->ill_ip_mib,
11937 					    ipIfStatsReasmPartDups);
11938 					break;
11939 				}
11940 				/* Did we cover another hole? */
11941 				if ((mp1->b_cont &&
11942 				    IP_REASS_END(mp1) !=
11943 				    IP_REASS_START(mp1->b_cont) &&
11944 				    end >= IP_REASS_START(mp1->b_cont)) ||
11945 				    (!ipf->ipf_last_frag_seen && !more)) {
11946 					ipf->ipf_hole_cnt--;
11947 				}
11948 				/* Clip out mp1. */
11949 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11950 					/*
11951 					 * After clipping out mp1, this guy
11952 					 * is now hanging off the end.
11953 					 */
11954 					ipf->ipf_tail_mp = mp;
11955 				}
11956 				IP_REASS_SET_START(mp1, 0);
11957 				IP_REASS_SET_END(mp1, 0);
11958 				/* Subtract byte count */
11959 				ipf->ipf_count -= mp1->b_datap->db_lim -
11960 				    mp1->b_datap->db_base;
11961 				freeb(mp1);
11962 				BUMP_MIB(ill->ill_ip_mib,
11963 				    ipIfStatsReasmPartDups);
11964 				mp1 = mp->b_cont;
11965 				if (!mp1)
11966 					break;
11967 				offset = IP_REASS_START(mp1);
11968 			}
11969 			ipf->ipf_mp->b_cont = mp;
11970 			continue;
11971 		}
11972 		/*
11973 		 * The new piece starts somewhere between the start of the head
11974 		 * and before the end of the tail.
11975 		 */
11976 		for (; mp1; mp1 = mp1->b_cont) {
11977 			offset = IP_REASS_END(mp1);
11978 			if (start < offset) {
11979 				if (end <= offset) {
11980 					/* Nothing new. */
11981 					IP_REASS_SET_START(mp, 0);
11982 					IP_REASS_SET_END(mp, 0);
11983 					/* Subtract byte count */
11984 					ipf->ipf_count -= mp->b_datap->db_lim -
11985 					    mp->b_datap->db_base;
11986 					if (incr_dups) {
11987 						ipf->ipf_num_dups++;
11988 						incr_dups = B_FALSE;
11989 					}
11990 					freeb(mp);
11991 					BUMP_MIB(ill->ill_ip_mib,
11992 					    ipIfStatsReasmDuplicates);
11993 					break;
11994 				}
11995 				/*
11996 				 * Trim redundant stuff off beginning of new
11997 				 * piece.
11998 				 */
11999 				IP_REASS_SET_START(mp, offset);
12000 				mp->b_rptr += offset - start;
12001 				BUMP_MIB(ill->ill_ip_mib,
12002 				    ipIfStatsReasmPartDups);
12003 				start = offset;
12004 				if (!mp1->b_cont) {
12005 					/*
12006 					 * After trimming, this guy is now
12007 					 * hanging off the end.
12008 					 */
12009 					mp1->b_cont = mp;
12010 					ipf->ipf_tail_mp = mp;
12011 					if (!more) {
12012 						ipf->ipf_hole_cnt--;
12013 					}
12014 					break;
12015 				}
12016 			}
12017 			if (start >= IP_REASS_START(mp1->b_cont))
12018 				continue;
12019 			/* Fill a hole */
12020 			if (start > offset)
12021 				ipf->ipf_hole_cnt++;
12022 			mp->b_cont = mp1->b_cont;
12023 			mp1->b_cont = mp;
12024 			mp1 = mp->b_cont;
12025 			offset = IP_REASS_START(mp1);
12026 			if (end >= offset) {
12027 				ipf->ipf_hole_cnt--;
12028 				/* Check for overlap. */
12029 				while (end > offset) {
12030 					if (end < IP_REASS_END(mp1)) {
12031 						mp->b_wptr -= end - offset;
12032 						IP_REASS_SET_END(mp, offset);
12033 						/*
12034 						 * TODO we might bump
12035 						 * this up twice if there is
12036 						 * overlap at both ends.
12037 						 */
12038 						BUMP_MIB(ill->ill_ip_mib,
12039 						    ipIfStatsReasmPartDups);
12040 						break;
12041 					}
12042 					/* Did we cover another hole? */
12043 					if ((mp1->b_cont &&
12044 					    IP_REASS_END(mp1)
12045 					    != IP_REASS_START(mp1->b_cont) &&
12046 					    end >=
12047 					    IP_REASS_START(mp1->b_cont)) ||
12048 					    (!ipf->ipf_last_frag_seen &&
12049 					    !more)) {
12050 						ipf->ipf_hole_cnt--;
12051 					}
12052 					/* Clip out mp1. */
12053 					if ((mp->b_cont = mp1->b_cont) ==
12054 					    NULL) {
12055 						/*
12056 						 * After clipping out mp1,
12057 						 * this guy is now hanging
12058 						 * off the end.
12059 						 */
12060 						ipf->ipf_tail_mp = mp;
12061 					}
12062 					IP_REASS_SET_START(mp1, 0);
12063 					IP_REASS_SET_END(mp1, 0);
12064 					/* Subtract byte count */
12065 					ipf->ipf_count -=
12066 					    mp1->b_datap->db_lim -
12067 					    mp1->b_datap->db_base;
12068 					freeb(mp1);
12069 					BUMP_MIB(ill->ill_ip_mib,
12070 					    ipIfStatsReasmPartDups);
12071 					mp1 = mp->b_cont;
12072 					if (!mp1)
12073 						break;
12074 					offset = IP_REASS_START(mp1);
12075 				}
12076 			}
12077 			break;
12078 		}
12079 	} while (start = end, mp = next_mp);
12080 
12081 	/* Fragment just processed could be the last one. Remember this fact */
12082 	if (!more)
12083 		ipf->ipf_last_frag_seen = B_TRUE;
12084 
12085 	/* Still got holes? */
12086 	if (ipf->ipf_hole_cnt)
12087 		return (IP_REASS_PARTIAL);
12088 	/* Clean up overloaded fields to avoid upstream disasters. */
12089 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12090 		IP_REASS_SET_START(mp1, 0);
12091 		IP_REASS_SET_END(mp1, 0);
12092 	}
12093 	return (IP_REASS_COMPLETE);
12094 }
12095 
12096 /*
12097  * ipsec processing for the fast path, used for input UDP Packets
12098  * Returns true if ready for passup to UDP.
12099  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12100  * was an ESP-in-UDP packet, etc.).
12101  */
12102 static boolean_t
12103 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12104     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12105 {
12106 	uint32_t	ill_index;
12107 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12108 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12109 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12110 	udp_t		*udp = connp->conn_udp;
12111 
12112 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12113 	/* The ill_index of the incoming ILL */
12114 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12115 
12116 	/* pass packet up to the transport */
12117 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12118 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12119 		    NULL, mctl_present);
12120 		if (*first_mpp == NULL) {
12121 			return (B_FALSE);
12122 		}
12123 	}
12124 
12125 	/* Initiate IPPF processing for fastpath UDP */
12126 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12127 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12128 		if (*mpp == NULL) {
12129 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12130 			    "deferred/dropped during IPPF processing\n"));
12131 			return (B_FALSE);
12132 		}
12133 	}
12134 	/*
12135 	 * Remove 0-spi if it's 0, or move everything behind
12136 	 * the UDP header over it and forward to ESP via
12137 	 * ip_proto_input().
12138 	 */
12139 	if (udp->udp_nat_t_endpoint) {
12140 		if (mctl_present) {
12141 			/* mctl_present *shouldn't* happen. */
12142 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12143 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12144 			    &ipss->ipsec_dropper);
12145 			*first_mpp = NULL;
12146 			return (B_FALSE);
12147 		}
12148 
12149 		/* "ill" is "recv_ill" in actuality. */
12150 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12151 			return (B_FALSE);
12152 
12153 		/* Else continue like a normal UDP packet. */
12154 	}
12155 
12156 	/*
12157 	 * We make the checks as below since we are in the fast path
12158 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12159 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12160 	 */
12161 	if (connp->conn_recvif || connp->conn_recvslla ||
12162 	    connp->conn_ip_recvpktinfo) {
12163 		if (connp->conn_recvif) {
12164 			in_flags = IPF_RECVIF;
12165 		}
12166 		/*
12167 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12168 		 * so the flag passed to ip_add_info is based on IP version
12169 		 * of connp.
12170 		 */
12171 		if (connp->conn_ip_recvpktinfo) {
12172 			if (connp->conn_af_isv6) {
12173 				/*
12174 				 * V6 only needs index
12175 				 */
12176 				in_flags |= IPF_RECVIF;
12177 			} else {
12178 				/*
12179 				 * V4 needs index + matching address.
12180 				 */
12181 				in_flags |= IPF_RECVADDR;
12182 			}
12183 		}
12184 		if (connp->conn_recvslla) {
12185 			in_flags |= IPF_RECVSLLA;
12186 		}
12187 		/*
12188 		 * since in_flags are being set ill will be
12189 		 * referenced in ip_add_info, so it better not
12190 		 * be NULL.
12191 		 */
12192 		/*
12193 		 * the actual data will be contained in b_cont
12194 		 * upon successful return of the following call.
12195 		 * If the call fails then the original mblk is
12196 		 * returned.
12197 		 */
12198 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12199 		    ipst);
12200 	}
12201 
12202 	return (B_TRUE);
12203 }
12204 
12205 /*
12206  * Fragmentation reassembly.  Each ILL has a hash table for
12207  * queuing packets undergoing reassembly for all IPIFs
12208  * associated with the ILL.  The hash is based on the packet
12209  * IP ident field.  The ILL frag hash table was allocated
12210  * as a timer block at the time the ILL was created.  Whenever
12211  * there is anything on the reassembly queue, the timer will
12212  * be running.  Returns B_TRUE if successful else B_FALSE;
12213  * frees mp on failure.
12214  */
12215 static boolean_t
12216 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12217     uint32_t *cksum_val, uint16_t *cksum_flags)
12218 {
12219 	uint32_t	frag_offset_flags;
12220 	mblk_t		*mp = *mpp;
12221 	mblk_t		*t_mp;
12222 	ipaddr_t	dst;
12223 	uint8_t		proto = ipha->ipha_protocol;
12224 	uint32_t	sum_val;
12225 	uint16_t	sum_flags;
12226 	ipf_t		*ipf;
12227 	ipf_t		**ipfp;
12228 	ipfb_t		*ipfb;
12229 	uint16_t	ident;
12230 	uint32_t	offset;
12231 	ipaddr_t	src;
12232 	uint_t		hdr_length;
12233 	uint32_t	end;
12234 	mblk_t		*mp1;
12235 	mblk_t		*tail_mp;
12236 	size_t		count;
12237 	size_t		msg_len;
12238 	uint8_t		ecn_info = 0;
12239 	uint32_t	packet_size;
12240 	boolean_t	pruned = B_FALSE;
12241 	ip_stack_t *ipst = ill->ill_ipst;
12242 
12243 	if (cksum_val != NULL)
12244 		*cksum_val = 0;
12245 	if (cksum_flags != NULL)
12246 		*cksum_flags = 0;
12247 
12248 	/*
12249 	 * Drop the fragmented as early as possible, if
12250 	 * we don't have resource(s) to re-assemble.
12251 	 */
12252 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12253 		freemsg(mp);
12254 		return (B_FALSE);
12255 	}
12256 
12257 	/* Check for fragmentation offset; return if there's none */
12258 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12259 	    (IPH_MF | IPH_OFFSET)) == 0)
12260 		return (B_TRUE);
12261 
12262 	/*
12263 	 * We utilize hardware computed checksum info only for UDP since
12264 	 * IP fragmentation is a normal occurrence for the protocol.  In
12265 	 * addition, checksum offload support for IP fragments carrying
12266 	 * UDP payload is commonly implemented across network adapters.
12267 	 */
12268 	ASSERT(recv_ill != NULL);
12269 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12270 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12271 		mblk_t *mp1 = mp->b_cont;
12272 		int32_t len;
12273 
12274 		/* Record checksum information from the packet */
12275 		sum_val = (uint32_t)DB_CKSUM16(mp);
12276 		sum_flags = DB_CKSUMFLAGS(mp);
12277 
12278 		/* IP payload offset from beginning of mblk */
12279 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12280 
12281 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12282 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12283 		    offset >= DB_CKSUMSTART(mp) &&
12284 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12285 			uint32_t adj;
12286 			/*
12287 			 * Partial checksum has been calculated by hardware
12288 			 * and attached to the packet; in addition, any
12289 			 * prepended extraneous data is even byte aligned.
12290 			 * If any such data exists, we adjust the checksum;
12291 			 * this would also handle any postpended data.
12292 			 */
12293 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12294 			    mp, mp1, len, adj);
12295 
12296 			/* One's complement subtract extraneous checksum */
12297 			if (adj >= sum_val)
12298 				sum_val = ~(adj - sum_val) & 0xFFFF;
12299 			else
12300 				sum_val -= adj;
12301 		}
12302 	} else {
12303 		sum_val = 0;
12304 		sum_flags = 0;
12305 	}
12306 
12307 	/* Clear hardware checksumming flag */
12308 	DB_CKSUMFLAGS(mp) = 0;
12309 
12310 	ident = ipha->ipha_ident;
12311 	offset = (frag_offset_flags << 3) & 0xFFFF;
12312 	src = ipha->ipha_src;
12313 	dst = ipha->ipha_dst;
12314 	hdr_length = IPH_HDR_LENGTH(ipha);
12315 	end = ntohs(ipha->ipha_length) - hdr_length;
12316 
12317 	/* If end == 0 then we have a packet with no data, so just free it */
12318 	if (end == 0) {
12319 		freemsg(mp);
12320 		return (B_FALSE);
12321 	}
12322 
12323 	/* Record the ECN field info. */
12324 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12325 	if (offset != 0) {
12326 		/*
12327 		 * If this isn't the first piece, strip the header, and
12328 		 * add the offset to the end value.
12329 		 */
12330 		mp->b_rptr += hdr_length;
12331 		end += offset;
12332 	}
12333 
12334 	msg_len = MBLKSIZE(mp);
12335 	tail_mp = mp;
12336 	while (tail_mp->b_cont != NULL) {
12337 		tail_mp = tail_mp->b_cont;
12338 		msg_len += MBLKSIZE(tail_mp);
12339 	}
12340 
12341 	/* If the reassembly list for this ILL will get too big, prune it */
12342 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12343 	    ipst->ips_ip_reass_queue_bytes) {
12344 		ill_frag_prune(ill,
12345 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12346 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12347 		pruned = B_TRUE;
12348 	}
12349 
12350 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12351 	mutex_enter(&ipfb->ipfb_lock);
12352 
12353 	ipfp = &ipfb->ipfb_ipf;
12354 	/* Try to find an existing fragment queue for this packet. */
12355 	for (;;) {
12356 		ipf = ipfp[0];
12357 		if (ipf != NULL) {
12358 			/*
12359 			 * It has to match on ident and src/dst address.
12360 			 */
12361 			if (ipf->ipf_ident == ident &&
12362 			    ipf->ipf_src == src &&
12363 			    ipf->ipf_dst == dst &&
12364 			    ipf->ipf_protocol == proto) {
12365 				/*
12366 				 * If we have received too many
12367 				 * duplicate fragments for this packet
12368 				 * free it.
12369 				 */
12370 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12371 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12372 					freemsg(mp);
12373 					mutex_exit(&ipfb->ipfb_lock);
12374 					return (B_FALSE);
12375 				}
12376 				/* Found it. */
12377 				break;
12378 			}
12379 			ipfp = &ipf->ipf_hash_next;
12380 			continue;
12381 		}
12382 
12383 		/*
12384 		 * If we pruned the list, do we want to store this new
12385 		 * fragment?. We apply an optimization here based on the
12386 		 * fact that most fragments will be received in order.
12387 		 * So if the offset of this incoming fragment is zero,
12388 		 * it is the first fragment of a new packet. We will
12389 		 * keep it.  Otherwise drop the fragment, as we have
12390 		 * probably pruned the packet already (since the
12391 		 * packet cannot be found).
12392 		 */
12393 		if (pruned && offset != 0) {
12394 			mutex_exit(&ipfb->ipfb_lock);
12395 			freemsg(mp);
12396 			return (B_FALSE);
12397 		}
12398 
12399 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12400 			/*
12401 			 * Too many fragmented packets in this hash
12402 			 * bucket. Free the oldest.
12403 			 */
12404 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12405 		}
12406 
12407 		/* New guy.  Allocate a frag message. */
12408 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12409 		if (mp1 == NULL) {
12410 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12411 			freemsg(mp);
12412 reass_done:
12413 			mutex_exit(&ipfb->ipfb_lock);
12414 			return (B_FALSE);
12415 		}
12416 
12417 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12418 		mp1->b_cont = mp;
12419 
12420 		/* Initialize the fragment header. */
12421 		ipf = (ipf_t *)mp1->b_rptr;
12422 		ipf->ipf_mp = mp1;
12423 		ipf->ipf_ptphn = ipfp;
12424 		ipfp[0] = ipf;
12425 		ipf->ipf_hash_next = NULL;
12426 		ipf->ipf_ident = ident;
12427 		ipf->ipf_protocol = proto;
12428 		ipf->ipf_src = src;
12429 		ipf->ipf_dst = dst;
12430 		ipf->ipf_nf_hdr_len = 0;
12431 		/* Record reassembly start time. */
12432 		ipf->ipf_timestamp = gethrestime_sec();
12433 		/* Record ipf generation and account for frag header */
12434 		ipf->ipf_gen = ill->ill_ipf_gen++;
12435 		ipf->ipf_count = MBLKSIZE(mp1);
12436 		ipf->ipf_last_frag_seen = B_FALSE;
12437 		ipf->ipf_ecn = ecn_info;
12438 		ipf->ipf_num_dups = 0;
12439 		ipfb->ipfb_frag_pkts++;
12440 		ipf->ipf_checksum = 0;
12441 		ipf->ipf_checksum_flags = 0;
12442 
12443 		/* Store checksum value in fragment header */
12444 		if (sum_flags != 0) {
12445 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12446 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12447 			ipf->ipf_checksum = sum_val;
12448 			ipf->ipf_checksum_flags = sum_flags;
12449 		}
12450 
12451 		/*
12452 		 * We handle reassembly two ways.  In the easy case,
12453 		 * where all the fragments show up in order, we do
12454 		 * minimal bookkeeping, and just clip new pieces on
12455 		 * the end.  If we ever see a hole, then we go off
12456 		 * to ip_reassemble which has to mark the pieces and
12457 		 * keep track of the number of holes, etc.  Obviously,
12458 		 * the point of having both mechanisms is so we can
12459 		 * handle the easy case as efficiently as possible.
12460 		 */
12461 		if (offset == 0) {
12462 			/* Easy case, in-order reassembly so far. */
12463 			ipf->ipf_count += msg_len;
12464 			ipf->ipf_tail_mp = tail_mp;
12465 			/*
12466 			 * Keep track of next expected offset in
12467 			 * ipf_end.
12468 			 */
12469 			ipf->ipf_end = end;
12470 			ipf->ipf_nf_hdr_len = hdr_length;
12471 		} else {
12472 			/* Hard case, hole at the beginning. */
12473 			ipf->ipf_tail_mp = NULL;
12474 			/*
12475 			 * ipf_end == 0 means that we have given up
12476 			 * on easy reassembly.
12477 			 */
12478 			ipf->ipf_end = 0;
12479 
12480 			/* Forget checksum offload from now on */
12481 			ipf->ipf_checksum_flags = 0;
12482 
12483 			/*
12484 			 * ipf_hole_cnt is set by ip_reassemble.
12485 			 * ipf_count is updated by ip_reassemble.
12486 			 * No need to check for return value here
12487 			 * as we don't expect reassembly to complete
12488 			 * or fail for the first fragment itself.
12489 			 */
12490 			(void) ip_reassemble(mp, ipf,
12491 			    (frag_offset_flags & IPH_OFFSET) << 3,
12492 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12493 		}
12494 		/* Update per ipfb and ill byte counts */
12495 		ipfb->ipfb_count += ipf->ipf_count;
12496 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12497 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12498 		/* If the frag timer wasn't already going, start it. */
12499 		mutex_enter(&ill->ill_lock);
12500 		ill_frag_timer_start(ill);
12501 		mutex_exit(&ill->ill_lock);
12502 		goto reass_done;
12503 	}
12504 
12505 	/*
12506 	 * If the packet's flag has changed (it could be coming up
12507 	 * from an interface different than the previous, therefore
12508 	 * possibly different checksum capability), then forget about
12509 	 * any stored checksum states.  Otherwise add the value to
12510 	 * the existing one stored in the fragment header.
12511 	 */
12512 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12513 		sum_val += ipf->ipf_checksum;
12514 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12515 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12516 		ipf->ipf_checksum = sum_val;
12517 	} else if (ipf->ipf_checksum_flags != 0) {
12518 		/* Forget checksum offload from now on */
12519 		ipf->ipf_checksum_flags = 0;
12520 	}
12521 
12522 	/*
12523 	 * We have a new piece of a datagram which is already being
12524 	 * reassembled.  Update the ECN info if all IP fragments
12525 	 * are ECN capable.  If there is one which is not, clear
12526 	 * all the info.  If there is at least one which has CE
12527 	 * code point, IP needs to report that up to transport.
12528 	 */
12529 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12530 		if (ecn_info == IPH_ECN_CE)
12531 			ipf->ipf_ecn = IPH_ECN_CE;
12532 	} else {
12533 		ipf->ipf_ecn = IPH_ECN_NECT;
12534 	}
12535 	if (offset && ipf->ipf_end == offset) {
12536 		/* The new fragment fits at the end */
12537 		ipf->ipf_tail_mp->b_cont = mp;
12538 		/* Update the byte count */
12539 		ipf->ipf_count += msg_len;
12540 		/* Update per ipfb and ill byte counts */
12541 		ipfb->ipfb_count += msg_len;
12542 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12543 		atomic_add_32(&ill->ill_frag_count, msg_len);
12544 		if (frag_offset_flags & IPH_MF) {
12545 			/* More to come. */
12546 			ipf->ipf_end = end;
12547 			ipf->ipf_tail_mp = tail_mp;
12548 			goto reass_done;
12549 		}
12550 	} else {
12551 		/* Go do the hard cases. */
12552 		int ret;
12553 
12554 		if (offset == 0)
12555 			ipf->ipf_nf_hdr_len = hdr_length;
12556 
12557 		/* Save current byte count */
12558 		count = ipf->ipf_count;
12559 		ret = ip_reassemble(mp, ipf,
12560 		    (frag_offset_flags & IPH_OFFSET) << 3,
12561 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12562 		/* Count of bytes added and subtracted (freeb()ed) */
12563 		count = ipf->ipf_count - count;
12564 		if (count) {
12565 			/* Update per ipfb and ill byte counts */
12566 			ipfb->ipfb_count += count;
12567 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12568 			atomic_add_32(&ill->ill_frag_count, count);
12569 		}
12570 		if (ret == IP_REASS_PARTIAL) {
12571 			goto reass_done;
12572 		} else if (ret == IP_REASS_FAILED) {
12573 			/* Reassembly failed. Free up all resources */
12574 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12575 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12576 				IP_REASS_SET_START(t_mp, 0);
12577 				IP_REASS_SET_END(t_mp, 0);
12578 			}
12579 			freemsg(mp);
12580 			goto reass_done;
12581 		}
12582 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12583 	}
12584 	/*
12585 	 * We have completed reassembly.  Unhook the frag header from
12586 	 * the reassembly list.
12587 	 *
12588 	 * Before we free the frag header, record the ECN info
12589 	 * to report back to the transport.
12590 	 */
12591 	ecn_info = ipf->ipf_ecn;
12592 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12593 	ipfp = ipf->ipf_ptphn;
12594 
12595 	/* We need to supply these to caller */
12596 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12597 		sum_val = ipf->ipf_checksum;
12598 	else
12599 		sum_val = 0;
12600 
12601 	mp1 = ipf->ipf_mp;
12602 	count = ipf->ipf_count;
12603 	ipf = ipf->ipf_hash_next;
12604 	if (ipf != NULL)
12605 		ipf->ipf_ptphn = ipfp;
12606 	ipfp[0] = ipf;
12607 	atomic_add_32(&ill->ill_frag_count, -count);
12608 	ASSERT(ipfb->ipfb_count >= count);
12609 	ipfb->ipfb_count -= count;
12610 	ipfb->ipfb_frag_pkts--;
12611 	mutex_exit(&ipfb->ipfb_lock);
12612 	/* Ditch the frag header. */
12613 	mp = mp1->b_cont;
12614 
12615 	freeb(mp1);
12616 
12617 	/* Restore original IP length in header. */
12618 	packet_size = (uint32_t)msgdsize(mp);
12619 	if (packet_size > IP_MAXPACKET) {
12620 		freemsg(mp);
12621 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12622 		return (B_FALSE);
12623 	}
12624 
12625 	if (DB_REF(mp) > 1) {
12626 		mblk_t *mp2 = copymsg(mp);
12627 
12628 		freemsg(mp);
12629 		if (mp2 == NULL) {
12630 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12631 			return (B_FALSE);
12632 		}
12633 		mp = mp2;
12634 	}
12635 	ipha = (ipha_t *)mp->b_rptr;
12636 
12637 	ipha->ipha_length = htons((uint16_t)packet_size);
12638 	/* We're now complete, zip the frag state */
12639 	ipha->ipha_fragment_offset_and_flags = 0;
12640 	/* Record the ECN info. */
12641 	ipha->ipha_type_of_service &= 0xFC;
12642 	ipha->ipha_type_of_service |= ecn_info;
12643 	*mpp = mp;
12644 
12645 	/* Reassembly is successful; return checksum information if needed */
12646 	if (cksum_val != NULL)
12647 		*cksum_val = sum_val;
12648 	if (cksum_flags != NULL)
12649 		*cksum_flags = sum_flags;
12650 
12651 	return (B_TRUE);
12652 }
12653 
12654 /*
12655  * Perform ip header check sum update local options.
12656  * return B_TRUE if all is well, else return B_FALSE and release
12657  * the mp. caller is responsible for decrementing ire ref cnt.
12658  */
12659 static boolean_t
12660 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12661     ip_stack_t *ipst)
12662 {
12663 	mblk_t		*first_mp;
12664 	boolean_t	mctl_present;
12665 	uint16_t	sum;
12666 
12667 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12668 	/*
12669 	 * Don't do the checksum if it has gone through AH/ESP
12670 	 * processing.
12671 	 */
12672 	if (!mctl_present) {
12673 		sum = ip_csum_hdr(ipha);
12674 		if (sum != 0) {
12675 			if (ill != NULL) {
12676 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12677 			} else {
12678 				BUMP_MIB(&ipst->ips_ip_mib,
12679 				    ipIfStatsInCksumErrs);
12680 			}
12681 			freemsg(first_mp);
12682 			return (B_FALSE);
12683 		}
12684 	}
12685 
12686 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12687 		if (mctl_present)
12688 			freeb(first_mp);
12689 		return (B_FALSE);
12690 	}
12691 
12692 	return (B_TRUE);
12693 }
12694 
12695 /*
12696  * All udp packet are delivered to the local host via this routine.
12697  */
12698 void
12699 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12700     ill_t *recv_ill)
12701 {
12702 	uint32_t	sum;
12703 	uint32_t	u1;
12704 	boolean_t	mctl_present;
12705 	conn_t		*connp;
12706 	mblk_t		*first_mp;
12707 	uint16_t	*up;
12708 	ill_t		*ill = (ill_t *)q->q_ptr;
12709 	uint16_t	reass_hck_flags = 0;
12710 	ip_stack_t	*ipst;
12711 
12712 	ASSERT(recv_ill != NULL);
12713 	ipst = recv_ill->ill_ipst;
12714 
12715 #define	rptr    ((uchar_t *)ipha)
12716 
12717 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12718 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12719 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12720 	ASSERT(ill != NULL);
12721 
12722 	/*
12723 	 * FAST PATH for udp packets
12724 	 */
12725 
12726 	/* u1 is # words of IP options */
12727 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12728 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12729 
12730 	/* IP options present */
12731 	if (u1 != 0)
12732 		goto ipoptions;
12733 
12734 	/* Check the IP header checksum.  */
12735 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12736 		/* Clear the IP header h/w cksum flag */
12737 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12738 	} else if (!mctl_present) {
12739 		/*
12740 		 * Don't verify header checksum if this packet is coming
12741 		 * back from AH/ESP as we already did it.
12742 		 */
12743 #define	uph	((uint16_t *)ipha)
12744 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12745 		    uph[6] + uph[7] + uph[8] + uph[9];
12746 #undef	uph
12747 		/* finish doing IP checksum */
12748 		sum = (sum & 0xFFFF) + (sum >> 16);
12749 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12750 		if (sum != 0 && sum != 0xFFFF) {
12751 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12752 			freemsg(first_mp);
12753 			return;
12754 		}
12755 	}
12756 
12757 	/*
12758 	 * Count for SNMP of inbound packets for ire.
12759 	 * if mctl is present this might be a secure packet and
12760 	 * has already been counted for in ip_proto_input().
12761 	 */
12762 	if (!mctl_present) {
12763 		UPDATE_IB_PKT_COUNT(ire);
12764 		ire->ire_last_used_time = lbolt;
12765 	}
12766 
12767 	/* packet part of fragmented IP packet? */
12768 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12769 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12770 		goto fragmented;
12771 	}
12772 
12773 	/* u1 = IP header length (20 bytes) */
12774 	u1 = IP_SIMPLE_HDR_LENGTH;
12775 
12776 	/* packet does not contain complete IP & UDP headers */
12777 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12778 		goto udppullup;
12779 
12780 	/* up points to UDP header */
12781 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12782 #define	iphs    ((uint16_t *)ipha)
12783 
12784 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12785 	if (up[3] != 0) {
12786 		mblk_t *mp1 = mp->b_cont;
12787 		boolean_t cksum_err;
12788 		uint16_t hck_flags = 0;
12789 
12790 		/* Pseudo-header checksum */
12791 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12792 		    iphs[9] + up[2];
12793 
12794 		/*
12795 		 * Revert to software checksum calculation if the interface
12796 		 * isn't capable of checksum offload or if IPsec is present.
12797 		 */
12798 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12799 			hck_flags = DB_CKSUMFLAGS(mp);
12800 
12801 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12802 			IP_STAT(ipst, ip_in_sw_cksum);
12803 
12804 		IP_CKSUM_RECV(hck_flags, u1,
12805 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12806 		    (int32_t)((uchar_t *)up - rptr),
12807 		    mp, mp1, cksum_err);
12808 
12809 		if (cksum_err) {
12810 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12811 			if (hck_flags & HCK_FULLCKSUM)
12812 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12813 			else if (hck_flags & HCK_PARTIALCKSUM)
12814 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12815 			else
12816 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12817 
12818 			freemsg(first_mp);
12819 			return;
12820 		}
12821 	}
12822 
12823 	/* Non-fragmented broadcast or multicast packet? */
12824 	if (ire->ire_type == IRE_BROADCAST)
12825 		goto udpslowpath;
12826 
12827 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12828 	    ire->ire_zoneid, ipst)) != NULL) {
12829 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12830 		IP_STAT(ipst, ip_udp_fast_path);
12831 
12832 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12833 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12834 			freemsg(mp);
12835 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12836 		} else {
12837 			if (!mctl_present) {
12838 				BUMP_MIB(ill->ill_ip_mib,
12839 				    ipIfStatsHCInDelivers);
12840 			}
12841 			/*
12842 			 * mp and first_mp can change.
12843 			 */
12844 			if (ip_udp_check(q, connp, recv_ill,
12845 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12846 				/* Send it upstream */
12847 				(connp->conn_recv)(connp, mp, NULL);
12848 			}
12849 		}
12850 		/*
12851 		 * freeb() cannot deal with null mblk being passed
12852 		 * in and first_mp can be set to null in the call
12853 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12854 		 */
12855 		if (mctl_present && first_mp != NULL) {
12856 			freeb(first_mp);
12857 		}
12858 		CONN_DEC_REF(connp);
12859 		return;
12860 	}
12861 
12862 	/*
12863 	 * if we got here we know the packet is not fragmented and
12864 	 * has no options. The classifier could not find a conn_t and
12865 	 * most likely its an icmp packet so send it through slow path.
12866 	 */
12867 
12868 	goto udpslowpath;
12869 
12870 ipoptions:
12871 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12872 		goto slow_done;
12873 	}
12874 
12875 	UPDATE_IB_PKT_COUNT(ire);
12876 	ire->ire_last_used_time = lbolt;
12877 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12878 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12879 fragmented:
12880 		/*
12881 		 * "sum" and "reass_hck_flags" are non-zero if the
12882 		 * reassembled packet has a valid hardware computed
12883 		 * checksum information associated with it.
12884 		 */
12885 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12886 		    &reass_hck_flags)) {
12887 			goto slow_done;
12888 		}
12889 
12890 		/*
12891 		 * Make sure that first_mp points back to mp as
12892 		 * the mp we came in with could have changed in
12893 		 * ip_rput_fragment().
12894 		 */
12895 		ASSERT(!mctl_present);
12896 		ipha = (ipha_t *)mp->b_rptr;
12897 		first_mp = mp;
12898 	}
12899 
12900 	/* Now we have a complete datagram, destined for this machine. */
12901 	u1 = IPH_HDR_LENGTH(ipha);
12902 	/* Pull up the UDP header, if necessary. */
12903 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12904 udppullup:
12905 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12906 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12907 			freemsg(first_mp);
12908 			goto slow_done;
12909 		}
12910 		ipha = (ipha_t *)mp->b_rptr;
12911 	}
12912 
12913 	/*
12914 	 * Validate the checksum for the reassembled packet; for the
12915 	 * pullup case we calculate the payload checksum in software.
12916 	 */
12917 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12918 	if (up[3] != 0) {
12919 		boolean_t cksum_err;
12920 
12921 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12922 			IP_STAT(ipst, ip_in_sw_cksum);
12923 
12924 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12925 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12926 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12927 		    iphs[9] + up[2], sum, cksum_err);
12928 
12929 		if (cksum_err) {
12930 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12931 
12932 			if (reass_hck_flags & HCK_FULLCKSUM)
12933 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12934 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12935 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12936 			else
12937 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12938 
12939 			freemsg(first_mp);
12940 			goto slow_done;
12941 		}
12942 	}
12943 udpslowpath:
12944 
12945 	/* Clear hardware checksum flag to be safe */
12946 	DB_CKSUMFLAGS(mp) = 0;
12947 
12948 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12949 	    (ire->ire_type == IRE_BROADCAST),
12950 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12951 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12952 
12953 slow_done:
12954 	IP_STAT(ipst, ip_udp_slow_path);
12955 	return;
12956 
12957 #undef  iphs
12958 #undef  rptr
12959 }
12960 
12961 /* ARGSUSED */
12962 static mblk_t *
12963 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12964     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12965     ill_rx_ring_t *ill_ring)
12966 {
12967 	conn_t		*connp;
12968 	uint32_t	sum;
12969 	uint32_t	u1;
12970 	uint16_t	*up;
12971 	int		offset;
12972 	ssize_t		len;
12973 	mblk_t		*mp1;
12974 	boolean_t	syn_present = B_FALSE;
12975 	tcph_t		*tcph;
12976 	uint_t		tcph_flags;
12977 	uint_t		ip_hdr_len;
12978 	ill_t		*ill = (ill_t *)q->q_ptr;
12979 	zoneid_t	zoneid = ire->ire_zoneid;
12980 	boolean_t	cksum_err;
12981 	uint16_t	hck_flags = 0;
12982 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12983 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12984 
12985 #define	rptr	((uchar_t *)ipha)
12986 
12987 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12988 	ASSERT(ill != NULL);
12989 
12990 	/*
12991 	 * FAST PATH for tcp packets
12992 	 */
12993 
12994 	/* u1 is # words of IP options */
12995 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12996 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12997 
12998 	/* IP options present */
12999 	if (u1) {
13000 		goto ipoptions;
13001 	} else if (!mctl_present) {
13002 		/* Check the IP header checksum.  */
13003 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
13004 			/* Clear the IP header h/w cksum flag */
13005 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13006 		} else if (!mctl_present) {
13007 			/*
13008 			 * Don't verify header checksum if this packet
13009 			 * is coming back from AH/ESP as we already did it.
13010 			 */
13011 #define	uph	((uint16_t *)ipha)
13012 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13013 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13014 #undef	uph
13015 			/* finish doing IP checksum */
13016 			sum = (sum & 0xFFFF) + (sum >> 16);
13017 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13018 			if (sum != 0 && sum != 0xFFFF) {
13019 				BUMP_MIB(ill->ill_ip_mib,
13020 				    ipIfStatsInCksumErrs);
13021 				goto error;
13022 			}
13023 		}
13024 	}
13025 
13026 	if (!mctl_present) {
13027 		UPDATE_IB_PKT_COUNT(ire);
13028 		ire->ire_last_used_time = lbolt;
13029 	}
13030 
13031 	/* packet part of fragmented IP packet? */
13032 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13033 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13034 		goto fragmented;
13035 	}
13036 
13037 	/* u1 = IP header length (20 bytes) */
13038 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13039 
13040 	/* does packet contain IP+TCP headers? */
13041 	len = mp->b_wptr - rptr;
13042 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13043 		IP_STAT(ipst, ip_tcppullup);
13044 		goto tcppullup;
13045 	}
13046 
13047 	/* TCP options present? */
13048 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13049 
13050 	/*
13051 	 * If options need to be pulled up, then goto tcpoptions.
13052 	 * otherwise we are still in the fast path
13053 	 */
13054 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13055 		IP_STAT(ipst, ip_tcpoptions);
13056 		goto tcpoptions;
13057 	}
13058 
13059 	/* multiple mblks of tcp data? */
13060 	if ((mp1 = mp->b_cont) != NULL) {
13061 		IP_STAT(ipst, ip_multipkttcp);
13062 		len += msgdsize(mp1);
13063 	}
13064 
13065 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13066 
13067 	/* part of pseudo checksum */
13068 
13069 	/* TCP datagram length */
13070 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13071 
13072 #define	iphs    ((uint16_t *)ipha)
13073 
13074 #ifdef	_BIG_ENDIAN
13075 	u1 += IPPROTO_TCP;
13076 #else
13077 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13078 #endif
13079 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13080 
13081 	/*
13082 	 * Revert to software checksum calculation if the interface
13083 	 * isn't capable of checksum offload or if IPsec is present.
13084 	 */
13085 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
13086 		hck_flags = DB_CKSUMFLAGS(mp);
13087 
13088 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13089 		IP_STAT(ipst, ip_in_sw_cksum);
13090 
13091 	IP_CKSUM_RECV(hck_flags, u1,
13092 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13093 	    (int32_t)((uchar_t *)up - rptr),
13094 	    mp, mp1, cksum_err);
13095 
13096 	if (cksum_err) {
13097 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13098 
13099 		if (hck_flags & HCK_FULLCKSUM)
13100 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13101 		else if (hck_flags & HCK_PARTIALCKSUM)
13102 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13103 		else
13104 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13105 
13106 		goto error;
13107 	}
13108 
13109 try_again:
13110 
13111 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13112 	    zoneid, ipst)) == NULL) {
13113 		/* Send the TH_RST */
13114 		goto no_conn;
13115 	}
13116 
13117 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13118 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13119 
13120 	/*
13121 	 * TCP FAST PATH for AF_INET socket.
13122 	 *
13123 	 * TCP fast path to avoid extra work. An AF_INET socket type
13124 	 * does not have facility to receive extra information via
13125 	 * ip_process or ip_add_info. Also, when the connection was
13126 	 * established, we made a check if this connection is impacted
13127 	 * by any global IPsec policy or per connection policy (a
13128 	 * policy that comes in effect later will not apply to this
13129 	 * connection). Since all this can be determined at the
13130 	 * connection establishment time, a quick check of flags
13131 	 * can avoid extra work.
13132 	 */
13133 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13134 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13135 		ASSERT(first_mp == mp);
13136 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13137 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13138 			SET_SQUEUE(mp, tcp_rput_data, connp);
13139 			return (mp);
13140 		}
13141 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13142 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13143 		SET_SQUEUE(mp, tcp_input, connp);
13144 		return (mp);
13145 	}
13146 
13147 	if (tcph_flags == TH_SYN) {
13148 		if (IPCL_IS_TCP(connp)) {
13149 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13150 			DB_CKSUMSTART(mp) =
13151 			    (intptr_t)ip_squeue_get(ill_ring);
13152 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13153 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13154 				BUMP_MIB(ill->ill_ip_mib,
13155 				    ipIfStatsHCInDelivers);
13156 				SET_SQUEUE(mp, connp->conn_recv, connp);
13157 				return (mp);
13158 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13159 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13160 				BUMP_MIB(ill->ill_ip_mib,
13161 				    ipIfStatsHCInDelivers);
13162 				ip_squeue_enter_unbound++;
13163 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13164 				    connp);
13165 				return (mp);
13166 			}
13167 			syn_present = B_TRUE;
13168 		}
13169 	}
13170 
13171 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13172 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13173 
13174 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13175 		/* No need to send this packet to TCP */
13176 		if ((flags & TH_RST) || (flags & TH_URG)) {
13177 			CONN_DEC_REF(connp);
13178 			freemsg(first_mp);
13179 			return (NULL);
13180 		}
13181 		if (flags & TH_ACK) {
13182 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13183 			    ipst->ips_netstack->netstack_tcp, connp);
13184 			CONN_DEC_REF(connp);
13185 			return (NULL);
13186 		}
13187 
13188 		CONN_DEC_REF(connp);
13189 		freemsg(first_mp);
13190 		return (NULL);
13191 	}
13192 
13193 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13194 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13195 		    ipha, NULL, mctl_present);
13196 		if (first_mp == NULL) {
13197 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13198 			CONN_DEC_REF(connp);
13199 			return (NULL);
13200 		}
13201 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13202 			ASSERT(syn_present);
13203 			if (mctl_present) {
13204 				ASSERT(first_mp != mp);
13205 				first_mp->b_datap->db_struioflag |=
13206 				    STRUIO_POLICY;
13207 			} else {
13208 				ASSERT(first_mp == mp);
13209 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13210 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13211 			}
13212 		} else {
13213 			/*
13214 			 * Discard first_mp early since we're dealing with a
13215 			 * fully-connected conn_t and tcp doesn't do policy in
13216 			 * this case.
13217 			 */
13218 			if (mctl_present) {
13219 				freeb(first_mp);
13220 				mctl_present = B_FALSE;
13221 			}
13222 			first_mp = mp;
13223 		}
13224 	}
13225 
13226 	/* Initiate IPPF processing for fastpath */
13227 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13228 		uint32_t	ill_index;
13229 
13230 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13231 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13232 		if (mp == NULL) {
13233 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13234 			    "deferred/dropped during IPPF processing\n"));
13235 			CONN_DEC_REF(connp);
13236 			if (mctl_present)
13237 				freeb(first_mp);
13238 			return (NULL);
13239 		} else if (mctl_present) {
13240 			/*
13241 			 * ip_process might return a new mp.
13242 			 */
13243 			ASSERT(first_mp != mp);
13244 			first_mp->b_cont = mp;
13245 		} else {
13246 			first_mp = mp;
13247 		}
13248 
13249 	}
13250 
13251 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13252 		/*
13253 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13254 		 * make sure IPF_RECVIF is passed to ip_add_info.
13255 		 */
13256 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13257 		    IPCL_ZONEID(connp), ipst);
13258 		if (mp == NULL) {
13259 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13260 			CONN_DEC_REF(connp);
13261 			if (mctl_present)
13262 				freeb(first_mp);
13263 			return (NULL);
13264 		} else if (mctl_present) {
13265 			/*
13266 			 * ip_add_info might return a new mp.
13267 			 */
13268 			ASSERT(first_mp != mp);
13269 			first_mp->b_cont = mp;
13270 		} else {
13271 			first_mp = mp;
13272 		}
13273 	}
13274 
13275 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13276 	if (IPCL_IS_TCP(connp)) {
13277 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13278 		return (first_mp);
13279 	} else {
13280 		/* SOCK_RAW, IPPROTO_TCP case */
13281 		(connp->conn_recv)(connp, first_mp, NULL);
13282 		CONN_DEC_REF(connp);
13283 		return (NULL);
13284 	}
13285 
13286 no_conn:
13287 	/* Initiate IPPf processing, if needed. */
13288 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13289 		uint32_t ill_index;
13290 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13291 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13292 		if (first_mp == NULL) {
13293 			return (NULL);
13294 		}
13295 	}
13296 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13297 
13298 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13299 	    ipst->ips_netstack->netstack_tcp, NULL);
13300 	return (NULL);
13301 ipoptions:
13302 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13303 		goto slow_done;
13304 	}
13305 
13306 	UPDATE_IB_PKT_COUNT(ire);
13307 	ire->ire_last_used_time = lbolt;
13308 
13309 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13310 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13311 fragmented:
13312 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13313 			if (mctl_present)
13314 				freeb(first_mp);
13315 			goto slow_done;
13316 		}
13317 		/*
13318 		 * Make sure that first_mp points back to mp as
13319 		 * the mp we came in with could have changed in
13320 		 * ip_rput_fragment().
13321 		 */
13322 		ASSERT(!mctl_present);
13323 		ipha = (ipha_t *)mp->b_rptr;
13324 		first_mp = mp;
13325 	}
13326 
13327 	/* Now we have a complete datagram, destined for this machine. */
13328 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13329 
13330 	len = mp->b_wptr - mp->b_rptr;
13331 	/* Pull up a minimal TCP header, if necessary. */
13332 	if (len < (u1 + 20)) {
13333 tcppullup:
13334 		if (!pullupmsg(mp, u1 + 20)) {
13335 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13336 			goto error;
13337 		}
13338 		ipha = (ipha_t *)mp->b_rptr;
13339 		len = mp->b_wptr - mp->b_rptr;
13340 	}
13341 
13342 	/*
13343 	 * Extract the offset field from the TCP header.  As usual, we
13344 	 * try to help the compiler more than the reader.
13345 	 */
13346 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13347 	if (offset != 5) {
13348 tcpoptions:
13349 		if (offset < 5) {
13350 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13351 			goto error;
13352 		}
13353 		/*
13354 		 * There must be TCP options.
13355 		 * Make sure we can grab them.
13356 		 */
13357 		offset <<= 2;
13358 		offset += u1;
13359 		if (len < offset) {
13360 			if (!pullupmsg(mp, offset)) {
13361 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13362 				goto error;
13363 			}
13364 			ipha = (ipha_t *)mp->b_rptr;
13365 			len = mp->b_wptr - rptr;
13366 		}
13367 	}
13368 
13369 	/* Get the total packet length in len, including headers. */
13370 	if (mp->b_cont)
13371 		len = msgdsize(mp);
13372 
13373 	/*
13374 	 * Check the TCP checksum by pulling together the pseudo-
13375 	 * header checksum, and passing it to ip_csum to be added in
13376 	 * with the TCP datagram.
13377 	 *
13378 	 * Since we are not using the hwcksum if available we must
13379 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13380 	 * If either of these fails along the way the mblk is freed.
13381 	 * If this logic ever changes and mblk is reused to say send
13382 	 * ICMP's back, then this flag may need to be cleared in
13383 	 * other places as well.
13384 	 */
13385 	DB_CKSUMFLAGS(mp) = 0;
13386 
13387 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13388 
13389 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13390 #ifdef	_BIG_ENDIAN
13391 	u1 += IPPROTO_TCP;
13392 #else
13393 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13394 #endif
13395 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13396 	/*
13397 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13398 	 */
13399 	IP_STAT(ipst, ip_in_sw_cksum);
13400 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13401 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13402 		goto error;
13403 	}
13404 
13405 	IP_STAT(ipst, ip_tcp_slow_path);
13406 	goto try_again;
13407 #undef  iphs
13408 #undef  rptr
13409 
13410 error:
13411 	freemsg(first_mp);
13412 slow_done:
13413 	return (NULL);
13414 }
13415 
13416 /* ARGSUSED */
13417 static void
13418 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13419     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13420 {
13421 	conn_t		*connp;
13422 	uint32_t	sum;
13423 	uint32_t	u1;
13424 	ssize_t		len;
13425 	sctp_hdr_t	*sctph;
13426 	zoneid_t	zoneid = ire->ire_zoneid;
13427 	uint32_t	pktsum;
13428 	uint32_t	calcsum;
13429 	uint32_t	ports;
13430 	in6_addr_t	map_src, map_dst;
13431 	ill_t		*ill = (ill_t *)q->q_ptr;
13432 	ip_stack_t	*ipst;
13433 	sctp_stack_t	*sctps;
13434 	boolean_t	sctp_csum_err = B_FALSE;
13435 
13436 	ASSERT(recv_ill != NULL);
13437 	ipst = recv_ill->ill_ipst;
13438 	sctps = ipst->ips_netstack->netstack_sctp;
13439 
13440 #define	rptr	((uchar_t *)ipha)
13441 
13442 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13443 	ASSERT(ill != NULL);
13444 
13445 	/* u1 is # words of IP options */
13446 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13447 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13448 
13449 	/* IP options present */
13450 	if (u1 > 0) {
13451 		goto ipoptions;
13452 	} else {
13453 		/* Check the IP header checksum.  */
13454 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13455 		    !mctl_present) {
13456 #define	uph	((uint16_t *)ipha)
13457 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13458 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13459 #undef	uph
13460 			/* finish doing IP checksum */
13461 			sum = (sum & 0xFFFF) + (sum >> 16);
13462 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13463 			/*
13464 			 * Don't verify header checksum if this packet
13465 			 * is coming back from AH/ESP as we already did it.
13466 			 */
13467 			if (sum != 0 && sum != 0xFFFF) {
13468 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13469 				goto error;
13470 			}
13471 		}
13472 		/*
13473 		 * Since there is no SCTP h/w cksum support yet, just
13474 		 * clear the flag.
13475 		 */
13476 		DB_CKSUMFLAGS(mp) = 0;
13477 	}
13478 
13479 	/*
13480 	 * Don't verify header checksum if this packet is coming
13481 	 * back from AH/ESP as we already did it.
13482 	 */
13483 	if (!mctl_present) {
13484 		UPDATE_IB_PKT_COUNT(ire);
13485 		ire->ire_last_used_time = lbolt;
13486 	}
13487 
13488 	/* packet part of fragmented IP packet? */
13489 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13490 	if (u1 & (IPH_MF | IPH_OFFSET))
13491 		goto fragmented;
13492 
13493 	/* u1 = IP header length (20 bytes) */
13494 	u1 = IP_SIMPLE_HDR_LENGTH;
13495 
13496 find_sctp_client:
13497 	/* Pullup if we don't have the sctp common header. */
13498 	len = MBLKL(mp);
13499 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13500 		if (mp->b_cont == NULL ||
13501 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13502 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13503 			goto error;
13504 		}
13505 		ipha = (ipha_t *)mp->b_rptr;
13506 		len = MBLKL(mp);
13507 	}
13508 
13509 	sctph = (sctp_hdr_t *)(rptr + u1);
13510 #ifdef	DEBUG
13511 	if (!skip_sctp_cksum) {
13512 #endif
13513 		pktsum = sctph->sh_chksum;
13514 		sctph->sh_chksum = 0;
13515 		calcsum = sctp_cksum(mp, u1);
13516 		sctph->sh_chksum = pktsum;
13517 		if (calcsum != pktsum)
13518 			sctp_csum_err = B_TRUE;
13519 #ifdef	DEBUG	/* skip_sctp_cksum */
13520 	}
13521 #endif
13522 	/* get the ports */
13523 	ports = *(uint32_t *)&sctph->sh_sport;
13524 
13525 	IRE_REFRELE(ire);
13526 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13527 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13528 	if (sctp_csum_err) {
13529 		/*
13530 		 * No potential sctp checksum errors go to the Sun
13531 		 * sctp stack however they might be Adler-32 summed
13532 		 * packets a userland stack bound to a raw IP socket
13533 		 * could reasonably use. Note though that Adler-32 is
13534 		 * a long deprecated algorithm and customer sctp
13535 		 * networks should eventually migrate to CRC-32 at
13536 		 * which time this facility should be removed.
13537 		 */
13538 		flags |= IP_FF_SCTP_CSUM_ERR;
13539 		goto no_conn;
13540 	}
13541 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13542 	    sctps)) == NULL) {
13543 		/* Check for raw socket or OOTB handling */
13544 		goto no_conn;
13545 	}
13546 
13547 	/* Found a client; up it goes */
13548 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13549 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13550 	return;
13551 
13552 no_conn:
13553 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13554 	    ports, mctl_present, flags, B_TRUE, zoneid);
13555 	return;
13556 
13557 ipoptions:
13558 	DB_CKSUMFLAGS(mp) = 0;
13559 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13560 		goto slow_done;
13561 
13562 	UPDATE_IB_PKT_COUNT(ire);
13563 	ire->ire_last_used_time = lbolt;
13564 
13565 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13566 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13567 fragmented:
13568 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13569 			goto slow_done;
13570 		/*
13571 		 * Make sure that first_mp points back to mp as
13572 		 * the mp we came in with could have changed in
13573 		 * ip_rput_fragment().
13574 		 */
13575 		ASSERT(!mctl_present);
13576 		ipha = (ipha_t *)mp->b_rptr;
13577 		first_mp = mp;
13578 	}
13579 
13580 	/* Now we have a complete datagram, destined for this machine. */
13581 	u1 = IPH_HDR_LENGTH(ipha);
13582 	goto find_sctp_client;
13583 #undef  iphs
13584 #undef  rptr
13585 
13586 error:
13587 	freemsg(first_mp);
13588 slow_done:
13589 	IRE_REFRELE(ire);
13590 }
13591 
13592 #define	VER_BITS	0xF0
13593 #define	VERSION_6	0x60
13594 
13595 static boolean_t
13596 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13597     ipaddr_t *dstp, ip_stack_t *ipst)
13598 {
13599 	uint_t	opt_len;
13600 	ipha_t *ipha;
13601 	ssize_t len;
13602 	uint_t	pkt_len;
13603 
13604 	ASSERT(ill != NULL);
13605 	IP_STAT(ipst, ip_ipoptions);
13606 	ipha = *iphapp;
13607 
13608 #define	rptr    ((uchar_t *)ipha)
13609 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13610 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13611 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13612 		freemsg(mp);
13613 		return (B_FALSE);
13614 	}
13615 
13616 	/* multiple mblk or too short */
13617 	pkt_len = ntohs(ipha->ipha_length);
13618 
13619 	/* Get the number of words of IP options in the IP header. */
13620 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13621 	if (opt_len) {
13622 		/* IP Options present!  Validate and process. */
13623 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13624 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13625 			goto done;
13626 		}
13627 		/*
13628 		 * Recompute complete header length and make sure we
13629 		 * have access to all of it.
13630 		 */
13631 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13632 		if (len > (mp->b_wptr - rptr)) {
13633 			if (len > pkt_len) {
13634 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13635 				goto done;
13636 			}
13637 			if (!pullupmsg(mp, len)) {
13638 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13639 				goto done;
13640 			}
13641 			ipha = (ipha_t *)mp->b_rptr;
13642 		}
13643 		/*
13644 		 * Go off to ip_rput_options which returns the next hop
13645 		 * destination address, which may have been affected
13646 		 * by source routing.
13647 		 */
13648 		IP_STAT(ipst, ip_opt);
13649 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13650 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13651 			return (B_FALSE);
13652 		}
13653 	}
13654 	*iphapp = ipha;
13655 	return (B_TRUE);
13656 done:
13657 	/* clear b_prev - used by ip_mroute_decap */
13658 	mp->b_prev = NULL;
13659 	freemsg(mp);
13660 	return (B_FALSE);
13661 #undef  rptr
13662 }
13663 
13664 /*
13665  * Deal with the fact that there is no ire for the destination.
13666  */
13667 static ire_t *
13668 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13669 {
13670 	ipha_t	*ipha;
13671 	ill_t	*ill;
13672 	ire_t	*ire;
13673 	ip_stack_t *ipst;
13674 	enum	ire_forward_action ret_action;
13675 
13676 	ipha = (ipha_t *)mp->b_rptr;
13677 	ill = (ill_t *)q->q_ptr;
13678 
13679 	ASSERT(ill != NULL);
13680 	ipst = ill->ill_ipst;
13681 
13682 	/*
13683 	 * No IRE for this destination, so it can't be for us.
13684 	 * Unless we are forwarding, drop the packet.
13685 	 * We have to let source routed packets through
13686 	 * since we don't yet know if they are 'ping -l'
13687 	 * packets i.e. if they will go out over the
13688 	 * same interface as they came in on.
13689 	 */
13690 	if (ll_multicast) {
13691 		freemsg(mp);
13692 		return (NULL);
13693 	}
13694 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13695 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13696 		freemsg(mp);
13697 		return (NULL);
13698 	}
13699 
13700 	/*
13701 	 * Mark this packet as having originated externally.
13702 	 *
13703 	 * For non-forwarding code path, ire_send later double
13704 	 * checks this interface to see if it is still exists
13705 	 * post-ARP resolution.
13706 	 *
13707 	 * Also, IPQOS uses this to differentiate between
13708 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13709 	 * QOS packet processing in ip_wput_attach_llhdr().
13710 	 * The QoS module can mark the b_band for a fastpath message
13711 	 * or the dl_priority field in a unitdata_req header for
13712 	 * CoS marking. This info can only be found in
13713 	 * ip_wput_attach_llhdr().
13714 	 */
13715 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13716 	/*
13717 	 * Clear the indication that this may have a hardware checksum
13718 	 * as we are not using it
13719 	 */
13720 	DB_CKSUMFLAGS(mp) = 0;
13721 
13722 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13723 	    msg_getlabel(mp), ipst);
13724 
13725 	if (ire == NULL && ret_action == Forward_check_multirt) {
13726 		/* Let ip_newroute handle CGTP  */
13727 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13728 		return (NULL);
13729 	}
13730 
13731 	if (ire != NULL)
13732 		return (ire);
13733 
13734 	mp->b_prev = mp->b_next = 0;
13735 
13736 	if (ret_action == Forward_blackhole) {
13737 		freemsg(mp);
13738 		return (NULL);
13739 	}
13740 	/* send icmp unreachable */
13741 	q = WR(q);
13742 	/* Sent by forwarding path, and router is global zone */
13743 	if (ip_source_routed(ipha, ipst)) {
13744 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13745 		    GLOBAL_ZONEID, ipst);
13746 	} else {
13747 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13748 		    ipst);
13749 	}
13750 
13751 	return (NULL);
13752 
13753 }
13754 
13755 /*
13756  * check ip header length and align it.
13757  */
13758 static boolean_t
13759 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13760 {
13761 	ssize_t len;
13762 	ill_t *ill;
13763 	ipha_t	*ipha;
13764 
13765 	len = MBLKL(mp);
13766 
13767 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13768 		ill = (ill_t *)q->q_ptr;
13769 
13770 		if (!OK_32PTR(mp->b_rptr))
13771 			IP_STAT(ipst, ip_notaligned1);
13772 		else
13773 			IP_STAT(ipst, ip_notaligned2);
13774 		/* Guard against bogus device drivers */
13775 		if (len < 0) {
13776 			/* clear b_prev - used by ip_mroute_decap */
13777 			mp->b_prev = NULL;
13778 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13779 			freemsg(mp);
13780 			return (B_FALSE);
13781 		}
13782 
13783 		if (ip_rput_pullups++ == 0) {
13784 			ipha = (ipha_t *)mp->b_rptr;
13785 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13786 			    "ip_check_and_align_header: %s forced us to "
13787 			    " pullup pkt, hdr len %ld, hdr addr %p",
13788 			    ill->ill_name, len, (void *)ipha);
13789 		}
13790 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13791 			/* clear b_prev - used by ip_mroute_decap */
13792 			mp->b_prev = NULL;
13793 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13794 			freemsg(mp);
13795 			return (B_FALSE);
13796 		}
13797 	}
13798 	return (B_TRUE);
13799 }
13800 
13801 /*
13802  * Handle the situation where a packet came in on `ill' but matched an IRE
13803  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13804  * for interface statistics.
13805  */
13806 ire_t *
13807 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13808 {
13809 	ire_t		*new_ire;
13810 	ill_t		*ire_ill;
13811 	uint_t		ifindex;
13812 	ip_stack_t	*ipst = ill->ill_ipst;
13813 	boolean_t	strict_check = B_FALSE;
13814 
13815 	/*
13816 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13817 	 * issue (e.g. packet received on an underlying interface matched an
13818 	 * IRE_LOCAL on its associated group interface).
13819 	 */
13820 	if (ire->ire_rfq != NULL &&
13821 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13822 		return (ire);
13823 	}
13824 
13825 	/*
13826 	 * Do another ire lookup here, using the ingress ill, to see if the
13827 	 * interface is in a usesrc group.
13828 	 * As long as the ills belong to the same group, we don't consider
13829 	 * them to be arriving on the wrong interface. Thus, if the switch
13830 	 * is doing inbound load spreading, we won't drop packets when the
13831 	 * ip*_strict_dst_multihoming switch is on.
13832 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13833 	 * where the local address may not be unique. In this case we were
13834 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13835 	 * actually returned. The new lookup, which is more specific, should
13836 	 * only find the IRE_LOCAL associated with the ingress ill if one
13837 	 * exists.
13838 	 */
13839 
13840 	if (ire->ire_ipversion == IPV4_VERSION) {
13841 		if (ipst->ips_ip_strict_dst_multihoming)
13842 			strict_check = B_TRUE;
13843 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13844 		    ill->ill_ipif, ALL_ZONES, NULL,
13845 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13846 	} else {
13847 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13848 		if (ipst->ips_ipv6_strict_dst_multihoming)
13849 			strict_check = B_TRUE;
13850 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13851 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13852 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13853 	}
13854 	/*
13855 	 * If the same ire that was returned in ip_input() is found then this
13856 	 * is an indication that usesrc groups are in use. The packet
13857 	 * arrived on a different ill in the group than the one associated with
13858 	 * the destination address.  If a different ire was found then the same
13859 	 * IP address must be hosted on multiple ills. This is possible with
13860 	 * unnumbered point2point interfaces. We switch to use this new ire in
13861 	 * order to have accurate interface statistics.
13862 	 */
13863 	if (new_ire != NULL) {
13864 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13865 			ire_refrele(ire);
13866 			ire = new_ire;
13867 		} else {
13868 			ire_refrele(new_ire);
13869 		}
13870 		return (ire);
13871 	} else if ((ire->ire_rfq == NULL) &&
13872 	    (ire->ire_ipversion == IPV4_VERSION)) {
13873 		/*
13874 		 * The best match could have been the original ire which
13875 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13876 		 * the strict multihoming checks are irrelevant as we consider
13877 		 * local addresses hosted on lo0 to be interface agnostic. We
13878 		 * only expect a null ire_rfq on IREs which are associated with
13879 		 * lo0 hence we can return now.
13880 		 */
13881 		return (ire);
13882 	}
13883 
13884 	/*
13885 	 * Chase pointers once and store locally.
13886 	 */
13887 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13888 	    (ill_t *)(ire->ire_rfq->q_ptr);
13889 	ifindex = ill->ill_usesrc_ifindex;
13890 
13891 	/*
13892 	 * Check if it's a legal address on the 'usesrc' interface.
13893 	 */
13894 	if ((ifindex != 0) && (ire_ill != NULL) &&
13895 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13896 		return (ire);
13897 	}
13898 
13899 	/*
13900 	 * If the ip*_strict_dst_multihoming switch is on then we can
13901 	 * only accept this packet if the interface is marked as routing.
13902 	 */
13903 	if (!(strict_check))
13904 		return (ire);
13905 
13906 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13907 	    ILLF_ROUTER) != 0) {
13908 		return (ire);
13909 	}
13910 
13911 	ire_refrele(ire);
13912 	return (NULL);
13913 }
13914 
13915 /*
13916  *
13917  * This is the fast forward path. If we are here, we dont need to
13918  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13919  * needed to find the nexthop in this case is much simpler
13920  */
13921 ire_t *
13922 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13923 {
13924 	ipha_t	*ipha;
13925 	ire_t	*src_ire;
13926 	ill_t	*stq_ill;
13927 	uint_t	hlen;
13928 	uint_t	pkt_len;
13929 	uint32_t sum;
13930 	queue_t	*dev_q;
13931 	ip_stack_t *ipst = ill->ill_ipst;
13932 	mblk_t *fpmp;
13933 	enum	ire_forward_action ret_action;
13934 
13935 	ipha = (ipha_t *)mp->b_rptr;
13936 
13937 	if (ire != NULL &&
13938 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13939 	    ire->ire_zoneid != ALL_ZONES) {
13940 		/*
13941 		 * Should only use IREs that are visible to the global
13942 		 * zone for forwarding.
13943 		 */
13944 		ire_refrele(ire);
13945 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13946 		/*
13947 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13948 		 * transient cases. In such case, just drop the packet
13949 		 */
13950 		if (ire->ire_type != IRE_CACHE)
13951 			goto drop;
13952 	}
13953 
13954 	/*
13955 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13956 	 * The loopback address check for both src and dst has already
13957 	 * been checked in ip_input
13958 	 */
13959 
13960 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13961 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13962 		goto drop;
13963 	}
13964 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13965 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13966 
13967 	if (src_ire != NULL) {
13968 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13969 		ire_refrele(src_ire);
13970 		goto drop;
13971 	}
13972 
13973 	/* No ire cache of nexthop. So first create one  */
13974 	if (ire == NULL) {
13975 
13976 		ire = ire_forward_simple(dst, &ret_action, ipst);
13977 
13978 		/*
13979 		 * We only come to ip_fast_forward if ip_cgtp_filter
13980 		 * is not set. So ire_forward() should not return with
13981 		 * Forward_check_multirt as the next action.
13982 		 */
13983 		ASSERT(ret_action != Forward_check_multirt);
13984 		if (ire == NULL) {
13985 			/* An attempt was made to forward the packet */
13986 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13987 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13988 			mp->b_prev = mp->b_next = 0;
13989 			/* send icmp unreachable */
13990 			/* Sent by forwarding path, and router is global zone */
13991 			if (ret_action == Forward_ret_icmp_err) {
13992 				if (ip_source_routed(ipha, ipst)) {
13993 					icmp_unreachable(ill->ill_wq, mp,
13994 					    ICMP_SOURCE_ROUTE_FAILED,
13995 					    GLOBAL_ZONEID, ipst);
13996 				} else {
13997 					icmp_unreachable(ill->ill_wq, mp,
13998 					    ICMP_HOST_UNREACHABLE,
13999 					    GLOBAL_ZONEID, ipst);
14000 				}
14001 			} else {
14002 				freemsg(mp);
14003 			}
14004 			return (NULL);
14005 		}
14006 	}
14007 
14008 	/*
14009 	 * Forwarding fastpath exception case:
14010 	 * If any of the following are true, we take the slowpath:
14011 	 *	o forwarding is not enabled
14012 	 *	o incoming and outgoing interface are the same, or in the same
14013 	 *	  IPMP group.
14014 	 *	o corresponding ire is in incomplete state
14015 	 *	o packet needs fragmentation
14016 	 *	o ARP cache is not resolved
14017 	 *
14018 	 * The codeflow from here on is thus:
14019 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14020 	 */
14021 	pkt_len = ntohs(ipha->ipha_length);
14022 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14023 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14024 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
14025 	    (ire->ire_nce == NULL) ||
14026 	    (pkt_len > ire->ire_max_frag) ||
14027 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
14028 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
14029 	    ipha->ipha_ttl <= 1) {
14030 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14031 		    ipha, ill, B_FALSE, B_TRUE);
14032 		return (ire);
14033 	}
14034 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14035 
14036 	DTRACE_PROBE4(ip4__forwarding__start,
14037 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14038 
14039 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14040 	    ipst->ips_ipv4firewall_forwarding,
14041 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
14042 
14043 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14044 
14045 	if (mp == NULL)
14046 		goto drop;
14047 
14048 	mp->b_datap->db_struioun.cksum.flags = 0;
14049 	/* Adjust the checksum to reflect the ttl decrement. */
14050 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14051 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14052 	ipha->ipha_ttl--;
14053 
14054 	/*
14055 	 * Write the link layer header.  We can do this safely here,
14056 	 * because we have already tested to make sure that the IP
14057 	 * policy is not set, and that we have a fast path destination
14058 	 * header.
14059 	 */
14060 	mp->b_rptr -= hlen;
14061 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14062 
14063 	UPDATE_IB_PKT_COUNT(ire);
14064 	ire->ire_last_used_time = lbolt;
14065 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14066 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14067 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14068 
14069 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14070 		dev_q = ire->ire_stq->q_next;
14071 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14072 			goto indiscard;
14073 	}
14074 
14075 	DTRACE_PROBE4(ip4__physical__out__start,
14076 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14077 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14078 	    ipst->ips_ipv4firewall_physical_out,
14079 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14080 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14081 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14082 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14083 	    ip6_t *, NULL, int, 0);
14084 
14085 	if (mp != NULL) {
14086 		if (ipst->ips_ipobs_enabled) {
14087 			zoneid_t szone;
14088 
14089 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14090 			    ipst, ALL_ZONES);
14091 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14092 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14093 		}
14094 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
14095 	}
14096 	return (ire);
14097 
14098 indiscard:
14099 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14100 drop:
14101 	if (mp != NULL)
14102 		freemsg(mp);
14103 	return (ire);
14104 
14105 }
14106 
14107 /*
14108  * This function is called in the forwarding slowpath, when
14109  * either the ire lacks the link-layer address, or the packet needs
14110  * further processing(eg. fragmentation), before transmission.
14111  */
14112 
14113 static void
14114 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14115     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14116 {
14117 	queue_t		*dev_q;
14118 	ire_t		*src_ire;
14119 	ip_stack_t	*ipst = ill->ill_ipst;
14120 	boolean_t	same_illgrp = B_FALSE;
14121 
14122 	ASSERT(ire->ire_stq != NULL);
14123 
14124 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14125 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14126 
14127 	/*
14128 	 * If the caller of this function is ip_fast_forward() skip the
14129 	 * next three checks as it does not apply.
14130 	 */
14131 	if (from_ip_fast_forward)
14132 		goto skip;
14133 
14134 	if (ll_multicast != 0) {
14135 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14136 		goto drop_pkt;
14137 	}
14138 
14139 	/*
14140 	 * check if ipha_src is a broadcast address. Note that this
14141 	 * check is redundant when we get here from ip_fast_forward()
14142 	 * which has already done this check. However, since we can
14143 	 * also get here from ip_rput_process_broadcast() or, for
14144 	 * for the slow path through ip_fast_forward(), we perform
14145 	 * the check again for code-reusability
14146 	 */
14147 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14148 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14149 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14150 		if (src_ire != NULL)
14151 			ire_refrele(src_ire);
14152 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14153 		ip2dbg(("ip_rput_process_forward: Received packet with"
14154 		    " bad src/dst address on %s\n", ill->ill_name));
14155 		goto drop_pkt;
14156 	}
14157 
14158 	/*
14159 	 * Check if we want to forward this one at this time.
14160 	 * We allow source routed packets on a host provided that
14161 	 * they go out the same ill or illgrp as they came in on.
14162 	 *
14163 	 * XXX To be quicker, we may wish to not chase pointers to
14164 	 * get the ILLF_ROUTER flag and instead store the
14165 	 * forwarding policy in the ire.  An unfortunate
14166 	 * side-effect of that would be requiring an ire flush
14167 	 * whenever the ILLF_ROUTER flag changes.
14168 	 */
14169 skip:
14170 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14171 
14172 	if (((ill->ill_flags &
14173 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14174 	    !(ip_source_routed(ipha, ipst) &&
14175 	    (ire->ire_rfq == q || same_illgrp))) {
14176 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14177 		if (ip_source_routed(ipha, ipst)) {
14178 			q = WR(q);
14179 			/*
14180 			 * Clear the indication that this may have
14181 			 * hardware checksum as we are not using it.
14182 			 */
14183 			DB_CKSUMFLAGS(mp) = 0;
14184 			/* Sent by forwarding path, and router is global zone */
14185 			icmp_unreachable(q, mp,
14186 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14187 			return;
14188 		}
14189 		goto drop_pkt;
14190 	}
14191 
14192 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14193 
14194 	/* Packet is being forwarded. Turning off hwcksum flag. */
14195 	DB_CKSUMFLAGS(mp) = 0;
14196 	if (ipst->ips_ip_g_send_redirects) {
14197 		/*
14198 		 * Check whether the incoming interface and outgoing
14199 		 * interface is part of the same group. If so,
14200 		 * send redirects.
14201 		 *
14202 		 * Check the source address to see if it originated
14203 		 * on the same logical subnet it is going back out on.
14204 		 * If so, we should be able to send it a redirect.
14205 		 * Avoid sending a redirect if the destination
14206 		 * is directly connected (i.e., ipha_dst is the same
14207 		 * as ire_gateway_addr or the ire_addr of the
14208 		 * nexthop IRE_CACHE ), or if the packet was source
14209 		 * routed out this interface.
14210 		 */
14211 		ipaddr_t src, nhop;
14212 		mblk_t	*mp1;
14213 		ire_t	*nhop_ire = NULL;
14214 
14215 		/*
14216 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14217 		 * If so, send redirects.
14218 		 */
14219 		if ((ire->ire_rfq == q || same_illgrp) &&
14220 		    !ip_source_routed(ipha, ipst)) {
14221 
14222 			nhop = (ire->ire_gateway_addr != 0 ?
14223 			    ire->ire_gateway_addr : ire->ire_addr);
14224 
14225 			if (ipha->ipha_dst == nhop) {
14226 				/*
14227 				 * We avoid sending a redirect if the
14228 				 * destination is directly connected
14229 				 * because it is possible that multiple
14230 				 * IP subnets may have been configured on
14231 				 * the link, and the source may not
14232 				 * be on the same subnet as ip destination,
14233 				 * even though they are on the same
14234 				 * physical link.
14235 				 */
14236 				goto sendit;
14237 			}
14238 
14239 			src = ipha->ipha_src;
14240 
14241 			/*
14242 			 * We look up the interface ire for the nexthop,
14243 			 * to see if ipha_src is in the same subnet
14244 			 * as the nexthop.
14245 			 *
14246 			 * Note that, if, in the future, IRE_CACHE entries
14247 			 * are obsoleted,  this lookup will not be needed,
14248 			 * as the ire passed to this function will be the
14249 			 * same as the nhop_ire computed below.
14250 			 */
14251 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14252 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14253 			    0, NULL, MATCH_IRE_TYPE, ipst);
14254 
14255 			if (nhop_ire != NULL) {
14256 				if ((src & nhop_ire->ire_mask) ==
14257 				    (nhop & nhop_ire->ire_mask)) {
14258 					/*
14259 					 * The source is directly connected.
14260 					 * Just copy the ip header (which is
14261 					 * in the first mblk)
14262 					 */
14263 					mp1 = copyb(mp);
14264 					if (mp1 != NULL) {
14265 						icmp_send_redirect(WR(q), mp1,
14266 						    nhop, ipst);
14267 					}
14268 				}
14269 				ire_refrele(nhop_ire);
14270 			}
14271 		}
14272 	}
14273 sendit:
14274 	dev_q = ire->ire_stq->q_next;
14275 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14276 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14277 		freemsg(mp);
14278 		return;
14279 	}
14280 
14281 	ip_rput_forward(ire, ipha, mp, ill);
14282 	return;
14283 
14284 drop_pkt:
14285 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14286 	freemsg(mp);
14287 }
14288 
14289 ire_t *
14290 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14291     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14292 {
14293 	queue_t		*q;
14294 	uint16_t	hcksumflags;
14295 	ip_stack_t	*ipst = ill->ill_ipst;
14296 
14297 	q = *qp;
14298 
14299 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14300 
14301 	/*
14302 	 * Clear the indication that this may have hardware
14303 	 * checksum as we are not using it for forwarding.
14304 	 */
14305 	hcksumflags = DB_CKSUMFLAGS(mp);
14306 	DB_CKSUMFLAGS(mp) = 0;
14307 
14308 	/*
14309 	 * Directed broadcast forwarding: if the packet came in over a
14310 	 * different interface then it is routed out over we can forward it.
14311 	 */
14312 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14313 		ire_refrele(ire);
14314 		freemsg(mp);
14315 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14316 		return (NULL);
14317 	}
14318 	/*
14319 	 * For multicast we have set dst to be INADDR_BROADCAST
14320 	 * for delivering to all STREAMS.
14321 	 */
14322 	if (!CLASSD(ipha->ipha_dst)) {
14323 		ire_t *new_ire;
14324 		ipif_t *ipif;
14325 
14326 		ipif = ipif_get_next_ipif(NULL, ill);
14327 		if (ipif == NULL) {
14328 discard:		ire_refrele(ire);
14329 			freemsg(mp);
14330 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14331 			return (NULL);
14332 		}
14333 		new_ire = ire_ctable_lookup(dst, 0, 0,
14334 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14335 		ipif_refrele(ipif);
14336 
14337 		if (new_ire != NULL) {
14338 			/*
14339 			 * If the matching IRE_BROADCAST is part of an IPMP
14340 			 * group, then drop the packet unless our ill has been
14341 			 * nominated to receive for the group.
14342 			 */
14343 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14344 			    new_ire->ire_rfq != q) {
14345 				ire_refrele(new_ire);
14346 				goto discard;
14347 			}
14348 
14349 			/*
14350 			 * In the special case of multirouted broadcast
14351 			 * packets, we unconditionally need to "gateway"
14352 			 * them to the appropriate interface here.
14353 			 * In the normal case, this cannot happen, because
14354 			 * there is no broadcast IRE tagged with the
14355 			 * RTF_MULTIRT flag.
14356 			 */
14357 			if (new_ire->ire_flags & RTF_MULTIRT) {
14358 				ire_refrele(new_ire);
14359 				if (ire->ire_rfq != NULL) {
14360 					q = ire->ire_rfq;
14361 					*qp = q;
14362 				}
14363 			} else {
14364 				ire_refrele(ire);
14365 				ire = new_ire;
14366 			}
14367 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14368 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14369 				/*
14370 				 * Free the message if
14371 				 * ip_g_forward_directed_bcast is turned
14372 				 * off for non-local broadcast.
14373 				 */
14374 				ire_refrele(ire);
14375 				freemsg(mp);
14376 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14377 				return (NULL);
14378 			}
14379 		} else {
14380 			/*
14381 			 * This CGTP packet successfully passed the
14382 			 * CGTP filter, but the related CGTP
14383 			 * broadcast IRE has not been found,
14384 			 * meaning that the redundant ipif is
14385 			 * probably down. However, if we discarded
14386 			 * this packet, its duplicate would be
14387 			 * filtered out by the CGTP filter so none
14388 			 * of them would get through. So we keep
14389 			 * going with this one.
14390 			 */
14391 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14392 			if (ire->ire_rfq != NULL) {
14393 				q = ire->ire_rfq;
14394 				*qp = q;
14395 			}
14396 		}
14397 	}
14398 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14399 		/*
14400 		 * Verify that there are not more then one
14401 		 * IRE_BROADCAST with this broadcast address which
14402 		 * has ire_stq set.
14403 		 * TODO: simplify, loop over all IRE's
14404 		 */
14405 		ire_t	*ire1;
14406 		int	num_stq = 0;
14407 		mblk_t	*mp1;
14408 
14409 		/* Find the first one with ire_stq set */
14410 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14411 		for (ire1 = ire; ire1 &&
14412 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14413 		    ire1 = ire1->ire_next)
14414 			;
14415 		if (ire1) {
14416 			ire_refrele(ire);
14417 			ire = ire1;
14418 			IRE_REFHOLD(ire);
14419 		}
14420 
14421 		/* Check if there are additional ones with stq set */
14422 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14423 			if (ire->ire_addr != ire1->ire_addr)
14424 				break;
14425 			if (ire1->ire_stq) {
14426 				num_stq++;
14427 				break;
14428 			}
14429 		}
14430 		rw_exit(&ire->ire_bucket->irb_lock);
14431 		if (num_stq == 1 && ire->ire_stq != NULL) {
14432 			ip1dbg(("ip_rput_process_broadcast: directed "
14433 			    "broadcast to 0x%x\n",
14434 			    ntohl(ire->ire_addr)));
14435 			mp1 = copymsg(mp);
14436 			if (mp1) {
14437 				switch (ipha->ipha_protocol) {
14438 				case IPPROTO_UDP:
14439 					ip_udp_input(q, mp1, ipha, ire, ill);
14440 					break;
14441 				default:
14442 					ip_proto_input(q, mp1, ipha, ire, ill,
14443 					    0);
14444 					break;
14445 				}
14446 			}
14447 			/*
14448 			 * Adjust ttl to 2 (1+1 - the forward engine
14449 			 * will decrement it by one.
14450 			 */
14451 			if (ip_csum_hdr(ipha)) {
14452 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14453 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14454 				freemsg(mp);
14455 				ire_refrele(ire);
14456 				return (NULL);
14457 			}
14458 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14459 			ipha->ipha_hdr_checksum = 0;
14460 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14461 			ip_rput_process_forward(q, mp, ire, ipha,
14462 			    ill, ll_multicast, B_FALSE);
14463 			ire_refrele(ire);
14464 			return (NULL);
14465 		}
14466 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14467 		    ntohl(ire->ire_addr)));
14468 	}
14469 
14470 	/* Restore any hardware checksum flags */
14471 	DB_CKSUMFLAGS(mp) = hcksumflags;
14472 	return (ire);
14473 }
14474 
14475 /* ARGSUSED */
14476 static boolean_t
14477 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14478     int *ll_multicast, ipaddr_t *dstp)
14479 {
14480 	ip_stack_t	*ipst = ill->ill_ipst;
14481 
14482 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14483 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14484 	    ntohs(ipha->ipha_length));
14485 
14486 	/*
14487 	 * So that we don't end up with dups, only one ill in an IPMP group is
14488 	 * nominated to receive multicast traffic.
14489 	 */
14490 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14491 		goto drop_pkt;
14492 
14493 	/*
14494 	 * Forward packets only if we have joined the allmulti
14495 	 * group on this interface.
14496 	 */
14497 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14498 		int retval;
14499 
14500 		/*
14501 		 * Clear the indication that this may have hardware
14502 		 * checksum as we are not using it.
14503 		 */
14504 		DB_CKSUMFLAGS(mp) = 0;
14505 		retval = ip_mforward(ill, ipha, mp);
14506 		/* ip_mforward updates mib variables if needed */
14507 		/* clear b_prev - used by ip_mroute_decap */
14508 		mp->b_prev = NULL;
14509 
14510 		switch (retval) {
14511 		case 0:
14512 			/*
14513 			 * pkt is okay and arrived on phyint.
14514 			 *
14515 			 * If we are running as a multicast router
14516 			 * we need to see all IGMP and/or PIM packets.
14517 			 */
14518 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14519 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14520 				goto done;
14521 			}
14522 			break;
14523 		case -1:
14524 			/* pkt is mal-formed, toss it */
14525 			goto drop_pkt;
14526 		case 1:
14527 			/* pkt is okay and arrived on a tunnel */
14528 			/*
14529 			 * If we are running a multicast router
14530 			 *  we need to see all igmp packets.
14531 			 */
14532 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14533 				*dstp = INADDR_BROADCAST;
14534 				*ll_multicast = 1;
14535 				return (B_FALSE);
14536 			}
14537 
14538 			goto drop_pkt;
14539 		}
14540 	}
14541 
14542 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14543 		/*
14544 		 * This might just be caused by the fact that
14545 		 * multiple IP Multicast addresses map to the same
14546 		 * link layer multicast - no need to increment counter!
14547 		 */
14548 		freemsg(mp);
14549 		return (B_TRUE);
14550 	}
14551 done:
14552 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14553 	/*
14554 	 * This assumes the we deliver to all streams for multicast
14555 	 * and broadcast packets.
14556 	 */
14557 	*dstp = INADDR_BROADCAST;
14558 	*ll_multicast = 1;
14559 	return (B_FALSE);
14560 drop_pkt:
14561 	ip2dbg(("ip_rput: drop pkt\n"));
14562 	freemsg(mp);
14563 	return (B_TRUE);
14564 }
14565 
14566 /*
14567  * This function is used to both return an indication of whether or not
14568  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14569  * and in doing so, determine whether or not it is broadcast vs multicast.
14570  * For it to be a broadcast packet, we must have the appropriate mblk_t
14571  * hanging off the ill_t.  If this is either not present or doesn't match
14572  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14573  * to be multicast.  Thus NICs that have no broadcast address (or no
14574  * capability for one, such as point to point links) cannot return as
14575  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14576  * the return values simplifies the current use of the return value of this
14577  * function, which is to pass through the multicast/broadcast characteristic
14578  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14579  * changing the return value to some other symbol demands the appropriate
14580  * "translation" when hpe_flags is set prior to calling hook_run() for
14581  * packet events.
14582  */
14583 int
14584 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14585 {
14586 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14587 	mblk_t *bmp;
14588 
14589 	if (ind->dl_group_address) {
14590 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14591 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14592 		    MBLKL(mb) &&
14593 		    (bmp = ill->ill_bcast_mp) != NULL) {
14594 			dl_unitdata_req_t *dlur;
14595 			uint8_t *bphys_addr;
14596 
14597 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14598 			if (ill->ill_sap_length < 0)
14599 				bphys_addr = (uchar_t *)dlur +
14600 				    dlur->dl_dest_addr_offset;
14601 			else
14602 				bphys_addr = (uchar_t *)dlur +
14603 				    dlur->dl_dest_addr_offset +
14604 				    ill->ill_sap_length;
14605 
14606 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14607 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14608 				return (HPE_BROADCAST);
14609 			}
14610 			return (HPE_MULTICAST);
14611 		}
14612 		return (HPE_MULTICAST);
14613 	}
14614 	return (0);
14615 }
14616 
14617 static boolean_t
14618 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14619     int *ll_multicast, mblk_t **mpp)
14620 {
14621 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14622 	boolean_t must_copy = B_FALSE;
14623 	struct iocblk   *iocp;
14624 	ipha_t		*ipha;
14625 	ip_stack_t	*ipst = ill->ill_ipst;
14626 
14627 #define	rptr    ((uchar_t *)ipha)
14628 
14629 	first_mp = *first_mpp;
14630 	mp = *mpp;
14631 
14632 	ASSERT(first_mp == mp);
14633 
14634 	/*
14635 	 * if db_ref > 1 then copymsg and free original. Packet may be
14636 	 * changed and do not want other entity who has a reference to this
14637 	 * message to trip over the changes. This is a blind change because
14638 	 * trying to catch all places that might change packet is too
14639 	 * difficult (since it may be a module above this one)
14640 	 *
14641 	 * This corresponds to the non-fast path case. We walk down the full
14642 	 * chain in this case, and check the db_ref count of all the dblks,
14643 	 * and do a copymsg if required. It is possible that the db_ref counts
14644 	 * of the data blocks in the mblk chain can be different.
14645 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14646 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14647 	 * 'snoop' is running.
14648 	 */
14649 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14650 		if (mp1->b_datap->db_ref > 1) {
14651 			must_copy = B_TRUE;
14652 			break;
14653 		}
14654 	}
14655 
14656 	if (must_copy) {
14657 		mp1 = copymsg(mp);
14658 		if (mp1 == NULL) {
14659 			for (mp1 = mp; mp1 != NULL;
14660 			    mp1 = mp1->b_cont) {
14661 				mp1->b_next = NULL;
14662 				mp1->b_prev = NULL;
14663 			}
14664 			freemsg(mp);
14665 			if (ill != NULL) {
14666 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14667 			} else {
14668 				BUMP_MIB(&ipst->ips_ip_mib,
14669 				    ipIfStatsInDiscards);
14670 			}
14671 			return (B_TRUE);
14672 		}
14673 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14674 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14675 			/* Copy b_prev - used by ip_mroute_decap */
14676 			to_mp->b_prev = from_mp->b_prev;
14677 			from_mp->b_prev = NULL;
14678 		}
14679 		*first_mpp = first_mp = mp1;
14680 		freemsg(mp);
14681 		mp = mp1;
14682 		*mpp = mp1;
14683 	}
14684 
14685 	ipha = (ipha_t *)mp->b_rptr;
14686 
14687 	/*
14688 	 * previous code has a case for M_DATA.
14689 	 * We want to check how that happens.
14690 	 */
14691 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14692 	switch (first_mp->b_datap->db_type) {
14693 	case M_PROTO:
14694 	case M_PCPROTO:
14695 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14696 		    DL_UNITDATA_IND) {
14697 			/* Go handle anything other than data elsewhere. */
14698 			ip_rput_dlpi(q, mp);
14699 			return (B_TRUE);
14700 		}
14701 
14702 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14703 		/* Ditch the DLPI header. */
14704 		mp1 = mp->b_cont;
14705 		ASSERT(first_mp == mp);
14706 		*first_mpp = mp1;
14707 		freeb(mp);
14708 		*mpp = mp1;
14709 		return (B_FALSE);
14710 	case M_IOCACK:
14711 		ip1dbg(("got iocack "));
14712 		iocp = (struct iocblk *)mp->b_rptr;
14713 		switch (iocp->ioc_cmd) {
14714 		case DL_IOC_HDR_INFO:
14715 			ill = (ill_t *)q->q_ptr;
14716 			ill_fastpath_ack(ill, mp);
14717 			return (B_TRUE);
14718 		case SIOCSTUNPARAM:
14719 		case OSIOCSTUNPARAM:
14720 			/* Go through qwriter_ip */
14721 			break;
14722 		case SIOCGTUNPARAM:
14723 		case OSIOCGTUNPARAM:
14724 			ip_rput_other(NULL, q, mp, NULL);
14725 			return (B_TRUE);
14726 		default:
14727 			putnext(q, mp);
14728 			return (B_TRUE);
14729 		}
14730 		/* FALLTHRU */
14731 	case M_ERROR:
14732 	case M_HANGUP:
14733 		/*
14734 		 * Since this is on the ill stream we unconditionally
14735 		 * bump up the refcount
14736 		 */
14737 		ill_refhold(ill);
14738 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14739 		return (B_TRUE);
14740 	case M_CTL:
14741 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14742 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14743 		    IPHADA_M_CTL)) {
14744 			/*
14745 			 * It's an IPsec accelerated packet.
14746 			 * Make sure that the ill from which we received the
14747 			 * packet has enabled IPsec hardware acceleration.
14748 			 */
14749 			if (!(ill->ill_capabilities &
14750 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14751 				/* IPsec kstats: bean counter */
14752 				freemsg(mp);
14753 				return (B_TRUE);
14754 			}
14755 
14756 			/*
14757 			 * Make mp point to the mblk following the M_CTL,
14758 			 * then process according to type of mp.
14759 			 * After this processing, first_mp will point to
14760 			 * the data-attributes and mp to the pkt following
14761 			 * the M_CTL.
14762 			 */
14763 			mp = first_mp->b_cont;
14764 			if (mp == NULL) {
14765 				freemsg(first_mp);
14766 				return (B_TRUE);
14767 			}
14768 			/*
14769 			 * A Hardware Accelerated packet can only be M_DATA
14770 			 * ESP or AH packet.
14771 			 */
14772 			if (mp->b_datap->db_type != M_DATA) {
14773 				/* non-M_DATA IPsec accelerated packet */
14774 				IPSECHW_DEBUG(IPSECHW_PKT,
14775 				    ("non-M_DATA IPsec accelerated pkt\n"));
14776 				freemsg(first_mp);
14777 				return (B_TRUE);
14778 			}
14779 			ipha = (ipha_t *)mp->b_rptr;
14780 			if (ipha->ipha_protocol != IPPROTO_AH &&
14781 			    ipha->ipha_protocol != IPPROTO_ESP) {
14782 				IPSECHW_DEBUG(IPSECHW_PKT,
14783 				    ("non-M_DATA IPsec accelerated pkt\n"));
14784 				freemsg(first_mp);
14785 				return (B_TRUE);
14786 			}
14787 			*mpp = mp;
14788 			return (B_FALSE);
14789 		}
14790 		putnext(q, mp);
14791 		return (B_TRUE);
14792 	case M_IOCNAK:
14793 		ip1dbg(("got iocnak "));
14794 		iocp = (struct iocblk *)mp->b_rptr;
14795 		switch (iocp->ioc_cmd) {
14796 		case SIOCSTUNPARAM:
14797 		case OSIOCSTUNPARAM:
14798 			/*
14799 			 * Since this is on the ill stream we unconditionally
14800 			 * bump up the refcount
14801 			 */
14802 			ill_refhold(ill);
14803 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14804 			return (B_TRUE);
14805 		case DL_IOC_HDR_INFO:
14806 		case SIOCGTUNPARAM:
14807 		case OSIOCGTUNPARAM:
14808 			ip_rput_other(NULL, q, mp, NULL);
14809 			return (B_TRUE);
14810 		default:
14811 			break;
14812 		}
14813 		/* FALLTHRU */
14814 	default:
14815 		putnext(q, mp);
14816 		return (B_TRUE);
14817 	}
14818 }
14819 
14820 /* Read side put procedure.  Packets coming from the wire arrive here. */
14821 void
14822 ip_rput(queue_t *q, mblk_t *mp)
14823 {
14824 	ill_t	*ill;
14825 	union DL_primitives *dl;
14826 
14827 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14828 
14829 	ill = (ill_t *)q->q_ptr;
14830 
14831 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14832 		/*
14833 		 * If things are opening or closing, only accept high-priority
14834 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14835 		 * created; on close, things hanging off the ill may have been
14836 		 * freed already.)
14837 		 */
14838 		dl = (union DL_primitives *)mp->b_rptr;
14839 		if (DB_TYPE(mp) != M_PCPROTO ||
14840 		    dl->dl_primitive == DL_UNITDATA_IND) {
14841 			/*
14842 			 * SIOC[GS]TUNPARAM ioctls can come here.
14843 			 */
14844 			inet_freemsg(mp);
14845 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14846 			    "ip_rput_end: q %p (%S)", q, "uninit");
14847 			return;
14848 		}
14849 	}
14850 
14851 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14852 	    "ip_rput_end: q %p (%S)", q, "end");
14853 
14854 	ip_input(ill, NULL, mp, NULL);
14855 }
14856 
14857 static mblk_t *
14858 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14859 {
14860 	mblk_t *mp1;
14861 	boolean_t adjusted = B_FALSE;
14862 	ip_stack_t *ipst = ill->ill_ipst;
14863 
14864 	IP_STAT(ipst, ip_db_ref);
14865 	/*
14866 	 * The IP_RECVSLLA option depends on having the
14867 	 * link layer header. First check that:
14868 	 * a> the underlying device is of type ether,
14869 	 * since this option is currently supported only
14870 	 * over ethernet.
14871 	 * b> there is enough room to copy over the link
14872 	 * layer header.
14873 	 *
14874 	 * Once the checks are done, adjust rptr so that
14875 	 * the link layer header will be copied via
14876 	 * copymsg. Note that, IFT_ETHER may be returned
14877 	 * by some non-ethernet drivers but in this case
14878 	 * the second check will fail.
14879 	 */
14880 	if (ill->ill_type == IFT_ETHER &&
14881 	    (mp->b_rptr - mp->b_datap->db_base) >=
14882 	    sizeof (struct ether_header)) {
14883 		mp->b_rptr -= sizeof (struct ether_header);
14884 		adjusted = B_TRUE;
14885 	}
14886 	mp1 = copymsg(mp);
14887 
14888 	if (mp1 == NULL) {
14889 		mp->b_next = NULL;
14890 		/* clear b_prev - used by ip_mroute_decap */
14891 		mp->b_prev = NULL;
14892 		freemsg(mp);
14893 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14894 		return (NULL);
14895 	}
14896 
14897 	if (adjusted) {
14898 		/*
14899 		 * Copy is done. Restore the pointer in
14900 		 * the _new_ mblk
14901 		 */
14902 		mp1->b_rptr += sizeof (struct ether_header);
14903 	}
14904 
14905 	/* Copy b_prev - used by ip_mroute_decap */
14906 	mp1->b_prev = mp->b_prev;
14907 	mp->b_prev = NULL;
14908 
14909 	/* preserve the hardware checksum flags and data, if present */
14910 	if (DB_CKSUMFLAGS(mp) != 0) {
14911 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14912 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14913 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14914 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14915 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14916 	}
14917 
14918 	freemsg(mp);
14919 	return (mp1);
14920 }
14921 
14922 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14923 	if (tail != NULL)					\
14924 		tail->b_next = mp;				\
14925 	else							\
14926 		head = mp;					\
14927 	tail = mp;						\
14928 	cnt++;							\
14929 }
14930 
14931 /*
14932  * Direct read side procedure capable of dealing with chains. GLDv3 based
14933  * drivers call this function directly with mblk chains while STREAMS
14934  * read side procedure ip_rput() calls this for single packet with ip_ring
14935  * set to NULL to process one packet at a time.
14936  *
14937  * The ill will always be valid if this function is called directly from
14938  * the driver.
14939  *
14940  * If ip_input() is called from GLDv3:
14941  *
14942  *   - This must be a non-VLAN IP stream.
14943  *   - 'mp' is either an untagged or a special priority-tagged packet.
14944  *   - Any VLAN tag that was in the MAC header has been stripped.
14945  *
14946  * If the IP header in packet is not 32-bit aligned, every message in the
14947  * chain will be aligned before further operations. This is required on SPARC
14948  * platform.
14949  */
14950 /* ARGSUSED */
14951 void
14952 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14953     struct mac_header_info_s *mhip)
14954 {
14955 	ipaddr_t		dst = NULL;
14956 	ipaddr_t		prev_dst;
14957 	ire_t			*ire = NULL;
14958 	ipha_t			*ipha;
14959 	uint_t			pkt_len;
14960 	ssize_t			len;
14961 	uint_t			opt_len;
14962 	int			ll_multicast;
14963 	int			cgtp_flt_pkt;
14964 	queue_t			*q = ill->ill_rq;
14965 	squeue_t		*curr_sqp = NULL;
14966 	mblk_t 			*head = NULL;
14967 	mblk_t			*tail = NULL;
14968 	mblk_t			*first_mp;
14969 	int			cnt = 0;
14970 	ip_stack_t		*ipst = ill->ill_ipst;
14971 	mblk_t			*mp;
14972 	mblk_t			*dmp;
14973 	uint8_t			tag;
14974 
14975 	ASSERT(mp_chain != NULL);
14976 	ASSERT(ill != NULL);
14977 
14978 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14979 
14980 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14981 
14982 #define	rptr	((uchar_t *)ipha)
14983 
14984 	while (mp_chain != NULL) {
14985 		mp = mp_chain;
14986 		mp_chain = mp_chain->b_next;
14987 		mp->b_next = NULL;
14988 		ll_multicast = 0;
14989 
14990 		/*
14991 		 * We do ire caching from one iteration to
14992 		 * another. In the event the packet chain contains
14993 		 * all packets from the same dst, this caching saves
14994 		 * an ire_cache_lookup for each of the succeeding
14995 		 * packets in a packet chain.
14996 		 */
14997 		prev_dst = dst;
14998 
14999 		/*
15000 		 * if db_ref > 1 then copymsg and free original. Packet
15001 		 * may be changed and we do not want the other entity
15002 		 * who has a reference to this message to trip over the
15003 		 * changes. This is a blind change because trying to
15004 		 * catch all places that might change the packet is too
15005 		 * difficult.
15006 		 *
15007 		 * This corresponds to the fast path case, where we have
15008 		 * a chain of M_DATA mblks.  We check the db_ref count
15009 		 * of only the 1st data block in the mblk chain. There
15010 		 * doesn't seem to be a reason why a device driver would
15011 		 * send up data with varying db_ref counts in the mblk
15012 		 * chain. In any case the Fast path is a private
15013 		 * interface, and our drivers don't do such a thing.
15014 		 * Given the above assumption, there is no need to walk
15015 		 * down the entire mblk chain (which could have a
15016 		 * potential performance problem)
15017 		 *
15018 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
15019 		 * to here because of exclusive ip stacks and vnics.
15020 		 * Packets transmitted from exclusive stack over vnic
15021 		 * can have db_ref > 1 and when it gets looped back to
15022 		 * another vnic in a different zone, you have ip_input()
15023 		 * getting dblks with db_ref > 1. So if someone
15024 		 * complains of TCP performance under this scenario,
15025 		 * take a serious look here on the impact of copymsg().
15026 		 */
15027 
15028 		if (DB_REF(mp) > 1) {
15029 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
15030 				continue;
15031 		}
15032 
15033 		/*
15034 		 * Check and align the IP header.
15035 		 */
15036 		first_mp = mp;
15037 		if (DB_TYPE(mp) == M_DATA) {
15038 			dmp = mp;
15039 		} else if (DB_TYPE(mp) == M_PROTO &&
15040 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15041 			dmp = mp->b_cont;
15042 		} else {
15043 			dmp = NULL;
15044 		}
15045 		if (dmp != NULL) {
15046 			/*
15047 			 * IP header ptr not aligned?
15048 			 * OR IP header not complete in first mblk
15049 			 */
15050 			if (!OK_32PTR(dmp->b_rptr) ||
15051 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15052 				if (!ip_check_and_align_header(q, dmp, ipst))
15053 					continue;
15054 			}
15055 		}
15056 
15057 		/*
15058 		 * ip_input fast path
15059 		 */
15060 
15061 		/* mblk type is not M_DATA */
15062 		if (DB_TYPE(mp) != M_DATA) {
15063 			if (ip_rput_process_notdata(q, &first_mp, ill,
15064 			    &ll_multicast, &mp))
15065 				continue;
15066 
15067 			/*
15068 			 * The only way we can get here is if we had a
15069 			 * packet that was either a DL_UNITDATA_IND or
15070 			 * an M_CTL for an IPsec accelerated packet.
15071 			 *
15072 			 * In either case, the first_mp will point to
15073 			 * the leading M_PROTO or M_CTL.
15074 			 */
15075 			ASSERT(first_mp != NULL);
15076 		} else if (mhip != NULL) {
15077 			/*
15078 			 * ll_multicast is set here so that it is ready
15079 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15080 			 * manipulates ll_multicast in the same fashion when
15081 			 * called from ip_rput_process_notdata.
15082 			 */
15083 			switch (mhip->mhi_dsttype) {
15084 			case MAC_ADDRTYPE_MULTICAST :
15085 				ll_multicast = HPE_MULTICAST;
15086 				break;
15087 			case MAC_ADDRTYPE_BROADCAST :
15088 				ll_multicast = HPE_BROADCAST;
15089 				break;
15090 			default :
15091 				break;
15092 			}
15093 		}
15094 
15095 		/* Only M_DATA can come here and it is always aligned */
15096 		ASSERT(DB_TYPE(mp) == M_DATA);
15097 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15098 
15099 		ipha = (ipha_t *)mp->b_rptr;
15100 		len = mp->b_wptr - rptr;
15101 		pkt_len = ntohs(ipha->ipha_length);
15102 
15103 		/*
15104 		 * We must count all incoming packets, even if they end
15105 		 * up being dropped later on.
15106 		 */
15107 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15108 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15109 
15110 		/* multiple mblk or too short */
15111 		len -= pkt_len;
15112 		if (len != 0) {
15113 			/*
15114 			 * Make sure we have data length consistent
15115 			 * with the IP header.
15116 			 */
15117 			if (mp->b_cont == NULL) {
15118 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15119 					BUMP_MIB(ill->ill_ip_mib,
15120 					    ipIfStatsInHdrErrors);
15121 					ip2dbg(("ip_input: drop pkt\n"));
15122 					freemsg(mp);
15123 					continue;
15124 				}
15125 				mp->b_wptr = rptr + pkt_len;
15126 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15127 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15128 					BUMP_MIB(ill->ill_ip_mib,
15129 					    ipIfStatsInHdrErrors);
15130 					ip2dbg(("ip_input: drop pkt\n"));
15131 					freemsg(mp);
15132 					continue;
15133 				}
15134 				(void) adjmsg(mp, -len);
15135 				/*
15136 				 * As the message len was adjusted, invalidate
15137 				 * any hw checksum here. This will force IP to
15138 				 * calculate the checksum in sw, but only for
15139 				 * this packet.
15140 				 */
15141 				DB_CKSUMFLAGS(mp) = 0;
15142 				IP_STAT(ipst, ip_multimblk3);
15143 			}
15144 		}
15145 
15146 		/* Obtain the dst of the current packet */
15147 		dst = ipha->ipha_dst;
15148 
15149 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15150 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15151 		    ipha, ip6_t *, NULL, int, 0);
15152 
15153 		/*
15154 		 * The following test for loopback is faster than
15155 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15156 		 * operations.
15157 		 * Note that these addresses are always in network byte order
15158 		 */
15159 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15160 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15161 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15162 			freemsg(mp);
15163 			continue;
15164 		}
15165 
15166 		/*
15167 		 * The event for packets being received from a 'physical'
15168 		 * interface is placed after validation of the source and/or
15169 		 * destination address as being local so that packets can be
15170 		 * redirected to loopback addresses using ipnat.
15171 		 */
15172 		DTRACE_PROBE4(ip4__physical__in__start,
15173 		    ill_t *, ill, ill_t *, NULL,
15174 		    ipha_t *, ipha, mblk_t *, first_mp);
15175 
15176 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15177 		    ipst->ips_ipv4firewall_physical_in,
15178 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15179 
15180 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15181 
15182 		if (first_mp == NULL) {
15183 			continue;
15184 		}
15185 		dst = ipha->ipha_dst;
15186 		/*
15187 		 * Attach any necessary label information to
15188 		 * this packet
15189 		 */
15190 		if (is_system_labeled() &&
15191 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15192 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15193 			freemsg(mp);
15194 			continue;
15195 		}
15196 
15197 		if (ipst->ips_ipobs_enabled) {
15198 			zoneid_t dzone;
15199 
15200 			/*
15201 			 * On the inbound path the src zone will be unknown as
15202 			 * this packet has come from the wire.
15203 			 */
15204 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15205 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15206 			    ill, IPV4_VERSION, 0, ipst);
15207 		}
15208 
15209 		/*
15210 		 * Reuse the cached ire only if the ipha_dst of the previous
15211 		 * packet is the same as the current packet AND it is not
15212 		 * INADDR_ANY.
15213 		 */
15214 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15215 		    (ire != NULL)) {
15216 			ire_refrele(ire);
15217 			ire = NULL;
15218 		}
15219 
15220 		opt_len = ipha->ipha_version_and_hdr_length -
15221 		    IP_SIMPLE_HDR_VERSION;
15222 
15223 		/*
15224 		 * Check to see if we can take the fastpath.
15225 		 * That is possible if the following conditions are met
15226 		 *	o Tsol disabled
15227 		 *	o CGTP disabled
15228 		 *	o ipp_action_count is 0
15229 		 *	o no options in the packet
15230 		 *	o not a RSVP packet
15231 		 * 	o not a multicast packet
15232 		 *	o ill not in IP_DHCPINIT_IF mode
15233 		 */
15234 		if (!is_system_labeled() &&
15235 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15236 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15237 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15238 			if (ire == NULL)
15239 				ire = ire_cache_lookup_simple(dst, ipst);
15240 			/*
15241 			 * Unless forwarding is enabled, dont call
15242 			 * ip_fast_forward(). Incoming packet is for forwarding
15243 			 */
15244 			if ((ill->ill_flags & ILLF_ROUTER) &&
15245 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15246 				ire = ip_fast_forward(ire, dst, ill, mp);
15247 				continue;
15248 			}
15249 			/* incoming packet is for local consumption */
15250 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15251 				goto local;
15252 		}
15253 
15254 		/*
15255 		 * Disable ire caching for anything more complex
15256 		 * than the simple fast path case we checked for above.
15257 		 */
15258 		if (ire != NULL) {
15259 			ire_refrele(ire);
15260 			ire = NULL;
15261 		}
15262 
15263 		/*
15264 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15265 		 * server to unicast DHCP packets to a DHCP client using the
15266 		 * IP address it is offering to the client.  This can be
15267 		 * disabled through the "broadcast bit", but not all DHCP
15268 		 * servers honor that bit.  Therefore, to interoperate with as
15269 		 * many DHCP servers as possible, the DHCP client allows the
15270 		 * server to unicast, but we treat those packets as broadcast
15271 		 * here.  Note that we don't rewrite the packet itself since
15272 		 * (a) that would mess up the checksums and (b) the DHCP
15273 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15274 		 * hand it the packet regardless.
15275 		 */
15276 		if (ill->ill_dhcpinit != 0 &&
15277 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15278 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15279 			udpha_t *udpha;
15280 
15281 			/*
15282 			 * Reload ipha since pullupmsg() can change b_rptr.
15283 			 */
15284 			ipha = (ipha_t *)mp->b_rptr;
15285 			udpha = (udpha_t *)&ipha[1];
15286 
15287 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15288 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15289 				    mblk_t *, mp);
15290 				dst = INADDR_BROADCAST;
15291 			}
15292 		}
15293 
15294 		/* Full-blown slow path */
15295 		if (opt_len != 0) {
15296 			if (len != 0)
15297 				IP_STAT(ipst, ip_multimblk4);
15298 			else
15299 				IP_STAT(ipst, ip_ipoptions);
15300 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15301 			    &dst, ipst))
15302 				continue;
15303 		}
15304 
15305 		/*
15306 		 * Invoke the CGTP (multirouting) filtering module to process
15307 		 * the incoming packet. Packets identified as duplicates
15308 		 * must be discarded. Filtering is active only if the
15309 		 * the ip_cgtp_filter ndd variable is non-zero.
15310 		 */
15311 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15312 		if (ipst->ips_ip_cgtp_filter &&
15313 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15314 			netstackid_t stackid;
15315 
15316 			stackid = ipst->ips_netstack->netstack_stackid;
15317 			cgtp_flt_pkt =
15318 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15319 			    ill->ill_phyint->phyint_ifindex, mp);
15320 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15321 				freemsg(first_mp);
15322 				continue;
15323 			}
15324 		}
15325 
15326 		/*
15327 		 * If rsvpd is running, let RSVP daemon handle its processing
15328 		 * and forwarding of RSVP multicast/unicast packets.
15329 		 * If rsvpd is not running but mrouted is running, RSVP
15330 		 * multicast packets are forwarded as multicast traffic
15331 		 * and RSVP unicast packets are forwarded by unicast router.
15332 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15333 		 * packets are not forwarded, but the unicast packets are
15334 		 * forwarded like unicast traffic.
15335 		 */
15336 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15337 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15338 		    NULL) {
15339 			/* RSVP packet and rsvpd running. Treat as ours */
15340 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15341 			/*
15342 			 * This assumes that we deliver to all streams for
15343 			 * multicast and broadcast packets.
15344 			 * We have to force ll_multicast to 1 to handle the
15345 			 * M_DATA messages passed in from ip_mroute_decap.
15346 			 */
15347 			dst = INADDR_BROADCAST;
15348 			ll_multicast = 1;
15349 		} else if (CLASSD(dst)) {
15350 			/* packet is multicast */
15351 			mp->b_next = NULL;
15352 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15353 			    &ll_multicast, &dst))
15354 				continue;
15355 		}
15356 
15357 		if (ire == NULL) {
15358 			ire = ire_cache_lookup(dst, ALL_ZONES,
15359 			    msg_getlabel(mp), ipst);
15360 		}
15361 
15362 		if (ire != NULL && ire->ire_stq != NULL &&
15363 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15364 		    ire->ire_zoneid != ALL_ZONES) {
15365 			/*
15366 			 * Should only use IREs that are visible from the
15367 			 * global zone for forwarding.
15368 			 */
15369 			ire_refrele(ire);
15370 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15371 			    msg_getlabel(mp), ipst);
15372 		}
15373 
15374 		if (ire == NULL) {
15375 			/*
15376 			 * No IRE for this destination, so it can't be for us.
15377 			 * Unless we are forwarding, drop the packet.
15378 			 * We have to let source routed packets through
15379 			 * since we don't yet know if they are 'ping -l'
15380 			 * packets i.e. if they will go out over the
15381 			 * same interface as they came in on.
15382 			 */
15383 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15384 			if (ire == NULL)
15385 				continue;
15386 		}
15387 
15388 		/*
15389 		 * Broadcast IRE may indicate either broadcast or
15390 		 * multicast packet
15391 		 */
15392 		if (ire->ire_type == IRE_BROADCAST) {
15393 			/*
15394 			 * Skip broadcast checks if packet is UDP multicast;
15395 			 * we'd rather not enter ip_rput_process_broadcast()
15396 			 * unless the packet is broadcast for real, since
15397 			 * that routine is a no-op for multicast.
15398 			 */
15399 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15400 			    !CLASSD(ipha->ipha_dst)) {
15401 				ire = ip_rput_process_broadcast(&q, mp,
15402 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15403 				    ll_multicast);
15404 				if (ire == NULL)
15405 					continue;
15406 			}
15407 		} else if (ire->ire_stq != NULL) {
15408 			/* fowarding? */
15409 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15410 			    ll_multicast, B_FALSE);
15411 			/* ip_rput_process_forward consumed the packet */
15412 			continue;
15413 		}
15414 
15415 local:
15416 		/*
15417 		 * If the queue in the ire is different to the ingress queue
15418 		 * then we need to check to see if we can accept the packet.
15419 		 * Note that for multicast packets and broadcast packets sent
15420 		 * to a broadcast address which is shared between multiple
15421 		 * interfaces we should not do this since we just got a random
15422 		 * broadcast ire.
15423 		 */
15424 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15425 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15426 			if (ire == NULL) {
15427 				/* Drop packet */
15428 				BUMP_MIB(ill->ill_ip_mib,
15429 				    ipIfStatsForwProhibits);
15430 				freemsg(mp);
15431 				continue;
15432 			}
15433 			if (ire->ire_rfq != NULL)
15434 				q = ire->ire_rfq;
15435 		}
15436 
15437 		switch (ipha->ipha_protocol) {
15438 		case IPPROTO_TCP:
15439 			ASSERT(first_mp == mp);
15440 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15441 			    mp, 0, q, ip_ring)) != NULL) {
15442 				if (curr_sqp == NULL) {
15443 					curr_sqp = GET_SQUEUE(mp);
15444 					ASSERT(cnt == 0);
15445 					cnt++;
15446 					head = tail = mp;
15447 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15448 					ASSERT(tail != NULL);
15449 					cnt++;
15450 					tail->b_next = mp;
15451 					tail = mp;
15452 				} else {
15453 					/*
15454 					 * A different squeue. Send the
15455 					 * chain for the previous squeue on
15456 					 * its way. This shouldn't happen
15457 					 * often unless interrupt binding
15458 					 * changes.
15459 					 */
15460 					IP_STAT(ipst, ip_input_multi_squeue);
15461 					SQUEUE_ENTER(curr_sqp, head,
15462 					    tail, cnt, SQ_PROCESS, tag);
15463 					curr_sqp = GET_SQUEUE(mp);
15464 					head = mp;
15465 					tail = mp;
15466 					cnt = 1;
15467 				}
15468 			}
15469 			continue;
15470 		case IPPROTO_UDP:
15471 			ASSERT(first_mp == mp);
15472 			ip_udp_input(q, mp, ipha, ire, ill);
15473 			continue;
15474 		case IPPROTO_SCTP:
15475 			ASSERT(first_mp == mp);
15476 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15477 			    q, dst);
15478 			/* ire has been released by ip_sctp_input */
15479 			ire = NULL;
15480 			continue;
15481 		default:
15482 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15483 			continue;
15484 		}
15485 	}
15486 
15487 	if (ire != NULL)
15488 		ire_refrele(ire);
15489 
15490 	if (head != NULL)
15491 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15492 
15493 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15494 	    "ip_input_end: q %p (%S)", q, "end");
15495 #undef  rptr
15496 }
15497 
15498 /*
15499  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15500  * a chain of packets in the poll mode. The packets have gone through the
15501  * data link processing but not IP processing. For performance and latency
15502  * reasons, the squeue wants to process the chain in line instead of feeding
15503  * it back via ip_input path.
15504  *
15505  * So this is a light weight function which checks to see if the packets
15506  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15507  * but we still do the paranoid check) meant for local machine and we don't
15508  * have labels etc enabled. Packets that meet the criterion are returned to
15509  * the squeue and processed inline while the rest go via ip_input path.
15510  */
15511 /*ARGSUSED*/
15512 mblk_t *
15513 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15514     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15515 {
15516 	mblk_t 		*mp;
15517 	ipaddr_t	dst = NULL;
15518 	ipaddr_t	prev_dst;
15519 	ire_t		*ire = NULL;
15520 	ipha_t		*ipha;
15521 	uint_t		pkt_len;
15522 	ssize_t		len;
15523 	uint_t		opt_len;
15524 	queue_t		*q = ill->ill_rq;
15525 	squeue_t	*curr_sqp;
15526 	mblk_t 		*ahead = NULL;	/* Accepted head */
15527 	mblk_t		*atail = NULL;	/* Accepted tail */
15528 	uint_t		acnt = 0;	/* Accepted count */
15529 	mblk_t		*utail = NULL;	/* Unaccepted head */
15530 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15531 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15532 	ip_stack_t	*ipst = ill->ill_ipst;
15533 
15534 	*cnt = 0;
15535 
15536 	ASSERT(ill != NULL);
15537 	ASSERT(ip_ring != NULL);
15538 
15539 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15540 
15541 #define	rptr	((uchar_t *)ipha)
15542 
15543 	while (mp_chain != NULL) {
15544 		mp = mp_chain;
15545 		mp_chain = mp_chain->b_next;
15546 		mp->b_next = NULL;
15547 
15548 		/*
15549 		 * We do ire caching from one iteration to
15550 		 * another. In the event the packet chain contains
15551 		 * all packets from the same dst, this caching saves
15552 		 * an ire_cache_lookup for each of the succeeding
15553 		 * packets in a packet chain.
15554 		 */
15555 		prev_dst = dst;
15556 
15557 		ipha = (ipha_t *)mp->b_rptr;
15558 		len = mp->b_wptr - rptr;
15559 
15560 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15561 
15562 		/*
15563 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15564 		 * or doesn't have min len, reject.
15565 		 */
15566 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15567 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15568 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15569 			continue;
15570 		}
15571 
15572 		pkt_len = ntohs(ipha->ipha_length);
15573 		if (len != pkt_len) {
15574 			if (len > pkt_len) {
15575 				mp->b_wptr = rptr + pkt_len;
15576 			} else {
15577 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15578 				continue;
15579 			}
15580 		}
15581 
15582 		opt_len = ipha->ipha_version_and_hdr_length -
15583 		    IP_SIMPLE_HDR_VERSION;
15584 		dst = ipha->ipha_dst;
15585 
15586 		/* IP version bad or there are IP options */
15587 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15588 		    mp, &ipha, &dst, ipst)))
15589 			continue;
15590 
15591 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15592 		    (ipst->ips_ip_cgtp_filter &&
15593 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15594 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15595 			continue;
15596 		}
15597 
15598 		/*
15599 		 * Reuse the cached ire only if the ipha_dst of the previous
15600 		 * packet is the same as the current packet AND it is not
15601 		 * INADDR_ANY.
15602 		 */
15603 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15604 		    (ire != NULL)) {
15605 			ire_refrele(ire);
15606 			ire = NULL;
15607 		}
15608 
15609 		if (ire == NULL)
15610 			ire = ire_cache_lookup_simple(dst, ipst);
15611 
15612 		/*
15613 		 * Unless forwarding is enabled, dont call
15614 		 * ip_fast_forward(). Incoming packet is for forwarding
15615 		 */
15616 		if ((ill->ill_flags & ILLF_ROUTER) &&
15617 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15618 
15619 			DTRACE_PROBE4(ip4__physical__in__start,
15620 			    ill_t *, ill, ill_t *, NULL,
15621 			    ipha_t *, ipha, mblk_t *, mp);
15622 
15623 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15624 			    ipst->ips_ipv4firewall_physical_in,
15625 			    ill, NULL, ipha, mp, mp, 0, ipst);
15626 
15627 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15628 
15629 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15630 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15631 			    pkt_len);
15632 
15633 			if (mp != NULL)
15634 				ire = ip_fast_forward(ire, dst, ill, mp);
15635 			continue;
15636 		}
15637 
15638 		/* incoming packet is for local consumption */
15639 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15640 			goto local_accept;
15641 
15642 		/*
15643 		 * Disable ire caching for anything more complex
15644 		 * than the simple fast path case we checked for above.
15645 		 */
15646 		if (ire != NULL) {
15647 			ire_refrele(ire);
15648 			ire = NULL;
15649 		}
15650 
15651 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15652 		    ipst);
15653 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15654 		    ire->ire_stq != NULL) {
15655 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15656 			if (ire != NULL) {
15657 				ire_refrele(ire);
15658 				ire = NULL;
15659 			}
15660 			continue;
15661 		}
15662 
15663 local_accept:
15664 
15665 		if (ire->ire_rfq != q) {
15666 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15667 			if (ire != NULL) {
15668 				ire_refrele(ire);
15669 				ire = NULL;
15670 			}
15671 			continue;
15672 		}
15673 
15674 		/*
15675 		 * The event for packets being received from a 'physical'
15676 		 * interface is placed after validation of the source and/or
15677 		 * destination address as being local so that packets can be
15678 		 * redirected to loopback addresses using ipnat.
15679 		 */
15680 		DTRACE_PROBE4(ip4__physical__in__start,
15681 		    ill_t *, ill, ill_t *, NULL,
15682 		    ipha_t *, ipha, mblk_t *, mp);
15683 
15684 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15685 		    ipst->ips_ipv4firewall_physical_in,
15686 		    ill, NULL, ipha, mp, mp, 0, ipst);
15687 
15688 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15689 
15690 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15691 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15692 
15693 		if (mp != NULL &&
15694 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15695 		    0, q, ip_ring)) != NULL) {
15696 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15697 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15698 			} else {
15699 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15700 				    SQ_FILL, SQTAG_IP_INPUT);
15701 			}
15702 		}
15703 	}
15704 
15705 	if (ire != NULL)
15706 		ire_refrele(ire);
15707 
15708 	if (uhead != NULL)
15709 		ip_input(ill, ip_ring, uhead, NULL);
15710 
15711 	if (ahead != NULL) {
15712 		*last = atail;
15713 		*cnt = acnt;
15714 		return (ahead);
15715 	}
15716 
15717 	return (NULL);
15718 #undef  rptr
15719 }
15720 
15721 static void
15722 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15723     t_uscalar_t err)
15724 {
15725 	if (dl_err == DL_SYSERR) {
15726 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15727 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15728 		    ill->ill_name, dl_primstr(prim), err);
15729 		return;
15730 	}
15731 
15732 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15733 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15734 	    dl_errstr(dl_err));
15735 }
15736 
15737 /*
15738  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15739  * than DL_UNITDATA_IND messages. If we need to process this message
15740  * exclusively, we call qwriter_ip, in which case we also need to call
15741  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15742  */
15743 void
15744 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15745 {
15746 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15747 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15748 	ill_t		*ill = q->q_ptr;
15749 	t_uscalar_t	prim = dloa->dl_primitive;
15750 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15751 
15752 	ip1dbg(("ip_rput_dlpi"));
15753 
15754 	/*
15755 	 * If we received an ACK but didn't send a request for it, then it
15756 	 * can't be part of any pending operation; discard up-front.
15757 	 */
15758 	switch (prim) {
15759 	case DL_ERROR_ACK:
15760 		reqprim = dlea->dl_error_primitive;
15761 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15762 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15763 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15764 		    dlea->dl_unix_errno));
15765 		break;
15766 	case DL_OK_ACK:
15767 		reqprim = dloa->dl_correct_primitive;
15768 		break;
15769 	case DL_INFO_ACK:
15770 		reqprim = DL_INFO_REQ;
15771 		break;
15772 	case DL_BIND_ACK:
15773 		reqprim = DL_BIND_REQ;
15774 		break;
15775 	case DL_PHYS_ADDR_ACK:
15776 		reqprim = DL_PHYS_ADDR_REQ;
15777 		break;
15778 	case DL_NOTIFY_ACK:
15779 		reqprim = DL_NOTIFY_REQ;
15780 		break;
15781 	case DL_CONTROL_ACK:
15782 		reqprim = DL_CONTROL_REQ;
15783 		break;
15784 	case DL_CAPABILITY_ACK:
15785 		reqprim = DL_CAPABILITY_REQ;
15786 		break;
15787 	}
15788 
15789 	if (prim != DL_NOTIFY_IND) {
15790 		if (reqprim == DL_PRIM_INVAL ||
15791 		    !ill_dlpi_pending(ill, reqprim)) {
15792 			/* Not a DLPI message we support or expected */
15793 			freemsg(mp);
15794 			return;
15795 		}
15796 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15797 		    dl_primstr(reqprim)));
15798 	}
15799 
15800 	switch (reqprim) {
15801 	case DL_UNBIND_REQ:
15802 		/*
15803 		 * NOTE: we mark the unbind as complete even if we got a
15804 		 * DL_ERROR_ACK, since there's not much else we can do.
15805 		 */
15806 		mutex_enter(&ill->ill_lock);
15807 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15808 		cv_signal(&ill->ill_cv);
15809 		mutex_exit(&ill->ill_lock);
15810 		break;
15811 
15812 	case DL_ENABMULTI_REQ:
15813 		if (prim == DL_OK_ACK) {
15814 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15815 				ill->ill_dlpi_multicast_state = IDS_OK;
15816 		}
15817 		break;
15818 	}
15819 
15820 	/*
15821 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15822 	 * need to become writer to continue to process it.  Because an
15823 	 * exclusive operation doesn't complete until replies to all queued
15824 	 * DLPI messages have been received, we know we're in the middle of an
15825 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15826 	 *
15827 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15828 	 * Since this is on the ill stream we unconditionally bump up the
15829 	 * refcount without doing ILL_CAN_LOOKUP().
15830 	 */
15831 	ill_refhold(ill);
15832 	if (prim == DL_NOTIFY_IND)
15833 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15834 	else
15835 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15836 }
15837 
15838 /*
15839  * Handling of DLPI messages that require exclusive access to the ipsq.
15840  *
15841  * Need to do ill_pending_mp_release on ioctl completion, which could
15842  * happen here. (along with mi_copy_done)
15843  */
15844 /* ARGSUSED */
15845 static void
15846 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15847 {
15848 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15849 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15850 	int		err = 0;
15851 	ill_t		*ill;
15852 	ipif_t		*ipif = NULL;
15853 	mblk_t		*mp1 = NULL;
15854 	conn_t		*connp = NULL;
15855 	t_uscalar_t	paddrreq;
15856 	mblk_t		*mp_hw;
15857 	boolean_t	success;
15858 	boolean_t	ioctl_aborted = B_FALSE;
15859 	boolean_t	log = B_TRUE;
15860 	ip_stack_t		*ipst;
15861 
15862 	ip1dbg(("ip_rput_dlpi_writer .."));
15863 	ill = (ill_t *)q->q_ptr;
15864 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15865 	ASSERT(IAM_WRITER_ILL(ill));
15866 
15867 	ipst = ill->ill_ipst;
15868 
15869 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15870 	/*
15871 	 * The current ioctl could have been aborted by the user and a new
15872 	 * ioctl to bring up another ill could have started. We could still
15873 	 * get a response from the driver later.
15874 	 */
15875 	if (ipif != NULL && ipif->ipif_ill != ill)
15876 		ioctl_aborted = B_TRUE;
15877 
15878 	switch (dloa->dl_primitive) {
15879 	case DL_ERROR_ACK:
15880 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15881 		    dl_primstr(dlea->dl_error_primitive)));
15882 
15883 		switch (dlea->dl_error_primitive) {
15884 		case DL_DISABMULTI_REQ:
15885 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15886 			break;
15887 		case DL_PROMISCON_REQ:
15888 		case DL_PROMISCOFF_REQ:
15889 		case DL_UNBIND_REQ:
15890 		case DL_ATTACH_REQ:
15891 		case DL_INFO_REQ:
15892 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15893 			break;
15894 		case DL_NOTIFY_REQ:
15895 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15896 			log = B_FALSE;
15897 			break;
15898 		case DL_PHYS_ADDR_REQ:
15899 			/*
15900 			 * For IPv6 only, there are two additional
15901 			 * phys_addr_req's sent to the driver to get the
15902 			 * IPv6 token and lla. This allows IP to acquire
15903 			 * the hardware address format for a given interface
15904 			 * without having built in knowledge of the hardware
15905 			 * address. ill_phys_addr_pend keeps track of the last
15906 			 * DL_PAR sent so we know which response we are
15907 			 * dealing with. ill_dlpi_done will update
15908 			 * ill_phys_addr_pend when it sends the next req.
15909 			 * We don't complete the IOCTL until all three DL_PARs
15910 			 * have been attempted, so set *_len to 0 and break.
15911 			 */
15912 			paddrreq = ill->ill_phys_addr_pend;
15913 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15914 			if (paddrreq == DL_IPV6_TOKEN) {
15915 				ill->ill_token_length = 0;
15916 				log = B_FALSE;
15917 				break;
15918 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15919 				ill->ill_nd_lla_len = 0;
15920 				log = B_FALSE;
15921 				break;
15922 			}
15923 			/*
15924 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15925 			 * We presumably have an IOCTL hanging out waiting
15926 			 * for completion. Find it and complete the IOCTL
15927 			 * with the error noted.
15928 			 * However, ill_dl_phys was called on an ill queue
15929 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15930 			 * set. But the ioctl is known to be pending on ill_wq.
15931 			 */
15932 			if (!ill->ill_ifname_pending)
15933 				break;
15934 			ill->ill_ifname_pending = 0;
15935 			if (!ioctl_aborted)
15936 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15937 			if (mp1 != NULL) {
15938 				/*
15939 				 * This operation (SIOCSLIFNAME) must have
15940 				 * happened on the ill. Assert there is no conn
15941 				 */
15942 				ASSERT(connp == NULL);
15943 				q = ill->ill_wq;
15944 			}
15945 			break;
15946 		case DL_BIND_REQ:
15947 			ill_dlpi_done(ill, DL_BIND_REQ);
15948 			if (ill->ill_ifname_pending)
15949 				break;
15950 			/*
15951 			 * Something went wrong with the bind.  We presumably
15952 			 * have an IOCTL hanging out waiting for completion.
15953 			 * Find it, take down the interface that was coming
15954 			 * up, and complete the IOCTL with the error noted.
15955 			 */
15956 			if (!ioctl_aborted)
15957 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15958 			if (mp1 != NULL) {
15959 				/*
15960 				 * This might be a result of a DL_NOTE_REPLUMB
15961 				 * notification. In that case, connp is NULL.
15962 				 */
15963 				if (connp != NULL)
15964 					q = CONNP_TO_WQ(connp);
15965 
15966 				(void) ipif_down(ipif, NULL, NULL);
15967 				/* error is set below the switch */
15968 			}
15969 			break;
15970 		case DL_ENABMULTI_REQ:
15971 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15972 
15973 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15974 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15975 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15976 				ipif_t *ipif;
15977 
15978 				printf("ip: joining multicasts failed (%d)"
15979 				    " on %s - will use link layer "
15980 				    "broadcasts for multicast\n",
15981 				    dlea->dl_errno, ill->ill_name);
15982 
15983 				/*
15984 				 * Set up the multicast mapping alone.
15985 				 * writer, so ok to access ill->ill_ipif
15986 				 * without any lock.
15987 				 */
15988 				ipif = ill->ill_ipif;
15989 				mutex_enter(&ill->ill_phyint->phyint_lock);
15990 				ill->ill_phyint->phyint_flags |=
15991 				    PHYI_MULTI_BCAST;
15992 				mutex_exit(&ill->ill_phyint->phyint_lock);
15993 
15994 				if (!ill->ill_isv6) {
15995 					(void) ipif_arp_setup_multicast(ipif,
15996 					    NULL);
15997 				} else {
15998 					(void) ipif_ndp_setup_multicast(ipif,
15999 					    NULL);
16000 				}
16001 			}
16002 			freemsg(mp);	/* Don't want to pass this up */
16003 			return;
16004 		case DL_CONTROL_REQ:
16005 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
16006 			    "DL_CONTROL_REQ\n"));
16007 			ill_dlpi_done(ill, dlea->dl_error_primitive);
16008 			freemsg(mp);
16009 			return;
16010 		case DL_CAPABILITY_REQ:
16011 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
16012 			    "DL_CAPABILITY REQ\n"));
16013 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
16014 				ill->ill_dlpi_capab_state = IDCS_FAILED;
16015 			ill_capability_done(ill);
16016 			freemsg(mp);
16017 			return;
16018 		}
16019 		/*
16020 		 * Note the error for IOCTL completion (mp1 is set when
16021 		 * ready to complete ioctl). If ill_ifname_pending_err is
16022 		 * set, an error occured during plumbing (ill_ifname_pending),
16023 		 * so we want to report that error.
16024 		 *
16025 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
16026 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
16027 		 * expected to get errack'd if the driver doesn't support
16028 		 * these flags (e.g. ethernet). log will be set to B_FALSE
16029 		 * if these error conditions are encountered.
16030 		 */
16031 		if (mp1 != NULL) {
16032 			if (ill->ill_ifname_pending_err != 0)  {
16033 				err = ill->ill_ifname_pending_err;
16034 				ill->ill_ifname_pending_err = 0;
16035 			} else {
16036 				err = dlea->dl_unix_errno ?
16037 				    dlea->dl_unix_errno : ENXIO;
16038 			}
16039 		/*
16040 		 * If we're plumbing an interface and an error hasn't already
16041 		 * been saved, set ill_ifname_pending_err to the error passed
16042 		 * up. Ignore the error if log is B_FALSE (see comment above).
16043 		 */
16044 		} else if (log && ill->ill_ifname_pending &&
16045 		    ill->ill_ifname_pending_err == 0) {
16046 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
16047 			    dlea->dl_unix_errno : ENXIO;
16048 		}
16049 
16050 		if (log)
16051 			ip_dlpi_error(ill, dlea->dl_error_primitive,
16052 			    dlea->dl_errno, dlea->dl_unix_errno);
16053 		break;
16054 	case DL_CAPABILITY_ACK:
16055 		ill_capability_ack(ill, mp);
16056 		/*
16057 		 * The message has been handed off to ill_capability_ack
16058 		 * and must not be freed below
16059 		 */
16060 		mp = NULL;
16061 		break;
16062 
16063 	case DL_CONTROL_ACK:
16064 		/* We treat all of these as "fire and forget" */
16065 		ill_dlpi_done(ill, DL_CONTROL_REQ);
16066 		break;
16067 	case DL_INFO_ACK:
16068 		/* Call a routine to handle this one. */
16069 		ill_dlpi_done(ill, DL_INFO_REQ);
16070 		ip_ll_subnet_defaults(ill, mp);
16071 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16072 		return;
16073 	case DL_BIND_ACK:
16074 		/*
16075 		 * We should have an IOCTL waiting on this unless
16076 		 * sent by ill_dl_phys, in which case just return
16077 		 */
16078 		ill_dlpi_done(ill, DL_BIND_REQ);
16079 		if (ill->ill_ifname_pending)
16080 			break;
16081 
16082 		if (!ioctl_aborted)
16083 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16084 		if (mp1 == NULL)
16085 			break;
16086 		/*
16087 		 * mp1 was added by ill_dl_up(). if that is a result of
16088 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
16089 		 */
16090 		if (connp != NULL)
16091 			q = CONNP_TO_WQ(connp);
16092 
16093 		/*
16094 		 * We are exclusive. So nothing can change even after
16095 		 * we get the pending mp. If need be we can put it back
16096 		 * and restart, as in calling ipif_arp_up()  below.
16097 		 */
16098 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16099 
16100 		mutex_enter(&ill->ill_lock);
16101 		ill->ill_dl_up = 1;
16102 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16103 		mutex_exit(&ill->ill_lock);
16104 
16105 		/*
16106 		 * Now bring up the resolver; when that is complete, we'll
16107 		 * create IREs.  Note that we intentionally mirror what
16108 		 * ipif_up() would have done, because we got here by way of
16109 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16110 		 */
16111 		if (ill->ill_isv6) {
16112 			if (ill->ill_flags & ILLF_XRESOLV) {
16113 				if (connp != NULL)
16114 					mutex_enter(&connp->conn_lock);
16115 				mutex_enter(&ill->ill_lock);
16116 				success = ipsq_pending_mp_add(connp, ipif, q,
16117 				    mp1, 0);
16118 				mutex_exit(&ill->ill_lock);
16119 				if (connp != NULL)
16120 					mutex_exit(&connp->conn_lock);
16121 				if (success) {
16122 					err = ipif_resolver_up(ipif,
16123 					    Res_act_initial);
16124 					if (err == EINPROGRESS) {
16125 						freemsg(mp);
16126 						return;
16127 					}
16128 					ASSERT(err != 0);
16129 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16130 					ASSERT(mp1 != NULL);
16131 				} else {
16132 					/* conn has started closing */
16133 					err = EINTR;
16134 				}
16135 			} else { /* Non XRESOLV interface */
16136 				(void) ipif_resolver_up(ipif, Res_act_initial);
16137 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16138 					err = ipif_up_done_v6(ipif);
16139 			}
16140 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16141 			/*
16142 			 * ARP and other v4 external resolvers.
16143 			 * Leave the pending mblk intact so that
16144 			 * the ioctl completes in ip_rput().
16145 			 */
16146 			if (connp != NULL)
16147 				mutex_enter(&connp->conn_lock);
16148 			mutex_enter(&ill->ill_lock);
16149 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16150 			mutex_exit(&ill->ill_lock);
16151 			if (connp != NULL)
16152 				mutex_exit(&connp->conn_lock);
16153 			if (success) {
16154 				err = ipif_resolver_up(ipif, Res_act_initial);
16155 				if (err == EINPROGRESS) {
16156 					freemsg(mp);
16157 					return;
16158 				}
16159 				ASSERT(err != 0);
16160 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16161 			} else {
16162 				/* The conn has started closing */
16163 				err = EINTR;
16164 			}
16165 		} else {
16166 			/*
16167 			 * This one is complete. Reply to pending ioctl.
16168 			 */
16169 			(void) ipif_resolver_up(ipif, Res_act_initial);
16170 			err = ipif_up_done(ipif);
16171 		}
16172 
16173 		if ((err == 0) && (ill->ill_up_ipifs)) {
16174 			err = ill_up_ipifs(ill, q, mp1);
16175 			if (err == EINPROGRESS) {
16176 				freemsg(mp);
16177 				return;
16178 			}
16179 		}
16180 
16181 		/*
16182 		 * If we have a moved ipif to bring up, and everything has
16183 		 * succeeded to this point, bring it up on the IPMP ill.
16184 		 * Otherwise, leave it down -- the admin can try to bring it
16185 		 * up by hand if need be.
16186 		 */
16187 		if (ill->ill_move_ipif != NULL) {
16188 			if (err != 0) {
16189 				ill->ill_move_ipif = NULL;
16190 			} else {
16191 				ipif = ill->ill_move_ipif;
16192 				ill->ill_move_ipif = NULL;
16193 				err = ipif_up(ipif, q, mp1);
16194 				if (err == EINPROGRESS) {
16195 					freemsg(mp);
16196 					return;
16197 				}
16198 			}
16199 		}
16200 		break;
16201 
16202 	case DL_NOTIFY_IND: {
16203 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16204 		ire_t *ire;
16205 		uint_t orig_mtu;
16206 		boolean_t need_ire_walk_v4 = B_FALSE;
16207 		boolean_t need_ire_walk_v6 = B_FALSE;
16208 
16209 		switch (notify->dl_notification) {
16210 		case DL_NOTE_PHYS_ADDR:
16211 			err = ill_set_phys_addr(ill, mp);
16212 			break;
16213 
16214 		case DL_NOTE_REPLUMB:
16215 			/*
16216 			 * Directly return after calling ill_replumb().
16217 			 * Note that we should not free mp as it is reused
16218 			 * in the ill_replumb() function.
16219 			 */
16220 			err = ill_replumb(ill, mp);
16221 			return;
16222 
16223 		case DL_NOTE_FASTPATH_FLUSH:
16224 			ill_fastpath_flush(ill);
16225 			break;
16226 
16227 		case DL_NOTE_SDU_SIZE:
16228 			/*
16229 			 * Change the MTU size of the interface, of all
16230 			 * attached ipif's, and of all relevant ire's.  The
16231 			 * new value's a uint32_t at notify->dl_data.
16232 			 * Mtu change Vs. new ire creation - protocol below.
16233 			 *
16234 			 * a Mark the ipif as IPIF_CHANGING.
16235 			 * b Set the new mtu in the ipif.
16236 			 * c Change the ire_max_frag on all affected ires
16237 			 * d Unmark the IPIF_CHANGING
16238 			 *
16239 			 * To see how the protocol works, assume an interface
16240 			 * route is also being added simultaneously by
16241 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16242 			 * the ire. If the ire is created before step a,
16243 			 * it will be cleaned up by step c. If the ire is
16244 			 * created after step d, it will see the new value of
16245 			 * ipif_mtu. Any attempt to create the ire between
16246 			 * steps a to d will fail because of the IPIF_CHANGING
16247 			 * flag. Note that ire_create() is passed a pointer to
16248 			 * the ipif_mtu, and not the value. During ire_add
16249 			 * under the bucket lock, the ire_max_frag of the
16250 			 * new ire being created is set from the ipif/ire from
16251 			 * which it is being derived.
16252 			 */
16253 			mutex_enter(&ill->ill_lock);
16254 
16255 			orig_mtu = ill->ill_max_mtu;
16256 			ill->ill_max_frag = (uint_t)notify->dl_data;
16257 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16258 
16259 			/*
16260 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16261 			 * clamp ill_max_mtu at it.
16262 			 */
16263 			if (ill->ill_user_mtu != 0 &&
16264 			    ill->ill_user_mtu < ill->ill_max_mtu)
16265 				ill->ill_max_mtu = ill->ill_user_mtu;
16266 
16267 			/*
16268 			 * If the MTU is unchanged, we're done.
16269 			 */
16270 			if (orig_mtu == ill->ill_max_mtu) {
16271 				mutex_exit(&ill->ill_lock);
16272 				break;
16273 			}
16274 
16275 			if (ill->ill_isv6) {
16276 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16277 					ill->ill_max_mtu = IPV6_MIN_MTU;
16278 			} else {
16279 				if (ill->ill_max_mtu < IP_MIN_MTU)
16280 					ill->ill_max_mtu = IP_MIN_MTU;
16281 			}
16282 			for (ipif = ill->ill_ipif; ipif != NULL;
16283 			    ipif = ipif->ipif_next) {
16284 				/*
16285 				 * Don't override the mtu if the user
16286 				 * has explicitly set it.
16287 				 */
16288 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16289 					continue;
16290 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16291 				if (ipif->ipif_isv6)
16292 					ire = ipif_to_ire_v6(ipif);
16293 				else
16294 					ire = ipif_to_ire(ipif);
16295 				if (ire != NULL) {
16296 					ire->ire_max_frag = ipif->ipif_mtu;
16297 					ire_refrele(ire);
16298 				}
16299 				if (ipif->ipif_flags & IPIF_UP) {
16300 					if (ill->ill_isv6)
16301 						need_ire_walk_v6 = B_TRUE;
16302 					else
16303 						need_ire_walk_v4 = B_TRUE;
16304 				}
16305 			}
16306 			mutex_exit(&ill->ill_lock);
16307 			if (need_ire_walk_v4)
16308 				ire_walk_v4(ill_mtu_change, (char *)ill,
16309 				    ALL_ZONES, ipst);
16310 			if (need_ire_walk_v6)
16311 				ire_walk_v6(ill_mtu_change, (char *)ill,
16312 				    ALL_ZONES, ipst);
16313 
16314 			/*
16315 			 * Refresh IPMP meta-interface MTU if necessary.
16316 			 */
16317 			if (IS_UNDER_IPMP(ill))
16318 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16319 			break;
16320 
16321 		case DL_NOTE_LINK_UP:
16322 		case DL_NOTE_LINK_DOWN: {
16323 			/*
16324 			 * We are writer. ill / phyint / ipsq assocs stable.
16325 			 * The RUNNING flag reflects the state of the link.
16326 			 */
16327 			phyint_t *phyint = ill->ill_phyint;
16328 			uint64_t new_phyint_flags;
16329 			boolean_t changed = B_FALSE;
16330 			boolean_t went_up;
16331 
16332 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16333 			mutex_enter(&phyint->phyint_lock);
16334 
16335 			new_phyint_flags = went_up ?
16336 			    phyint->phyint_flags | PHYI_RUNNING :
16337 			    phyint->phyint_flags & ~PHYI_RUNNING;
16338 
16339 			if (IS_IPMP(ill)) {
16340 				new_phyint_flags = went_up ?
16341 				    new_phyint_flags & ~PHYI_FAILED :
16342 				    new_phyint_flags | PHYI_FAILED;
16343 			}
16344 
16345 			if (new_phyint_flags != phyint->phyint_flags) {
16346 				phyint->phyint_flags = new_phyint_flags;
16347 				changed = B_TRUE;
16348 			}
16349 			mutex_exit(&phyint->phyint_lock);
16350 			/*
16351 			 * ill_restart_dad handles the DAD restart and routing
16352 			 * socket notification logic.
16353 			 */
16354 			if (changed) {
16355 				ill_restart_dad(phyint->phyint_illv4, went_up);
16356 				ill_restart_dad(phyint->phyint_illv6, went_up);
16357 			}
16358 			break;
16359 		}
16360 		case DL_NOTE_PROMISC_ON_PHYS: {
16361 			phyint_t *phyint = ill->ill_phyint;
16362 
16363 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16364 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16365 			mutex_enter(&phyint->phyint_lock);
16366 			phyint->phyint_flags |= PHYI_PROMISC;
16367 			mutex_exit(&phyint->phyint_lock);
16368 			break;
16369 		}
16370 		case DL_NOTE_PROMISC_OFF_PHYS: {
16371 			phyint_t *phyint = ill->ill_phyint;
16372 
16373 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16374 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16375 			mutex_enter(&phyint->phyint_lock);
16376 			phyint->phyint_flags &= ~PHYI_PROMISC;
16377 			mutex_exit(&phyint->phyint_lock);
16378 			break;
16379 		}
16380 		case DL_NOTE_CAPAB_RENEG:
16381 			/*
16382 			 * Something changed on the driver side.
16383 			 * It wants us to renegotiate the capabilities
16384 			 * on this ill. One possible cause is the aggregation
16385 			 * interface under us where a port got added or
16386 			 * went away.
16387 			 *
16388 			 * If the capability negotiation is already done
16389 			 * or is in progress, reset the capabilities and
16390 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16391 			 * so that when the ack comes back, we can start
16392 			 * the renegotiation process.
16393 			 *
16394 			 * Note that if ill_capab_reneg is already B_TRUE
16395 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16396 			 * the capability resetting request has been sent
16397 			 * and the renegotiation has not been started yet;
16398 			 * nothing needs to be done in this case.
16399 			 */
16400 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16401 			ill_capability_reset(ill, B_TRUE);
16402 			ipsq_current_finish(ipsq);
16403 			break;
16404 		default:
16405 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16406 			    "type 0x%x for DL_NOTIFY_IND\n",
16407 			    notify->dl_notification));
16408 			break;
16409 		}
16410 
16411 		/*
16412 		 * As this is an asynchronous operation, we
16413 		 * should not call ill_dlpi_done
16414 		 */
16415 		break;
16416 	}
16417 	case DL_NOTIFY_ACK: {
16418 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16419 
16420 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16421 			ill->ill_note_link = 1;
16422 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16423 		break;
16424 	}
16425 	case DL_PHYS_ADDR_ACK: {
16426 		/*
16427 		 * As part of plumbing the interface via SIOCSLIFNAME,
16428 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16429 		 * whose answers we receive here.  As each answer is received,
16430 		 * we call ill_dlpi_done() to dispatch the next request as
16431 		 * we're processing the current one.  Once all answers have
16432 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16433 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16434 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16435 		 * available, but we know the ioctl is pending on ill_wq.)
16436 		 */
16437 		uint_t	paddrlen, paddroff;
16438 
16439 		paddrreq = ill->ill_phys_addr_pend;
16440 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16441 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16442 
16443 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16444 		if (paddrreq == DL_IPV6_TOKEN) {
16445 			/*
16446 			 * bcopy to low-order bits of ill_token
16447 			 *
16448 			 * XXX Temporary hack - currently, all known tokens
16449 			 * are 64 bits, so I'll cheat for the moment.
16450 			 */
16451 			bcopy(mp->b_rptr + paddroff,
16452 			    &ill->ill_token.s6_addr32[2], paddrlen);
16453 			ill->ill_token_length = paddrlen;
16454 			break;
16455 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16456 			ASSERT(ill->ill_nd_lla_mp == NULL);
16457 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16458 			mp = NULL;
16459 			break;
16460 		}
16461 
16462 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16463 		ASSERT(ill->ill_phys_addr_mp == NULL);
16464 		if (!ill->ill_ifname_pending)
16465 			break;
16466 		ill->ill_ifname_pending = 0;
16467 		if (!ioctl_aborted)
16468 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16469 		if (mp1 != NULL) {
16470 			ASSERT(connp == NULL);
16471 			q = ill->ill_wq;
16472 		}
16473 		/*
16474 		 * If any error acks received during the plumbing sequence,
16475 		 * ill_ifname_pending_err will be set. Break out and send up
16476 		 * the error to the pending ioctl.
16477 		 */
16478 		if (ill->ill_ifname_pending_err != 0) {
16479 			err = ill->ill_ifname_pending_err;
16480 			ill->ill_ifname_pending_err = 0;
16481 			break;
16482 		}
16483 
16484 		ill->ill_phys_addr_mp = mp;
16485 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16486 		mp = NULL;
16487 
16488 		/*
16489 		 * If paddrlen is zero, the DLPI provider doesn't support
16490 		 * physical addresses.  The other two tests were historical
16491 		 * workarounds for bugs in our former PPP implementation, but
16492 		 * now other things have grown dependencies on them -- e.g.,
16493 		 * the tun module specifies a dl_addr_length of zero in its
16494 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16495 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16496 		 * but only after careful testing ensures that all dependent
16497 		 * broken DLPI providers have been fixed.
16498 		 */
16499 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16500 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16501 			ill->ill_phys_addr = NULL;
16502 		} else if (paddrlen != ill->ill_phys_addr_length) {
16503 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16504 			    paddrlen, ill->ill_phys_addr_length));
16505 			err = EINVAL;
16506 			break;
16507 		}
16508 
16509 		if (ill->ill_nd_lla_mp == NULL) {
16510 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16511 				err = ENOMEM;
16512 				break;
16513 			}
16514 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16515 		}
16516 
16517 		/*
16518 		 * Set the interface token.  If the zeroth interface address
16519 		 * is unspecified, then set it to the link local address.
16520 		 */
16521 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16522 			(void) ill_setdefaulttoken(ill);
16523 
16524 		ASSERT(ill->ill_ipif->ipif_id == 0);
16525 		if (ipif != NULL &&
16526 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16527 			(void) ipif_setlinklocal(ipif);
16528 		}
16529 		break;
16530 	}
16531 	case DL_OK_ACK:
16532 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16533 		    dl_primstr((int)dloa->dl_correct_primitive),
16534 		    dloa->dl_correct_primitive));
16535 		switch (dloa->dl_correct_primitive) {
16536 		case DL_ENABMULTI_REQ:
16537 		case DL_DISABMULTI_REQ:
16538 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16539 			break;
16540 		case DL_PROMISCON_REQ:
16541 		case DL_PROMISCOFF_REQ:
16542 		case DL_UNBIND_REQ:
16543 		case DL_ATTACH_REQ:
16544 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16545 			break;
16546 		}
16547 		break;
16548 	default:
16549 		break;
16550 	}
16551 
16552 	freemsg(mp);
16553 	if (mp1 == NULL)
16554 		return;
16555 
16556 	/*
16557 	 * The operation must complete without EINPROGRESS since
16558 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16559 	 * the operation will be stuck forever inside the IPSQ.
16560 	 */
16561 	ASSERT(err != EINPROGRESS);
16562 
16563 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16564 	case 0:
16565 		ipsq_current_finish(ipsq);
16566 		break;
16567 
16568 	case SIOCSLIFNAME:
16569 	case IF_UNITSEL: {
16570 		ill_t *ill_other = ILL_OTHER(ill);
16571 
16572 		/*
16573 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16574 		 * ill has a peer which is in an IPMP group, then place ill
16575 		 * into the same group.  One catch: although ifconfig plumbs
16576 		 * the appropriate IPMP meta-interface prior to plumbing this
16577 		 * ill, it is possible for multiple ifconfig applications to
16578 		 * race (or for another application to adjust plumbing), in
16579 		 * which case the IPMP meta-interface we need will be missing.
16580 		 * If so, kick the phyint out of the group.
16581 		 */
16582 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16583 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16584 			ipmp_illgrp_t	*illg;
16585 
16586 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16587 			if (illg == NULL)
16588 				ipmp_phyint_leave_grp(ill->ill_phyint);
16589 			else
16590 				ipmp_ill_join_illgrp(ill, illg);
16591 		}
16592 
16593 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16594 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16595 		else
16596 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16597 		break;
16598 	}
16599 	case SIOCLIFADDIF:
16600 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16601 		break;
16602 
16603 	default:
16604 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16605 		break;
16606 	}
16607 }
16608 
16609 /*
16610  * ip_rput_other is called by ip_rput to handle messages modifying the global
16611  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16612  */
16613 /* ARGSUSED */
16614 void
16615 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16616 {
16617 	ill_t		*ill = q->q_ptr;
16618 	struct iocblk	*iocp;
16619 	mblk_t		*mp1;
16620 	conn_t		*connp = NULL;
16621 
16622 	ip1dbg(("ip_rput_other "));
16623 	if (ipsq != NULL) {
16624 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16625 		ASSERT(ipsq->ipsq_xop ==
16626 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16627 	}
16628 
16629 	switch (mp->b_datap->db_type) {
16630 	case M_ERROR:
16631 	case M_HANGUP:
16632 		/*
16633 		 * The device has a problem.  We force the ILL down.  It can
16634 		 * be brought up again manually using SIOCSIFFLAGS (via
16635 		 * ifconfig or equivalent).
16636 		 */
16637 		ASSERT(ipsq != NULL);
16638 		if (mp->b_rptr < mp->b_wptr)
16639 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16640 		if (ill->ill_error == 0)
16641 			ill->ill_error = ENXIO;
16642 		if (!ill_down_start(q, mp))
16643 			return;
16644 		ipif_all_down_tail(ipsq, q, mp, NULL);
16645 		break;
16646 	case M_IOCACK:
16647 		iocp = (struct iocblk *)mp->b_rptr;
16648 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16649 		switch (iocp->ioc_cmd) {
16650 		case SIOCSTUNPARAM:
16651 		case OSIOCSTUNPARAM:
16652 			ASSERT(ipsq != NULL);
16653 			/*
16654 			 * Finish socket ioctl passed through to tun.
16655 			 * We should have an IOCTL waiting on this.
16656 			 */
16657 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16658 			if (ill->ill_isv6) {
16659 				struct iftun_req *ta;
16660 
16661 				/*
16662 				 * if a source or destination is
16663 				 * being set, try and set the link
16664 				 * local address for the tunnel
16665 				 */
16666 				ta = (struct iftun_req *)mp->b_cont->
16667 				    b_cont->b_rptr;
16668 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16669 					ipif_set_tun_llink(ill, ta);
16670 				}
16671 
16672 			}
16673 			if (mp1 != NULL) {
16674 				/*
16675 				 * Now copy back the b_next/b_prev used by
16676 				 * mi code for the mi_copy* functions.
16677 				 * See ip_sioctl_tunparam() for the reason.
16678 				 * Also protect against missing b_cont.
16679 				 */
16680 				if (mp->b_cont != NULL) {
16681 					mp->b_cont->b_next =
16682 					    mp1->b_cont->b_next;
16683 					mp->b_cont->b_prev =
16684 					    mp1->b_cont->b_prev;
16685 				}
16686 				inet_freemsg(mp1);
16687 				ASSERT(connp != NULL);
16688 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16689 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16690 			} else {
16691 				ASSERT(connp == NULL);
16692 				putnext(q, mp);
16693 			}
16694 			break;
16695 		case SIOCGTUNPARAM:
16696 		case OSIOCGTUNPARAM:
16697 			/*
16698 			 * This is really M_IOCDATA from the tunnel driver.
16699 			 * convert back and complete the ioctl.
16700 			 * We should have an IOCTL waiting on this.
16701 			 */
16702 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16703 			if (mp1) {
16704 				/*
16705 				 * Now copy back the b_next/b_prev used by
16706 				 * mi code for the mi_copy* functions.
16707 				 * See ip_sioctl_tunparam() for the reason.
16708 				 * Also protect against missing b_cont.
16709 				 */
16710 				if (mp->b_cont != NULL) {
16711 					mp->b_cont->b_next =
16712 					    mp1->b_cont->b_next;
16713 					mp->b_cont->b_prev =
16714 					    mp1->b_cont->b_prev;
16715 				}
16716 				inet_freemsg(mp1);
16717 				if (iocp->ioc_error == 0)
16718 					mp->b_datap->db_type = M_IOCDATA;
16719 				ASSERT(connp != NULL);
16720 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16721 				    iocp->ioc_error, COPYOUT, NULL);
16722 			} else {
16723 				ASSERT(connp == NULL);
16724 				putnext(q, mp);
16725 			}
16726 			break;
16727 		default:
16728 			break;
16729 		}
16730 		break;
16731 	case M_IOCNAK:
16732 		iocp = (struct iocblk *)mp->b_rptr;
16733 
16734 		switch (iocp->ioc_cmd) {
16735 			int mode;
16736 
16737 		case DL_IOC_HDR_INFO:
16738 			/*
16739 			 * If this was the first attempt, turn off the
16740 			 * fastpath probing.
16741 			 */
16742 			mutex_enter(&ill->ill_lock);
16743 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16744 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16745 				mutex_exit(&ill->ill_lock);
16746 				ill_fastpath_nack(ill);
16747 				ip1dbg(("ip_rput: DLPI fastpath off on "
16748 				    "interface %s\n",
16749 				    ill->ill_name));
16750 			} else {
16751 				mutex_exit(&ill->ill_lock);
16752 			}
16753 			freemsg(mp);
16754 			break;
16755 			case SIOCSTUNPARAM:
16756 		case OSIOCSTUNPARAM:
16757 			ASSERT(ipsq != NULL);
16758 			/*
16759 			 * Finish socket ioctl passed through to tun
16760 			 * We should have an IOCTL waiting on this.
16761 			 */
16762 			/* FALLTHRU */
16763 		case SIOCGTUNPARAM:
16764 		case OSIOCGTUNPARAM:
16765 			/*
16766 			 * This is really M_IOCDATA from the tunnel driver.
16767 			 * convert back and complete the ioctl.
16768 			 * We should have an IOCTL waiting on this.
16769 			 */
16770 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16771 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16772 				mp1 = ill_pending_mp_get(ill, &connp,
16773 				    iocp->ioc_id);
16774 				mode = COPYOUT;
16775 				ipsq = NULL;
16776 			} else {
16777 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16778 				mode = NO_COPYOUT;
16779 			}
16780 			if (mp1 != NULL) {
16781 				/*
16782 				 * Now copy back the b_next/b_prev used by
16783 				 * mi code for the mi_copy* functions.
16784 				 * See ip_sioctl_tunparam() for the reason.
16785 				 * Also protect against missing b_cont.
16786 				 */
16787 				if (mp->b_cont != NULL) {
16788 					mp->b_cont->b_next =
16789 					    mp1->b_cont->b_next;
16790 					mp->b_cont->b_prev =
16791 					    mp1->b_cont->b_prev;
16792 				}
16793 				inet_freemsg(mp1);
16794 				if (iocp->ioc_error == 0)
16795 					iocp->ioc_error = EINVAL;
16796 				ASSERT(connp != NULL);
16797 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16798 				    iocp->ioc_error, mode, ipsq);
16799 			} else {
16800 				ASSERT(connp == NULL);
16801 				putnext(q, mp);
16802 			}
16803 			break;
16804 		default:
16805 			break;
16806 		}
16807 	default:
16808 		break;
16809 	}
16810 }
16811 
16812 /*
16813  * NOTE : This function does not ire_refrele the ire argument passed in.
16814  *
16815  * IPQoS notes
16816  * IP policy is invoked twice for a forwarded packet, once on the read side
16817  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16818  * enabled. An additional parameter, in_ill, has been added for this purpose.
16819  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16820  * because ip_mroute drops this information.
16821  *
16822  */
16823 void
16824 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16825 {
16826 	uint32_t	old_pkt_len;
16827 	uint32_t	pkt_len;
16828 	queue_t	*q;
16829 	uint32_t	sum;
16830 #define	rptr	((uchar_t *)ipha)
16831 	uint32_t	max_frag;
16832 	uint32_t	ill_index;
16833 	ill_t		*out_ill;
16834 	mib2_ipIfStatsEntry_t *mibptr;
16835 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16836 
16837 	/* Get the ill_index of the incoming ILL */
16838 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16839 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16840 
16841 	/* Initiate Read side IPPF processing */
16842 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16843 		ip_process(IPP_FWD_IN, &mp, ill_index);
16844 		if (mp == NULL) {
16845 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16846 			    "during IPPF processing\n"));
16847 			return;
16848 		}
16849 	}
16850 
16851 	/* Adjust the checksum to reflect the ttl decrement. */
16852 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16853 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16854 
16855 	if (ipha->ipha_ttl-- <= 1) {
16856 		if (ip_csum_hdr(ipha)) {
16857 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16858 			goto drop_pkt;
16859 		}
16860 		/*
16861 		 * Note: ire_stq this will be NULL for multicast
16862 		 * datagrams using the long path through arp (the IRE
16863 		 * is not an IRE_CACHE). This should not cause
16864 		 * problems since we don't generate ICMP errors for
16865 		 * multicast packets.
16866 		 */
16867 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16868 		q = ire->ire_stq;
16869 		if (q != NULL) {
16870 			/* Sent by forwarding path, and router is global zone */
16871 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16872 			    GLOBAL_ZONEID, ipst);
16873 		} else
16874 			freemsg(mp);
16875 		return;
16876 	}
16877 
16878 	/*
16879 	 * Don't forward if the interface is down
16880 	 */
16881 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16882 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16883 		ip2dbg(("ip_rput_forward:interface is down\n"));
16884 		goto drop_pkt;
16885 	}
16886 
16887 	/* Get the ill_index of the outgoing ILL */
16888 	out_ill = ire_to_ill(ire);
16889 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16890 
16891 	DTRACE_PROBE4(ip4__forwarding__start,
16892 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16893 
16894 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16895 	    ipst->ips_ipv4firewall_forwarding,
16896 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16897 
16898 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16899 
16900 	if (mp == NULL)
16901 		return;
16902 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16903 
16904 	if (is_system_labeled()) {
16905 		mblk_t *mp1;
16906 
16907 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16908 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16909 			goto drop_pkt;
16910 		}
16911 		/* Size may have changed */
16912 		mp = mp1;
16913 		ipha = (ipha_t *)mp->b_rptr;
16914 		pkt_len = ntohs(ipha->ipha_length);
16915 	}
16916 
16917 	/* Check if there are options to update */
16918 	if (!IS_SIMPLE_IPH(ipha)) {
16919 		if (ip_csum_hdr(ipha)) {
16920 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16921 			goto drop_pkt;
16922 		}
16923 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16924 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16925 			return;
16926 		}
16927 
16928 		ipha->ipha_hdr_checksum = 0;
16929 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16930 	}
16931 	max_frag = ire->ire_max_frag;
16932 	if (pkt_len > max_frag) {
16933 		/*
16934 		 * It needs fragging on its way out.  We haven't
16935 		 * verified the header checksum yet.  Since we
16936 		 * are going to put a surely good checksum in the
16937 		 * outgoing header, we have to make sure that it
16938 		 * was good coming in.
16939 		 */
16940 		if (ip_csum_hdr(ipha)) {
16941 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16942 			goto drop_pkt;
16943 		}
16944 		/* Initiate Write side IPPF processing */
16945 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16946 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16947 			if (mp == NULL) {
16948 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16949 				    " during IPPF processing\n"));
16950 				return;
16951 			}
16952 		}
16953 		/*
16954 		 * Handle labeled packet resizing.
16955 		 *
16956 		 * If we have added a label, inform ip_wput_frag() of its
16957 		 * effect on the MTU for ICMP messages.
16958 		 */
16959 		if (pkt_len > old_pkt_len) {
16960 			uint32_t secopt_size;
16961 
16962 			secopt_size = pkt_len - old_pkt_len;
16963 			if (secopt_size < max_frag)
16964 				max_frag -= secopt_size;
16965 		}
16966 
16967 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16968 		    GLOBAL_ZONEID, ipst, NULL);
16969 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16970 		return;
16971 	}
16972 
16973 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16974 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16975 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16976 	    ipst->ips_ipv4firewall_physical_out,
16977 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16978 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16979 	if (mp == NULL)
16980 		return;
16981 
16982 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16983 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16984 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16985 	/* ip_xmit_v4 always consumes the packet */
16986 	return;
16987 
16988 drop_pkt:;
16989 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16990 	freemsg(mp);
16991 #undef	rptr
16992 }
16993 
16994 void
16995 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16996 {
16997 	ire_t	*ire;
16998 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16999 
17000 	ASSERT(!ipif->ipif_isv6);
17001 	/*
17002 	 * Find an IRE which matches the destination and the outgoing
17003 	 * queue in the cache table. All we need is an IRE_CACHE which
17004 	 * is pointing at ipif->ipif_ill.
17005 	 */
17006 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
17007 		dst = ipif->ipif_pp_dst_addr;
17008 
17009 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
17010 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
17011 	if (ire == NULL) {
17012 		/*
17013 		 * Mark this packet to make it be delivered to
17014 		 * ip_rput_forward after the new ire has been
17015 		 * created.
17016 		 */
17017 		mp->b_prev = NULL;
17018 		mp->b_next = mp;
17019 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
17020 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
17021 	} else {
17022 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
17023 		IRE_REFRELE(ire);
17024 	}
17025 }
17026 
17027 /* Update any source route, record route or timestamp options */
17028 static int
17029 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
17030 {
17031 	ipoptp_t	opts;
17032 	uchar_t		*opt;
17033 	uint8_t		optval;
17034 	uint8_t		optlen;
17035 	ipaddr_t	dst;
17036 	uint32_t	ts;
17037 	ire_t		*dst_ire = NULL;
17038 	ire_t		*tmp_ire = NULL;
17039 	timestruc_t	now;
17040 
17041 	ip2dbg(("ip_rput_forward_options\n"));
17042 	dst = ipha->ipha_dst;
17043 	for (optval = ipoptp_first(&opts, ipha);
17044 	    optval != IPOPT_EOL;
17045 	    optval = ipoptp_next(&opts)) {
17046 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17047 		opt = opts.ipoptp_cur;
17048 		optlen = opts.ipoptp_len;
17049 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
17050 		    optval, opts.ipoptp_len));
17051 		switch (optval) {
17052 			uint32_t off;
17053 		case IPOPT_SSRR:
17054 		case IPOPT_LSRR:
17055 			/* Check if adminstratively disabled */
17056 			if (!ipst->ips_ip_forward_src_routed) {
17057 				if (ire->ire_stq != NULL) {
17058 					/*
17059 					 * Sent by forwarding path, and router
17060 					 * is global zone
17061 					 */
17062 					icmp_unreachable(ire->ire_stq, mp,
17063 					    ICMP_SOURCE_ROUTE_FAILED,
17064 					    GLOBAL_ZONEID, ipst);
17065 				} else {
17066 					ip0dbg(("ip_rput_forward_options: "
17067 					    "unable to send unreach\n"));
17068 					freemsg(mp);
17069 				}
17070 				return (-1);
17071 			}
17072 
17073 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17074 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17075 			if (dst_ire == NULL) {
17076 				/*
17077 				 * Must be partial since ip_rput_options
17078 				 * checked for strict.
17079 				 */
17080 				break;
17081 			}
17082 			off = opt[IPOPT_OFFSET];
17083 			off--;
17084 		redo_srr:
17085 			if (optlen < IP_ADDR_LEN ||
17086 			    off > optlen - IP_ADDR_LEN) {
17087 				/* End of source route */
17088 				ip1dbg((
17089 				    "ip_rput_forward_options: end of SR\n"));
17090 				ire_refrele(dst_ire);
17091 				break;
17092 			}
17093 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17094 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17095 			    IP_ADDR_LEN);
17096 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17097 			    ntohl(dst)));
17098 
17099 			/*
17100 			 * Check if our address is present more than
17101 			 * once as consecutive hops in source route.
17102 			 */
17103 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17104 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17105 			if (tmp_ire != NULL) {
17106 				ire_refrele(tmp_ire);
17107 				off += IP_ADDR_LEN;
17108 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17109 				goto redo_srr;
17110 			}
17111 			ipha->ipha_dst = dst;
17112 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17113 			ire_refrele(dst_ire);
17114 			break;
17115 		case IPOPT_RR:
17116 			off = opt[IPOPT_OFFSET];
17117 			off--;
17118 			if (optlen < IP_ADDR_LEN ||
17119 			    off > optlen - IP_ADDR_LEN) {
17120 				/* No more room - ignore */
17121 				ip1dbg((
17122 				    "ip_rput_forward_options: end of RR\n"));
17123 				break;
17124 			}
17125 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17126 			    IP_ADDR_LEN);
17127 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17128 			break;
17129 		case IPOPT_TS:
17130 			/* Insert timestamp if there is room */
17131 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17132 			case IPOPT_TS_TSONLY:
17133 				off = IPOPT_TS_TIMELEN;
17134 				break;
17135 			case IPOPT_TS_PRESPEC:
17136 			case IPOPT_TS_PRESPEC_RFC791:
17137 				/* Verify that the address matched */
17138 				off = opt[IPOPT_OFFSET] - 1;
17139 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17140 				dst_ire = ire_ctable_lookup(dst, 0,
17141 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17142 				    MATCH_IRE_TYPE, ipst);
17143 				if (dst_ire == NULL) {
17144 					/* Not for us */
17145 					break;
17146 				}
17147 				ire_refrele(dst_ire);
17148 				/* FALLTHRU */
17149 			case IPOPT_TS_TSANDADDR:
17150 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17151 				break;
17152 			default:
17153 				/*
17154 				 * ip_*put_options should have already
17155 				 * dropped this packet.
17156 				 */
17157 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17158 				    "unknown IT - bug in ip_rput_options?\n");
17159 				return (0);	/* Keep "lint" happy */
17160 			}
17161 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17162 				/* Increase overflow counter */
17163 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17164 				opt[IPOPT_POS_OV_FLG] =
17165 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17166 				    (off << 4));
17167 				break;
17168 			}
17169 			off = opt[IPOPT_OFFSET] - 1;
17170 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17171 			case IPOPT_TS_PRESPEC:
17172 			case IPOPT_TS_PRESPEC_RFC791:
17173 			case IPOPT_TS_TSANDADDR:
17174 				bcopy(&ire->ire_src_addr,
17175 				    (char *)opt + off, IP_ADDR_LEN);
17176 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17177 				/* FALLTHRU */
17178 			case IPOPT_TS_TSONLY:
17179 				off = opt[IPOPT_OFFSET] - 1;
17180 				/* Compute # of milliseconds since midnight */
17181 				gethrestime(&now);
17182 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17183 				    now.tv_nsec / (NANOSEC / MILLISEC);
17184 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17185 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17186 				break;
17187 			}
17188 			break;
17189 		}
17190 	}
17191 	return (0);
17192 }
17193 
17194 /*
17195  * This is called after processing at least one of AH/ESP headers.
17196  *
17197  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17198  * the actual, physical interface on which the packet was received,
17199  * but, when ip_strict_dst_multihoming is set to 1, could be the
17200  * interface which had the ipha_dst configured when the packet went
17201  * through ip_rput. The ill_index corresponding to the recv_ill
17202  * is saved in ipsec_in_rill_index
17203  *
17204  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17205  * cannot assume "ire" points to valid data for any IPv6 cases.
17206  */
17207 void
17208 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17209 {
17210 	mblk_t *mp;
17211 	ipaddr_t dst;
17212 	in6_addr_t *v6dstp;
17213 	ipha_t *ipha;
17214 	ip6_t *ip6h;
17215 	ipsec_in_t *ii;
17216 	boolean_t ill_need_rele = B_FALSE;
17217 	boolean_t rill_need_rele = B_FALSE;
17218 	boolean_t ire_need_rele = B_FALSE;
17219 	netstack_t	*ns;
17220 	ip_stack_t	*ipst;
17221 
17222 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17223 	ASSERT(ii->ipsec_in_ill_index != 0);
17224 	ns = ii->ipsec_in_ns;
17225 	ASSERT(ii->ipsec_in_ns != NULL);
17226 	ipst = ns->netstack_ip;
17227 
17228 	mp = ipsec_mp->b_cont;
17229 	ASSERT(mp != NULL);
17230 
17231 	if (ill == NULL) {
17232 		ASSERT(recv_ill == NULL);
17233 		/*
17234 		 * We need to get the original queue on which ip_rput_local
17235 		 * or ip_rput_data_v6 was called.
17236 		 */
17237 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17238 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17239 		ill_need_rele = B_TRUE;
17240 
17241 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17242 			recv_ill = ill_lookup_on_ifindex(
17243 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17244 			    NULL, NULL, NULL, NULL, ipst);
17245 			rill_need_rele = B_TRUE;
17246 		} else {
17247 			recv_ill = ill;
17248 		}
17249 
17250 		if ((ill == NULL) || (recv_ill == NULL)) {
17251 			ip0dbg(("ip_fanout_proto_again: interface "
17252 			    "disappeared\n"));
17253 			if (ill != NULL)
17254 				ill_refrele(ill);
17255 			if (recv_ill != NULL)
17256 				ill_refrele(recv_ill);
17257 			freemsg(ipsec_mp);
17258 			return;
17259 		}
17260 	}
17261 
17262 	ASSERT(ill != NULL && recv_ill != NULL);
17263 
17264 	if (mp->b_datap->db_type == M_CTL) {
17265 		/*
17266 		 * AH/ESP is returning the ICMP message after
17267 		 * removing their headers. Fanout again till
17268 		 * it gets to the right protocol.
17269 		 */
17270 		if (ii->ipsec_in_v4) {
17271 			icmph_t *icmph;
17272 			int iph_hdr_length;
17273 			int hdr_length;
17274 
17275 			ipha = (ipha_t *)mp->b_rptr;
17276 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17277 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17278 			ipha = (ipha_t *)&icmph[1];
17279 			hdr_length = IPH_HDR_LENGTH(ipha);
17280 			/*
17281 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17282 			 * Reset the type to M_DATA.
17283 			 */
17284 			mp->b_datap->db_type = M_DATA;
17285 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17286 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17287 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17288 		} else {
17289 			icmp6_t *icmp6;
17290 			int hdr_length;
17291 
17292 			ip6h = (ip6_t *)mp->b_rptr;
17293 			/* Don't call hdr_length_v6() unless you have to. */
17294 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17295 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17296 			else
17297 				hdr_length = IPV6_HDR_LEN;
17298 
17299 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17300 			/*
17301 			 * icmp_inbound_error_fanout_v6 may need to do
17302 			 * pullupmsg.  Reset the type to M_DATA.
17303 			 */
17304 			mp->b_datap->db_type = M_DATA;
17305 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17306 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17307 			    ii->ipsec_in_zoneid);
17308 		}
17309 		if (ill_need_rele)
17310 			ill_refrele(ill);
17311 		if (rill_need_rele)
17312 			ill_refrele(recv_ill);
17313 		return;
17314 	}
17315 
17316 	if (ii->ipsec_in_v4) {
17317 		ipha = (ipha_t *)mp->b_rptr;
17318 		dst = ipha->ipha_dst;
17319 		if (CLASSD(dst)) {
17320 			/*
17321 			 * Multicast has to be delivered to all streams.
17322 			 */
17323 			dst = INADDR_BROADCAST;
17324 		}
17325 
17326 		if (ire == NULL) {
17327 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17328 			    msg_getlabel(mp), ipst);
17329 			if (ire == NULL) {
17330 				if (ill_need_rele)
17331 					ill_refrele(ill);
17332 				if (rill_need_rele)
17333 					ill_refrele(recv_ill);
17334 				ip1dbg(("ip_fanout_proto_again: "
17335 				    "IRE not found"));
17336 				freemsg(ipsec_mp);
17337 				return;
17338 			}
17339 			ire_need_rele = B_TRUE;
17340 		}
17341 
17342 		switch (ipha->ipha_protocol) {
17343 		case IPPROTO_UDP:
17344 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17345 			    recv_ill);
17346 			if (ire_need_rele)
17347 				ire_refrele(ire);
17348 			break;
17349 		case IPPROTO_TCP:
17350 			if (!ire_need_rele)
17351 				IRE_REFHOLD(ire);
17352 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17353 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17354 			IRE_REFRELE(ire);
17355 			if (mp != NULL) {
17356 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17357 				    mp, 1, SQ_PROCESS,
17358 				    SQTAG_IP_PROTO_AGAIN);
17359 			}
17360 			break;
17361 		case IPPROTO_SCTP:
17362 			if (!ire_need_rele)
17363 				IRE_REFHOLD(ire);
17364 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17365 			    ipsec_mp, 0, ill->ill_rq, dst);
17366 			break;
17367 		default:
17368 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17369 			    recv_ill, 0);
17370 			if (ire_need_rele)
17371 				ire_refrele(ire);
17372 			break;
17373 		}
17374 	} else {
17375 		uint32_t rput_flags = 0;
17376 
17377 		ip6h = (ip6_t *)mp->b_rptr;
17378 		v6dstp = &ip6h->ip6_dst;
17379 		/*
17380 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17381 		 * address.
17382 		 *
17383 		 * Currently, we don't store that state in the IPSEC_IN
17384 		 * message, and we may need to.
17385 		 */
17386 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17387 		    IP6_IN_LLMCAST : 0);
17388 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17389 		    NULL, NULL);
17390 	}
17391 	if (ill_need_rele)
17392 		ill_refrele(ill);
17393 	if (rill_need_rele)
17394 		ill_refrele(recv_ill);
17395 }
17396 
17397 /*
17398  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17399  * returns 'true' if there are still fragments left on the queue, in
17400  * which case we restart the timer.
17401  */
17402 void
17403 ill_frag_timer(void *arg)
17404 {
17405 	ill_t	*ill = (ill_t *)arg;
17406 	boolean_t frag_pending;
17407 	ip_stack_t	*ipst = ill->ill_ipst;
17408 	time_t	timeout;
17409 
17410 	mutex_enter(&ill->ill_lock);
17411 	ASSERT(!ill->ill_fragtimer_executing);
17412 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17413 		ill->ill_frag_timer_id = 0;
17414 		mutex_exit(&ill->ill_lock);
17415 		return;
17416 	}
17417 	ill->ill_fragtimer_executing = 1;
17418 	mutex_exit(&ill->ill_lock);
17419 
17420 	if (ill->ill_isv6)
17421 		timeout = ipst->ips_ipv6_frag_timeout;
17422 	else
17423 		timeout = ipst->ips_ip_g_frag_timeout;
17424 
17425 	frag_pending = ill_frag_timeout(ill, timeout);
17426 
17427 	/*
17428 	 * Restart the timer, if we have fragments pending or if someone
17429 	 * wanted us to be scheduled again.
17430 	 */
17431 	mutex_enter(&ill->ill_lock);
17432 	ill->ill_fragtimer_executing = 0;
17433 	ill->ill_frag_timer_id = 0;
17434 	if (frag_pending || ill->ill_fragtimer_needrestart)
17435 		ill_frag_timer_start(ill);
17436 	mutex_exit(&ill->ill_lock);
17437 }
17438 
17439 void
17440 ill_frag_timer_start(ill_t *ill)
17441 {
17442 	ip_stack_t	*ipst = ill->ill_ipst;
17443 	clock_t	timeo_ms;
17444 
17445 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17446 
17447 	/* If the ill is closing or opening don't proceed */
17448 	if (ill->ill_state_flags & ILL_CONDEMNED)
17449 		return;
17450 
17451 	if (ill->ill_fragtimer_executing) {
17452 		/*
17453 		 * ill_frag_timer is currently executing. Just record the
17454 		 * the fact that we want the timer to be restarted.
17455 		 * ill_frag_timer will post a timeout before it returns,
17456 		 * ensuring it will be called again.
17457 		 */
17458 		ill->ill_fragtimer_needrestart = 1;
17459 		return;
17460 	}
17461 
17462 	if (ill->ill_frag_timer_id == 0) {
17463 		if (ill->ill_isv6)
17464 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
17465 		else
17466 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
17467 		/*
17468 		 * The timer is neither running nor is the timeout handler
17469 		 * executing. Post a timeout so that ill_frag_timer will be
17470 		 * called
17471 		 */
17472 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17473 		    MSEC_TO_TICK(timeo_ms >> 1));
17474 		ill->ill_fragtimer_needrestart = 0;
17475 	}
17476 }
17477 
17478 /*
17479  * This routine is needed for loopback when forwarding multicasts.
17480  *
17481  * IPQoS Notes:
17482  * IPPF processing is done in fanout routines.
17483  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17484  * processing for IPsec packets is done when it comes back in clear.
17485  * NOTE : The callers of this function need to do the ire_refrele for the
17486  *	  ire that is being passed in.
17487  */
17488 void
17489 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17490     ill_t *recv_ill, uint32_t esp_udp_ports)
17491 {
17492 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17493 	ill_t	*ill = (ill_t *)q->q_ptr;
17494 	uint32_t	sum;
17495 	uint32_t	u1;
17496 	uint32_t	u2;
17497 	int		hdr_length;
17498 	boolean_t	mctl_present;
17499 	mblk_t		*first_mp = mp;
17500 	mblk_t		*hada_mp = NULL;
17501 	ipha_t		*inner_ipha;
17502 	ip_stack_t	*ipst;
17503 
17504 	ASSERT(recv_ill != NULL);
17505 	ipst = recv_ill->ill_ipst;
17506 
17507 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17508 	    "ip_rput_locl_start: q %p", q);
17509 
17510 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17511 	ASSERT(ill != NULL);
17512 
17513 #define	rptr	((uchar_t *)ipha)
17514 #define	iphs	((uint16_t *)ipha)
17515 
17516 	/*
17517 	 * no UDP or TCP packet should come here anymore.
17518 	 */
17519 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17520 	    ipha->ipha_protocol != IPPROTO_UDP);
17521 
17522 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17523 	if (mctl_present &&
17524 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17525 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17526 
17527 		/*
17528 		 * It's an IPsec accelerated packet.
17529 		 * Keep a pointer to the data attributes around until
17530 		 * we allocate the ipsec_info_t.
17531 		 */
17532 		IPSECHW_DEBUG(IPSECHW_PKT,
17533 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17534 		hada_mp = first_mp;
17535 		hada_mp->b_cont = NULL;
17536 		/*
17537 		 * Since it is accelerated, it comes directly from
17538 		 * the ill and the data attributes is followed by
17539 		 * the packet data.
17540 		 */
17541 		ASSERT(mp->b_datap->db_type != M_CTL);
17542 		first_mp = mp;
17543 		mctl_present = B_FALSE;
17544 	}
17545 
17546 	/*
17547 	 * IF M_CTL is not present, then ipsec_in_is_secure
17548 	 * should return B_TRUE. There is a case where loopback
17549 	 * packets has an M_CTL in the front with all the
17550 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17551 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17552 	 * packets never comes here, it is safe to ASSERT the
17553 	 * following.
17554 	 */
17555 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17556 
17557 	/*
17558 	 * Also, we should never have an mctl_present if this is an
17559 	 * ESP-in-UDP packet.
17560 	 */
17561 	ASSERT(!mctl_present || !esp_in_udp_packet);
17562 
17563 	/* u1 is # words of IP options */
17564 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17565 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17566 
17567 	/*
17568 	 * Don't verify header checksum if we just removed UDP header or
17569 	 * packet is coming back from AH/ESP.
17570 	 */
17571 	if (!esp_in_udp_packet && !mctl_present) {
17572 		if (u1) {
17573 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17574 				if (hada_mp != NULL)
17575 					freemsg(hada_mp);
17576 				return;
17577 			}
17578 		} else {
17579 			/* Check the IP header checksum.  */
17580 #define	uph	((uint16_t *)ipha)
17581 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17582 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17583 #undef  uph
17584 			/* finish doing IP checksum */
17585 			sum = (sum & 0xFFFF) + (sum >> 16);
17586 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17587 			if (sum && sum != 0xFFFF) {
17588 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17589 				goto drop_pkt;
17590 			}
17591 		}
17592 	}
17593 
17594 	/*
17595 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17596 	 * might be called more than once for secure packets, count only
17597 	 * the first time.
17598 	 */
17599 	if (!mctl_present) {
17600 		UPDATE_IB_PKT_COUNT(ire);
17601 		ire->ire_last_used_time = lbolt;
17602 	}
17603 
17604 	/* Check for fragmentation offset. */
17605 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17606 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17607 	if (u1) {
17608 		/*
17609 		 * We re-assemble fragments before we do the AH/ESP
17610 		 * processing. Thus, M_CTL should not be present
17611 		 * while we are re-assembling.
17612 		 */
17613 		ASSERT(!mctl_present);
17614 		ASSERT(first_mp == mp);
17615 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17616 			return;
17617 
17618 		/*
17619 		 * Make sure that first_mp points back to mp as
17620 		 * the mp we came in with could have changed in
17621 		 * ip_rput_fragment().
17622 		 */
17623 		ipha = (ipha_t *)mp->b_rptr;
17624 		first_mp = mp;
17625 	}
17626 
17627 	/*
17628 	 * Clear hardware checksumming flag as it is currently only
17629 	 * used by TCP and UDP.
17630 	 */
17631 	DB_CKSUMFLAGS(mp) = 0;
17632 
17633 	/* Now we have a complete datagram, destined for this machine. */
17634 	u1 = IPH_HDR_LENGTH(ipha);
17635 	switch (ipha->ipha_protocol) {
17636 	case IPPROTO_ICMP: {
17637 		ire_t		*ire_zone;
17638 		ilm_t		*ilm;
17639 		mblk_t		*mp1;
17640 		zoneid_t	last_zoneid;
17641 		ilm_walker_t	ilw;
17642 
17643 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17644 			ASSERT(ire->ire_type == IRE_BROADCAST);
17645 
17646 			/*
17647 			 * In the multicast case, applications may have joined
17648 			 * the group from different zones, so we need to deliver
17649 			 * the packet to each of them. Loop through the
17650 			 * multicast memberships structures (ilm) on the receive
17651 			 * ill and send a copy of the packet up each matching
17652 			 * one. However, we don't do this for multicasts sent on
17653 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17654 			 * they must stay in the sender's zone.
17655 			 *
17656 			 * ilm_add_v6() ensures that ilms in the same zone are
17657 			 * contiguous in the ill_ilm list. We use this property
17658 			 * to avoid sending duplicates needed when two
17659 			 * applications in the same zone join the same group on
17660 			 * different logical interfaces: we ignore the ilm if
17661 			 * its zoneid is the same as the last matching one.
17662 			 * In addition, the sending of the packet for
17663 			 * ire_zoneid is delayed until all of the other ilms
17664 			 * have been exhausted.
17665 			 */
17666 			last_zoneid = -1;
17667 			ilm = ilm_walker_start(&ilw, recv_ill);
17668 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17669 				if (ipha->ipha_dst != ilm->ilm_addr ||
17670 				    ilm->ilm_zoneid == last_zoneid ||
17671 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17672 				    ilm->ilm_zoneid == ALL_ZONES ||
17673 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17674 					continue;
17675 				mp1 = ip_copymsg(first_mp);
17676 				if (mp1 == NULL)
17677 					continue;
17678 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17679 				    0, sum, mctl_present, B_TRUE,
17680 				    recv_ill, ilm->ilm_zoneid);
17681 				last_zoneid = ilm->ilm_zoneid;
17682 			}
17683 			ilm_walker_finish(&ilw);
17684 		} else if (ire->ire_type == IRE_BROADCAST) {
17685 			/*
17686 			 * In the broadcast case, there may be many zones
17687 			 * which need a copy of the packet delivered to them.
17688 			 * There is one IRE_BROADCAST per broadcast address
17689 			 * and per zone; we walk those using a helper function.
17690 			 * In addition, the sending of the packet for ire is
17691 			 * delayed until all of the other ires have been
17692 			 * processed.
17693 			 */
17694 			IRB_REFHOLD(ire->ire_bucket);
17695 			ire_zone = NULL;
17696 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17697 			    ire)) != NULL) {
17698 				mp1 = ip_copymsg(first_mp);
17699 				if (mp1 == NULL)
17700 					continue;
17701 
17702 				UPDATE_IB_PKT_COUNT(ire_zone);
17703 				ire_zone->ire_last_used_time = lbolt;
17704 				icmp_inbound(q, mp1, B_TRUE, ill,
17705 				    0, sum, mctl_present, B_TRUE,
17706 				    recv_ill, ire_zone->ire_zoneid);
17707 			}
17708 			IRB_REFRELE(ire->ire_bucket);
17709 		}
17710 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17711 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17712 		    ire->ire_zoneid);
17713 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17714 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17715 		return;
17716 	}
17717 	case IPPROTO_IGMP:
17718 		/*
17719 		 * If we are not willing to accept IGMP packets in clear,
17720 		 * then check with global policy.
17721 		 */
17722 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17723 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17724 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17725 			if (first_mp == NULL)
17726 				return;
17727 		}
17728 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17729 			freemsg(first_mp);
17730 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17731 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17732 			return;
17733 		}
17734 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17735 			/* Bad packet - discarded by igmp_input */
17736 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17737 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17738 			if (mctl_present)
17739 				freeb(first_mp);
17740 			return;
17741 		}
17742 		/*
17743 		 * igmp_input() may have returned the pulled up message.
17744 		 * So first_mp and ipha need to be reinitialized.
17745 		 */
17746 		ipha = (ipha_t *)mp->b_rptr;
17747 		if (mctl_present)
17748 			first_mp->b_cont = mp;
17749 		else
17750 			first_mp = mp;
17751 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17752 		    connf_head != NULL) {
17753 			/* No user-level listener for IGMP packets */
17754 			goto drop_pkt;
17755 		}
17756 		/* deliver to local raw users */
17757 		break;
17758 	case IPPROTO_PIM:
17759 		/*
17760 		 * If we are not willing to accept PIM packets in clear,
17761 		 * then check with global policy.
17762 		 */
17763 		if (ipst->ips_pim_accept_clear_messages == 0) {
17764 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17765 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17766 			if (first_mp == NULL)
17767 				return;
17768 		}
17769 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17770 			freemsg(first_mp);
17771 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17772 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17773 			return;
17774 		}
17775 		if (pim_input(q, mp, ill) != 0) {
17776 			/* Bad packet - discarded by pim_input */
17777 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17778 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17779 			if (mctl_present)
17780 				freeb(first_mp);
17781 			return;
17782 		}
17783 
17784 		/*
17785 		 * pim_input() may have pulled up the message so ipha needs to
17786 		 * be reinitialized.
17787 		 */
17788 		ipha = (ipha_t *)mp->b_rptr;
17789 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17790 		    connf_head != NULL) {
17791 			/* No user-level listener for PIM packets */
17792 			goto drop_pkt;
17793 		}
17794 		/* deliver to local raw users */
17795 		break;
17796 	case IPPROTO_ENCAP:
17797 		/*
17798 		 * Handle self-encapsulated packets (IP-in-IP where
17799 		 * the inner addresses == the outer addresses).
17800 		 */
17801 		hdr_length = IPH_HDR_LENGTH(ipha);
17802 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17803 		    mp->b_wptr) {
17804 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17805 			    sizeof (ipha_t) - mp->b_rptr)) {
17806 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17807 				freemsg(first_mp);
17808 				return;
17809 			}
17810 			ipha = (ipha_t *)mp->b_rptr;
17811 		}
17812 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17813 		/*
17814 		 * Check the sanity of the inner IP header.
17815 		 */
17816 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17817 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17818 			freemsg(first_mp);
17819 			return;
17820 		}
17821 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17822 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17823 			freemsg(first_mp);
17824 			return;
17825 		}
17826 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17827 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17828 			ipsec_in_t *ii;
17829 
17830 			/*
17831 			 * Self-encapsulated tunnel packet. Remove
17832 			 * the outer IP header and fanout again.
17833 			 * We also need to make sure that the inner
17834 			 * header is pulled up until options.
17835 			 */
17836 			mp->b_rptr = (uchar_t *)inner_ipha;
17837 			ipha = inner_ipha;
17838 			hdr_length = IPH_HDR_LENGTH(ipha);
17839 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17840 				if (!pullupmsg(mp, (uchar_t *)ipha +
17841 				    + hdr_length - mp->b_rptr)) {
17842 					freemsg(first_mp);
17843 					return;
17844 				}
17845 				ipha = (ipha_t *)mp->b_rptr;
17846 			}
17847 			if (hdr_length > sizeof (ipha_t)) {
17848 				/* We got options on the inner packet. */
17849 				ipaddr_t dst = ipha->ipha_dst;
17850 
17851 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17852 				    -1) {
17853 					/* Bad options! */
17854 					return;
17855 				}
17856 				if (dst != ipha->ipha_dst) {
17857 					/*
17858 					 * Someone put a source-route in
17859 					 * the inside header of a self-
17860 					 * encapsulated packet.  Drop it
17861 					 * with extreme prejudice and let
17862 					 * the sender know.
17863 					 */
17864 					icmp_unreachable(q, first_mp,
17865 					    ICMP_SOURCE_ROUTE_FAILED,
17866 					    recv_ill->ill_zoneid, ipst);
17867 					return;
17868 				}
17869 			}
17870 			if (!mctl_present) {
17871 				ASSERT(first_mp == mp);
17872 				/*
17873 				 * This means that somebody is sending
17874 				 * Self-encapsualted packets without AH/ESP.
17875 				 * If AH/ESP was present, we would have already
17876 				 * allocated the first_mp.
17877 				 *
17878 				 * Send this packet to find a tunnel endpoint.
17879 				 * if I can't find one, an ICMP
17880 				 * PROTOCOL_UNREACHABLE will get sent.
17881 				 */
17882 				goto fanout;
17883 			}
17884 			/*
17885 			 * We generally store the ill_index if we need to
17886 			 * do IPsec processing as we lose the ill queue when
17887 			 * we come back. But in this case, we never should
17888 			 * have to store the ill_index here as it should have
17889 			 * been stored previously when we processed the
17890 			 * AH/ESP header in this routine or for non-ipsec
17891 			 * cases, we still have the queue. But for some bad
17892 			 * packets from the wire, we can get to IPsec after
17893 			 * this and we better store the index for that case.
17894 			 */
17895 			ill = (ill_t *)q->q_ptr;
17896 			ii = (ipsec_in_t *)first_mp->b_rptr;
17897 			ii->ipsec_in_ill_index =
17898 			    ill->ill_phyint->phyint_ifindex;
17899 			ii->ipsec_in_rill_index =
17900 			    recv_ill->ill_phyint->phyint_ifindex;
17901 			if (ii->ipsec_in_decaps) {
17902 				/*
17903 				 * This packet is self-encapsulated multiple
17904 				 * times. We don't want to recurse infinitely.
17905 				 * To keep it simple, drop the packet.
17906 				 */
17907 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17908 				freemsg(first_mp);
17909 				return;
17910 			}
17911 			ii->ipsec_in_decaps = B_TRUE;
17912 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17913 			    ire);
17914 			return;
17915 		}
17916 		break;
17917 	case IPPROTO_AH:
17918 	case IPPROTO_ESP: {
17919 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17920 
17921 		/*
17922 		 * Fast path for AH/ESP. If this is the first time
17923 		 * we are sending a datagram to AH/ESP, allocate
17924 		 * a IPSEC_IN message and prepend it. Otherwise,
17925 		 * just fanout.
17926 		 */
17927 
17928 		int ipsec_rc;
17929 		ipsec_in_t *ii;
17930 		netstack_t *ns = ipst->ips_netstack;
17931 
17932 		IP_STAT(ipst, ipsec_proto_ahesp);
17933 		if (!mctl_present) {
17934 			ASSERT(first_mp == mp);
17935 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17936 			if (first_mp == NULL) {
17937 				ip1dbg(("ip_proto_input: IPSEC_IN "
17938 				    "allocation failure.\n"));
17939 				freemsg(hada_mp); /* okay ifnull */
17940 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17941 				freemsg(mp);
17942 				return;
17943 			}
17944 			/*
17945 			 * Store the ill_index so that when we come back
17946 			 * from IPsec we ride on the same queue.
17947 			 */
17948 			ill = (ill_t *)q->q_ptr;
17949 			ii = (ipsec_in_t *)first_mp->b_rptr;
17950 			ii->ipsec_in_ill_index =
17951 			    ill->ill_phyint->phyint_ifindex;
17952 			ii->ipsec_in_rill_index =
17953 			    recv_ill->ill_phyint->phyint_ifindex;
17954 			first_mp->b_cont = mp;
17955 			/*
17956 			 * Cache hardware acceleration info.
17957 			 */
17958 			if (hada_mp != NULL) {
17959 				IPSECHW_DEBUG(IPSECHW_PKT,
17960 				    ("ip_rput_local: caching data attr.\n"));
17961 				ii->ipsec_in_accelerated = B_TRUE;
17962 				ii->ipsec_in_da = hada_mp;
17963 				hada_mp = NULL;
17964 			}
17965 		} else {
17966 			ii = (ipsec_in_t *)first_mp->b_rptr;
17967 		}
17968 
17969 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17970 
17971 		if (!ipsec_loaded(ipss)) {
17972 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17973 			    ire->ire_zoneid, ipst);
17974 			return;
17975 		}
17976 
17977 		ns = ipst->ips_netstack;
17978 		/* select inbound SA and have IPsec process the pkt */
17979 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17980 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17981 			boolean_t esp_in_udp_sa;
17982 			if (esph == NULL)
17983 				return;
17984 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17985 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17986 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17987 			    IPSA_F_NATT) != 0);
17988 			/*
17989 			 * The following is a fancy, but quick, way of saying:
17990 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17991 			 *    OR
17992 			 * ESP SA and ESP-in-UDP packet --> drop
17993 			 */
17994 			if (esp_in_udp_sa != esp_in_udp_packet) {
17995 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17996 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17997 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17998 				    &ns->netstack_ipsec->ipsec_dropper);
17999 				return;
18000 			}
18001 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
18002 			    first_mp, esph);
18003 		} else {
18004 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
18005 			if (ah == NULL)
18006 				return;
18007 			ASSERT(ii->ipsec_in_ah_sa != NULL);
18008 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
18009 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
18010 			    first_mp, ah);
18011 		}
18012 
18013 		switch (ipsec_rc) {
18014 		case IPSEC_STATUS_SUCCESS:
18015 			break;
18016 		case IPSEC_STATUS_FAILED:
18017 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
18018 			/* FALLTHRU */
18019 		case IPSEC_STATUS_PENDING:
18020 			return;
18021 		}
18022 		/* we're done with IPsec processing, send it up */
18023 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
18024 		return;
18025 	}
18026 	default:
18027 		break;
18028 	}
18029 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
18030 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
18031 		    ire->ire_zoneid));
18032 		goto drop_pkt;
18033 	}
18034 	/*
18035 	 * Handle protocols with which IP is less intimate.  There
18036 	 * can be more than one stream bound to a particular
18037 	 * protocol.  When this is the case, each one gets a copy
18038 	 * of any incoming packets.
18039 	 */
18040 fanout:
18041 	ip_fanout_proto(q, first_mp, ill, ipha,
18042 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
18043 	    B_TRUE, recv_ill, ire->ire_zoneid);
18044 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
18045 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
18046 	return;
18047 
18048 drop_pkt:
18049 	freemsg(first_mp);
18050 	if (hada_mp != NULL)
18051 		freeb(hada_mp);
18052 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
18053 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
18054 #undef	rptr
18055 #undef  iphs
18056 
18057 }
18058 
18059 /*
18060  * Update any source route, record route or timestamp options.
18061  * Check that we are at end of strict source route.
18062  * The options have already been checked for sanity in ip_rput_options().
18063  */
18064 static boolean_t
18065 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
18066     ip_stack_t *ipst)
18067 {
18068 	ipoptp_t	opts;
18069 	uchar_t		*opt;
18070 	uint8_t		optval;
18071 	uint8_t		optlen;
18072 	ipaddr_t	dst;
18073 	uint32_t	ts;
18074 	ire_t		*dst_ire;
18075 	timestruc_t	now;
18076 	zoneid_t	zoneid;
18077 	ill_t		*ill;
18078 
18079 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18080 
18081 	ip2dbg(("ip_rput_local_options\n"));
18082 
18083 	for (optval = ipoptp_first(&opts, ipha);
18084 	    optval != IPOPT_EOL;
18085 	    optval = ipoptp_next(&opts)) {
18086 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18087 		opt = opts.ipoptp_cur;
18088 		optlen = opts.ipoptp_len;
18089 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18090 		    optval, optlen));
18091 		switch (optval) {
18092 			uint32_t off;
18093 		case IPOPT_SSRR:
18094 		case IPOPT_LSRR:
18095 			off = opt[IPOPT_OFFSET];
18096 			off--;
18097 			if (optlen < IP_ADDR_LEN ||
18098 			    off > optlen - IP_ADDR_LEN) {
18099 				/* End of source route */
18100 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18101 				break;
18102 			}
18103 			/*
18104 			 * This will only happen if two consecutive entries
18105 			 * in the source route contains our address or if
18106 			 * it is a packet with a loose source route which
18107 			 * reaches us before consuming the whole source route
18108 			 */
18109 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18110 			if (optval == IPOPT_SSRR) {
18111 				goto bad_src_route;
18112 			}
18113 			/*
18114 			 * Hack: instead of dropping the packet truncate the
18115 			 * source route to what has been used by filling the
18116 			 * rest with IPOPT_NOP.
18117 			 */
18118 			opt[IPOPT_OLEN] = (uint8_t)off;
18119 			while (off < optlen) {
18120 				opt[off++] = IPOPT_NOP;
18121 			}
18122 			break;
18123 		case IPOPT_RR:
18124 			off = opt[IPOPT_OFFSET];
18125 			off--;
18126 			if (optlen < IP_ADDR_LEN ||
18127 			    off > optlen - IP_ADDR_LEN) {
18128 				/* No more room - ignore */
18129 				ip1dbg((
18130 				    "ip_rput_local_options: end of RR\n"));
18131 				break;
18132 			}
18133 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18134 			    IP_ADDR_LEN);
18135 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18136 			break;
18137 		case IPOPT_TS:
18138 			/* Insert timestamp if there is romm */
18139 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18140 			case IPOPT_TS_TSONLY:
18141 				off = IPOPT_TS_TIMELEN;
18142 				break;
18143 			case IPOPT_TS_PRESPEC:
18144 			case IPOPT_TS_PRESPEC_RFC791:
18145 				/* Verify that the address matched */
18146 				off = opt[IPOPT_OFFSET] - 1;
18147 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18148 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18149 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18150 				    ipst);
18151 				if (dst_ire == NULL) {
18152 					/* Not for us */
18153 					break;
18154 				}
18155 				ire_refrele(dst_ire);
18156 				/* FALLTHRU */
18157 			case IPOPT_TS_TSANDADDR:
18158 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18159 				break;
18160 			default:
18161 				/*
18162 				 * ip_*put_options should have already
18163 				 * dropped this packet.
18164 				 */
18165 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18166 				    "unknown IT - bug in ip_rput_options?\n");
18167 				return (B_TRUE);	/* Keep "lint" happy */
18168 			}
18169 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18170 				/* Increase overflow counter */
18171 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18172 				opt[IPOPT_POS_OV_FLG] =
18173 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18174 				    (off << 4));
18175 				break;
18176 			}
18177 			off = opt[IPOPT_OFFSET] - 1;
18178 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18179 			case IPOPT_TS_PRESPEC:
18180 			case IPOPT_TS_PRESPEC_RFC791:
18181 			case IPOPT_TS_TSANDADDR:
18182 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18183 				    IP_ADDR_LEN);
18184 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18185 				/* FALLTHRU */
18186 			case IPOPT_TS_TSONLY:
18187 				off = opt[IPOPT_OFFSET] - 1;
18188 				/* Compute # of milliseconds since midnight */
18189 				gethrestime(&now);
18190 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18191 				    now.tv_nsec / (NANOSEC / MILLISEC);
18192 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18193 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18194 				break;
18195 			}
18196 			break;
18197 		}
18198 	}
18199 	return (B_TRUE);
18200 
18201 bad_src_route:
18202 	q = WR(q);
18203 	if (q->q_next != NULL)
18204 		ill = q->q_ptr;
18205 	else
18206 		ill = NULL;
18207 
18208 	/* make sure we clear any indication of a hardware checksum */
18209 	DB_CKSUMFLAGS(mp) = 0;
18210 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18211 	if (zoneid == ALL_ZONES)
18212 		freemsg(mp);
18213 	else
18214 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18215 	return (B_FALSE);
18216 
18217 }
18218 
18219 /*
18220  * Process IP options in an inbound packet.  If an option affects the
18221  * effective destination address, return the next hop address via dstp.
18222  * Returns -1 if something fails in which case an ICMP error has been sent
18223  * and mp freed.
18224  */
18225 static int
18226 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18227     ip_stack_t *ipst)
18228 {
18229 	ipoptp_t	opts;
18230 	uchar_t		*opt;
18231 	uint8_t		optval;
18232 	uint8_t		optlen;
18233 	ipaddr_t	dst;
18234 	intptr_t	code = 0;
18235 	ire_t		*ire = NULL;
18236 	zoneid_t	zoneid;
18237 	ill_t		*ill;
18238 
18239 	ip2dbg(("ip_rput_options\n"));
18240 	dst = ipha->ipha_dst;
18241 	for (optval = ipoptp_first(&opts, ipha);
18242 	    optval != IPOPT_EOL;
18243 	    optval = ipoptp_next(&opts)) {
18244 		opt = opts.ipoptp_cur;
18245 		optlen = opts.ipoptp_len;
18246 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18247 		    optval, optlen));
18248 		/*
18249 		 * Note: we need to verify the checksum before we
18250 		 * modify anything thus this routine only extracts the next
18251 		 * hop dst from any source route.
18252 		 */
18253 		switch (optval) {
18254 			uint32_t off;
18255 		case IPOPT_SSRR:
18256 		case IPOPT_LSRR:
18257 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18258 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18259 			if (ire == NULL) {
18260 				if (optval == IPOPT_SSRR) {
18261 					ip1dbg(("ip_rput_options: not next"
18262 					    " strict source route 0x%x\n",
18263 					    ntohl(dst)));
18264 					code = (char *)&ipha->ipha_dst -
18265 					    (char *)ipha;
18266 					goto param_prob; /* RouterReq's */
18267 				}
18268 				ip2dbg(("ip_rput_options: "
18269 				    "not next source route 0x%x\n",
18270 				    ntohl(dst)));
18271 				break;
18272 			}
18273 			ire_refrele(ire);
18274 
18275 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18276 				ip1dbg((
18277 				    "ip_rput_options: bad option offset\n"));
18278 				code = (char *)&opt[IPOPT_OLEN] -
18279 				    (char *)ipha;
18280 				goto param_prob;
18281 			}
18282 			off = opt[IPOPT_OFFSET];
18283 			off--;
18284 		redo_srr:
18285 			if (optlen < IP_ADDR_LEN ||
18286 			    off > optlen - IP_ADDR_LEN) {
18287 				/* End of source route */
18288 				ip1dbg(("ip_rput_options: end of SR\n"));
18289 				break;
18290 			}
18291 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18292 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18293 			    ntohl(dst)));
18294 
18295 			/*
18296 			 * Check if our address is present more than
18297 			 * once as consecutive hops in source route.
18298 			 * XXX verify per-interface ip_forwarding
18299 			 * for source route?
18300 			 */
18301 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18302 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18303 
18304 			if (ire != NULL) {
18305 				ire_refrele(ire);
18306 				off += IP_ADDR_LEN;
18307 				goto redo_srr;
18308 			}
18309 
18310 			if (dst == htonl(INADDR_LOOPBACK)) {
18311 				ip1dbg(("ip_rput_options: loopback addr in "
18312 				    "source route!\n"));
18313 				goto bad_src_route;
18314 			}
18315 			/*
18316 			 * For strict: verify that dst is directly
18317 			 * reachable.
18318 			 */
18319 			if (optval == IPOPT_SSRR) {
18320 				ire = ire_ftable_lookup(dst, 0, 0,
18321 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18322 				    msg_getlabel(mp),
18323 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18324 				if (ire == NULL) {
18325 					ip1dbg(("ip_rput_options: SSRR not "
18326 					    "directly reachable: 0x%x\n",
18327 					    ntohl(dst)));
18328 					goto bad_src_route;
18329 				}
18330 				ire_refrele(ire);
18331 			}
18332 			/*
18333 			 * Defer update of the offset and the record route
18334 			 * until the packet is forwarded.
18335 			 */
18336 			break;
18337 		case IPOPT_RR:
18338 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18339 				ip1dbg((
18340 				    "ip_rput_options: bad option offset\n"));
18341 				code = (char *)&opt[IPOPT_OLEN] -
18342 				    (char *)ipha;
18343 				goto param_prob;
18344 			}
18345 			break;
18346 		case IPOPT_TS:
18347 			/*
18348 			 * Verify that length >= 5 and that there is either
18349 			 * room for another timestamp or that the overflow
18350 			 * counter is not maxed out.
18351 			 */
18352 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18353 			if (optlen < IPOPT_MINLEN_IT) {
18354 				goto param_prob;
18355 			}
18356 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18357 				ip1dbg((
18358 				    "ip_rput_options: bad option offset\n"));
18359 				code = (char *)&opt[IPOPT_OFFSET] -
18360 				    (char *)ipha;
18361 				goto param_prob;
18362 			}
18363 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18364 			case IPOPT_TS_TSONLY:
18365 				off = IPOPT_TS_TIMELEN;
18366 				break;
18367 			case IPOPT_TS_TSANDADDR:
18368 			case IPOPT_TS_PRESPEC:
18369 			case IPOPT_TS_PRESPEC_RFC791:
18370 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18371 				break;
18372 			default:
18373 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18374 				    (char *)ipha;
18375 				goto param_prob;
18376 			}
18377 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18378 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18379 				/*
18380 				 * No room and the overflow counter is 15
18381 				 * already.
18382 				 */
18383 				goto param_prob;
18384 			}
18385 			break;
18386 		}
18387 	}
18388 
18389 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18390 		*dstp = dst;
18391 		return (0);
18392 	}
18393 
18394 	ip1dbg(("ip_rput_options: error processing IP options."));
18395 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18396 
18397 param_prob:
18398 	q = WR(q);
18399 	if (q->q_next != NULL)
18400 		ill = q->q_ptr;
18401 	else
18402 		ill = NULL;
18403 
18404 	/* make sure we clear any indication of a hardware checksum */
18405 	DB_CKSUMFLAGS(mp) = 0;
18406 	/* Don't know whether this is for non-global or global/forwarding */
18407 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18408 	if (zoneid == ALL_ZONES)
18409 		freemsg(mp);
18410 	else
18411 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18412 	return (-1);
18413 
18414 bad_src_route:
18415 	q = WR(q);
18416 	if (q->q_next != NULL)
18417 		ill = q->q_ptr;
18418 	else
18419 		ill = NULL;
18420 
18421 	/* make sure we clear any indication of a hardware checksum */
18422 	DB_CKSUMFLAGS(mp) = 0;
18423 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18424 	if (zoneid == ALL_ZONES)
18425 		freemsg(mp);
18426 	else
18427 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18428 	return (-1);
18429 }
18430 
18431 /*
18432  * IP & ICMP info in >=14 msg's ...
18433  *  - ip fixed part (mib2_ip_t)
18434  *  - icmp fixed part (mib2_icmp_t)
18435  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18436  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18437  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18438  *  - ipRouteAttributeTable (ip 102)	labeled routes
18439  *  - ip multicast membership (ip_member_t)
18440  *  - ip multicast source filtering (ip_grpsrc_t)
18441  *  - igmp fixed part (struct igmpstat)
18442  *  - multicast routing stats (struct mrtstat)
18443  *  - multicast routing vifs (array of struct vifctl)
18444  *  - multicast routing routes (array of struct mfcctl)
18445  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18446  *					One per ill plus one generic
18447  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18448  *					One per ill plus one generic
18449  *  - ipv6RouteEntry			all IPv6 IREs
18450  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18451  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18452  *  - ipv6AddrEntry			all IPv6 ipifs
18453  *  - ipv6 multicast membership (ipv6_member_t)
18454  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18455  *
18456  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18457  *
18458  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18459  * already filled in by the caller.
18460  * Return value of 0 indicates that no messages were sent and caller
18461  * should free mpctl.
18462  */
18463 int
18464 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18465 {
18466 	ip_stack_t *ipst;
18467 	sctp_stack_t *sctps;
18468 
18469 	if (q->q_next != NULL) {
18470 		ipst = ILLQ_TO_IPST(q);
18471 	} else {
18472 		ipst = CONNQ_TO_IPST(q);
18473 	}
18474 	ASSERT(ipst != NULL);
18475 	sctps = ipst->ips_netstack->netstack_sctp;
18476 
18477 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18478 		return (0);
18479 	}
18480 
18481 	/*
18482 	 * For the purposes of the (broken) packet shell use
18483 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18484 	 * to make TCP and UDP appear first in the list of mib items.
18485 	 * TBD: We could expand this and use it in netstat so that
18486 	 * the kernel doesn't have to produce large tables (connections,
18487 	 * routes, etc) when netstat only wants the statistics or a particular
18488 	 * table.
18489 	 */
18490 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18491 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18492 			return (1);
18493 		}
18494 	}
18495 
18496 	if (level != MIB2_TCP) {
18497 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18498 			return (1);
18499 		}
18500 	}
18501 
18502 	if (level != MIB2_UDP) {
18503 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18504 			return (1);
18505 		}
18506 	}
18507 
18508 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18509 	    ipst)) == NULL) {
18510 		return (1);
18511 	}
18512 
18513 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18514 		return (1);
18515 	}
18516 
18517 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18518 		return (1);
18519 	}
18520 
18521 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18522 		return (1);
18523 	}
18524 
18525 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18526 		return (1);
18527 	}
18528 
18529 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18530 		return (1);
18531 	}
18532 
18533 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18534 		return (1);
18535 	}
18536 
18537 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18538 		return (1);
18539 	}
18540 
18541 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18542 		return (1);
18543 	}
18544 
18545 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18546 		return (1);
18547 	}
18548 
18549 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18550 		return (1);
18551 	}
18552 
18553 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18554 		return (1);
18555 	}
18556 
18557 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18558 		return (1);
18559 	}
18560 
18561 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18562 		return (1);
18563 	}
18564 
18565 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18566 	if (mpctl == NULL)
18567 		return (1);
18568 
18569 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18570 	if (mpctl == NULL)
18571 		return (1);
18572 
18573 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18574 		return (1);
18575 	}
18576 	freemsg(mpctl);
18577 	return (1);
18578 }
18579 
18580 /* Get global (legacy) IPv4 statistics */
18581 static mblk_t *
18582 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18583     ip_stack_t *ipst)
18584 {
18585 	mib2_ip_t		old_ip_mib;
18586 	struct opthdr		*optp;
18587 	mblk_t			*mp2ctl;
18588 
18589 	/*
18590 	 * make a copy of the original message
18591 	 */
18592 	mp2ctl = copymsg(mpctl);
18593 
18594 	/* fixed length IP structure... */
18595 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18596 	optp->level = MIB2_IP;
18597 	optp->name = 0;
18598 	SET_MIB(old_ip_mib.ipForwarding,
18599 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18600 	SET_MIB(old_ip_mib.ipDefaultTTL,
18601 	    (uint32_t)ipst->ips_ip_def_ttl);
18602 	SET_MIB(old_ip_mib.ipReasmTimeout,
18603 	    ipst->ips_ip_g_frag_timeout);
18604 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18605 	    sizeof (mib2_ipAddrEntry_t));
18606 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18607 	    sizeof (mib2_ipRouteEntry_t));
18608 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18609 	    sizeof (mib2_ipNetToMediaEntry_t));
18610 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18611 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18612 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18613 	    sizeof (mib2_ipAttributeEntry_t));
18614 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18615 
18616 	/*
18617 	 * Grab the statistics from the new IP MIB
18618 	 */
18619 	SET_MIB(old_ip_mib.ipInReceives,
18620 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18621 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18622 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18623 	SET_MIB(old_ip_mib.ipForwDatagrams,
18624 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18625 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18626 	    ipmib->ipIfStatsInUnknownProtos);
18627 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18628 	SET_MIB(old_ip_mib.ipInDelivers,
18629 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18630 	SET_MIB(old_ip_mib.ipOutRequests,
18631 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18632 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18633 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18634 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18635 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18636 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18637 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18638 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18639 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18640 
18641 	/* ipRoutingDiscards is not being used */
18642 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18643 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18644 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18645 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18646 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18647 	    ipmib->ipIfStatsReasmDuplicates);
18648 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18649 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18650 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18651 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18652 	SET_MIB(old_ip_mib.rawipInOverflows,
18653 	    ipmib->rawipIfStatsInOverflows);
18654 
18655 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18656 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18657 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18658 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18659 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18660 	    ipmib->ipIfStatsOutSwitchIPVersion);
18661 
18662 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18663 	    (int)sizeof (old_ip_mib))) {
18664 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18665 		    (uint_t)sizeof (old_ip_mib)));
18666 	}
18667 
18668 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18669 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18670 	    (int)optp->level, (int)optp->name, (int)optp->len));
18671 	qreply(q, mpctl);
18672 	return (mp2ctl);
18673 }
18674 
18675 /* Per interface IPv4 statistics */
18676 static mblk_t *
18677 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18678 {
18679 	struct opthdr		*optp;
18680 	mblk_t			*mp2ctl;
18681 	ill_t			*ill;
18682 	ill_walk_context_t	ctx;
18683 	mblk_t			*mp_tail = NULL;
18684 	mib2_ipIfStatsEntry_t	global_ip_mib;
18685 
18686 	/*
18687 	 * Make a copy of the original message
18688 	 */
18689 	mp2ctl = copymsg(mpctl);
18690 
18691 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18692 	optp->level = MIB2_IP;
18693 	optp->name = MIB2_IP_TRAFFIC_STATS;
18694 	/* Include "unknown interface" ip_mib */
18695 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18696 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18697 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18698 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18699 	    (ipst->ips_ip_g_forward ? 1 : 2));
18700 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18701 	    (uint32_t)ipst->ips_ip_def_ttl);
18702 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18703 	    sizeof (mib2_ipIfStatsEntry_t));
18704 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18705 	    sizeof (mib2_ipAddrEntry_t));
18706 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18707 	    sizeof (mib2_ipRouteEntry_t));
18708 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18709 	    sizeof (mib2_ipNetToMediaEntry_t));
18710 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18711 	    sizeof (ip_member_t));
18712 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18713 	    sizeof (ip_grpsrc_t));
18714 
18715 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18716 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18717 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18718 		    "failed to allocate %u bytes\n",
18719 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18720 	}
18721 
18722 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18723 
18724 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18725 	ill = ILL_START_WALK_V4(&ctx, ipst);
18726 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18727 		ill->ill_ip_mib->ipIfStatsIfIndex =
18728 		    ill->ill_phyint->phyint_ifindex;
18729 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18730 		    (ipst->ips_ip_g_forward ? 1 : 2));
18731 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18732 		    (uint32_t)ipst->ips_ip_def_ttl);
18733 
18734 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18735 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18736 		    (char *)ill->ill_ip_mib,
18737 		    (int)sizeof (*ill->ill_ip_mib))) {
18738 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18739 			    "failed to allocate %u bytes\n",
18740 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18741 		}
18742 	}
18743 	rw_exit(&ipst->ips_ill_g_lock);
18744 
18745 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18746 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18747 	    "level %d, name %d, len %d\n",
18748 	    (int)optp->level, (int)optp->name, (int)optp->len));
18749 	qreply(q, mpctl);
18750 
18751 	if (mp2ctl == NULL)
18752 		return (NULL);
18753 
18754 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18755 }
18756 
18757 /* Global IPv4 ICMP statistics */
18758 static mblk_t *
18759 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18760 {
18761 	struct opthdr		*optp;
18762 	mblk_t			*mp2ctl;
18763 
18764 	/*
18765 	 * Make a copy of the original message
18766 	 */
18767 	mp2ctl = copymsg(mpctl);
18768 
18769 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18770 	optp->level = MIB2_ICMP;
18771 	optp->name = 0;
18772 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18773 	    (int)sizeof (ipst->ips_icmp_mib))) {
18774 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18775 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18776 	}
18777 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18778 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18779 	    (int)optp->level, (int)optp->name, (int)optp->len));
18780 	qreply(q, mpctl);
18781 	return (mp2ctl);
18782 }
18783 
18784 /* Global IPv4 IGMP statistics */
18785 static mblk_t *
18786 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18787 {
18788 	struct opthdr		*optp;
18789 	mblk_t			*mp2ctl;
18790 
18791 	/*
18792 	 * make a copy of the original message
18793 	 */
18794 	mp2ctl = copymsg(mpctl);
18795 
18796 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18797 	optp->level = EXPER_IGMP;
18798 	optp->name = 0;
18799 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18800 	    (int)sizeof (ipst->ips_igmpstat))) {
18801 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18802 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18803 	}
18804 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18805 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18806 	    (int)optp->level, (int)optp->name, (int)optp->len));
18807 	qreply(q, mpctl);
18808 	return (mp2ctl);
18809 }
18810 
18811 /* Global IPv4 Multicast Routing statistics */
18812 static mblk_t *
18813 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18814 {
18815 	struct opthdr		*optp;
18816 	mblk_t			*mp2ctl;
18817 
18818 	/*
18819 	 * make a copy of the original message
18820 	 */
18821 	mp2ctl = copymsg(mpctl);
18822 
18823 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18824 	optp->level = EXPER_DVMRP;
18825 	optp->name = 0;
18826 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18827 		ip0dbg(("ip_mroute_stats: failed\n"));
18828 	}
18829 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18830 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18831 	    (int)optp->level, (int)optp->name, (int)optp->len));
18832 	qreply(q, mpctl);
18833 	return (mp2ctl);
18834 }
18835 
18836 /* IPv4 address information */
18837 static mblk_t *
18838 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18839 {
18840 	struct opthdr		*optp;
18841 	mblk_t			*mp2ctl;
18842 	mblk_t			*mp_tail = NULL;
18843 	ill_t			*ill;
18844 	ipif_t			*ipif;
18845 	uint_t			bitval;
18846 	mib2_ipAddrEntry_t	mae;
18847 	zoneid_t		zoneid;
18848 	ill_walk_context_t ctx;
18849 
18850 	/*
18851 	 * make a copy of the original message
18852 	 */
18853 	mp2ctl = copymsg(mpctl);
18854 
18855 	/* ipAddrEntryTable */
18856 
18857 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18858 	optp->level = MIB2_IP;
18859 	optp->name = MIB2_IP_ADDR;
18860 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18861 
18862 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18863 	ill = ILL_START_WALK_V4(&ctx, ipst);
18864 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18865 		for (ipif = ill->ill_ipif; ipif != NULL;
18866 		    ipif = ipif->ipif_next) {
18867 			if (ipif->ipif_zoneid != zoneid &&
18868 			    ipif->ipif_zoneid != ALL_ZONES)
18869 				continue;
18870 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18871 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18872 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18873 
18874 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18875 			    OCTET_LENGTH);
18876 			mae.ipAdEntIfIndex.o_length =
18877 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18878 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18879 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18880 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18881 			mae.ipAdEntInfo.ae_subnet_len =
18882 			    ip_mask_to_plen(ipif->ipif_net_mask);
18883 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18884 			for (bitval = 1;
18885 			    bitval &&
18886 			    !(bitval & ipif->ipif_brd_addr);
18887 			    bitval <<= 1)
18888 				noop;
18889 			mae.ipAdEntBcastAddr = bitval;
18890 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18891 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18892 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18893 			mae.ipAdEntInfo.ae_broadcast_addr =
18894 			    ipif->ipif_brd_addr;
18895 			mae.ipAdEntInfo.ae_pp_dst_addr =
18896 			    ipif->ipif_pp_dst_addr;
18897 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18898 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18899 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18900 
18901 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18902 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18903 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18904 				    "allocate %u bytes\n",
18905 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18906 			}
18907 		}
18908 	}
18909 	rw_exit(&ipst->ips_ill_g_lock);
18910 
18911 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18912 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18913 	    (int)optp->level, (int)optp->name, (int)optp->len));
18914 	qreply(q, mpctl);
18915 	return (mp2ctl);
18916 }
18917 
18918 /* IPv6 address information */
18919 static mblk_t *
18920 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18921 {
18922 	struct opthdr		*optp;
18923 	mblk_t			*mp2ctl;
18924 	mblk_t			*mp_tail = NULL;
18925 	ill_t			*ill;
18926 	ipif_t			*ipif;
18927 	mib2_ipv6AddrEntry_t	mae6;
18928 	zoneid_t		zoneid;
18929 	ill_walk_context_t	ctx;
18930 
18931 	/*
18932 	 * make a copy of the original message
18933 	 */
18934 	mp2ctl = copymsg(mpctl);
18935 
18936 	/* ipv6AddrEntryTable */
18937 
18938 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18939 	optp->level = MIB2_IP6;
18940 	optp->name = MIB2_IP6_ADDR;
18941 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18942 
18943 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18944 	ill = ILL_START_WALK_V6(&ctx, ipst);
18945 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18946 		for (ipif = ill->ill_ipif; ipif != NULL;
18947 		    ipif = ipif->ipif_next) {
18948 			if (ipif->ipif_zoneid != zoneid &&
18949 			    ipif->ipif_zoneid != ALL_ZONES)
18950 				continue;
18951 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18952 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18953 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18954 
18955 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18956 			    OCTET_LENGTH);
18957 			mae6.ipv6AddrIfIndex.o_length =
18958 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18959 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18960 			mae6.ipv6AddrPfxLength =
18961 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18962 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18963 			mae6.ipv6AddrInfo.ae_subnet_len =
18964 			    mae6.ipv6AddrPfxLength;
18965 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18966 
18967 			/* Type: stateless(1), stateful(2), unknown(3) */
18968 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18969 				mae6.ipv6AddrType = 1;
18970 			else
18971 				mae6.ipv6AddrType = 2;
18972 			/* Anycast: true(1), false(2) */
18973 			if (ipif->ipif_flags & IPIF_ANYCAST)
18974 				mae6.ipv6AddrAnycastFlag = 1;
18975 			else
18976 				mae6.ipv6AddrAnycastFlag = 2;
18977 
18978 			/*
18979 			 * Address status: preferred(1), deprecated(2),
18980 			 * invalid(3), inaccessible(4), unknown(5)
18981 			 */
18982 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18983 				mae6.ipv6AddrStatus = 3;
18984 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18985 				mae6.ipv6AddrStatus = 2;
18986 			else
18987 				mae6.ipv6AddrStatus = 1;
18988 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18989 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18990 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18991 			    ipif->ipif_v6pp_dst_addr;
18992 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18993 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18994 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18995 			mae6.ipv6AddrIdentifier = ill->ill_token;
18996 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18997 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18998 			mae6.ipv6AddrRetransmitTime =
18999 			    ill->ill_reachable_retrans_time;
19000 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19001 			    (char *)&mae6,
19002 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
19003 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
19004 				    "allocate %u bytes\n",
19005 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
19006 			}
19007 		}
19008 	}
19009 	rw_exit(&ipst->ips_ill_g_lock);
19010 
19011 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19012 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
19013 	    (int)optp->level, (int)optp->name, (int)optp->len));
19014 	qreply(q, mpctl);
19015 	return (mp2ctl);
19016 }
19017 
19018 /* IPv4 multicast group membership. */
19019 static mblk_t *
19020 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19021 {
19022 	struct opthdr		*optp;
19023 	mblk_t			*mp2ctl;
19024 	ill_t			*ill;
19025 	ipif_t			*ipif;
19026 	ilm_t			*ilm;
19027 	ip_member_t		ipm;
19028 	mblk_t			*mp_tail = NULL;
19029 	ill_walk_context_t	ctx;
19030 	zoneid_t		zoneid;
19031 	ilm_walker_t		ilw;
19032 
19033 	/*
19034 	 * make a copy of the original message
19035 	 */
19036 	mp2ctl = copymsg(mpctl);
19037 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19038 
19039 	/* ipGroupMember table */
19040 	optp = (struct opthdr *)&mpctl->b_rptr[
19041 	    sizeof (struct T_optmgmt_ack)];
19042 	optp->level = MIB2_IP;
19043 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
19044 
19045 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19046 	ill = ILL_START_WALK_V4(&ctx, ipst);
19047 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19048 		if (IS_UNDER_IPMP(ill))
19049 			continue;
19050 
19051 		ilm = ilm_walker_start(&ilw, ill);
19052 		for (ipif = ill->ill_ipif; ipif != NULL;
19053 		    ipif = ipif->ipif_next) {
19054 			if (ipif->ipif_zoneid != zoneid &&
19055 			    ipif->ipif_zoneid != ALL_ZONES)
19056 				continue;	/* not this zone */
19057 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
19058 			    OCTET_LENGTH);
19059 			ipm.ipGroupMemberIfIndex.o_length =
19060 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
19061 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19062 				ASSERT(ilm->ilm_ipif != NULL);
19063 				ASSERT(ilm->ilm_ill == NULL);
19064 				if (ilm->ilm_ipif != ipif)
19065 					continue;
19066 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
19067 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
19068 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
19069 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19070 				    (char *)&ipm, (int)sizeof (ipm))) {
19071 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
19072 					    "failed to allocate %u bytes\n",
19073 					    (uint_t)sizeof (ipm)));
19074 				}
19075 			}
19076 		}
19077 		ilm_walker_finish(&ilw);
19078 	}
19079 	rw_exit(&ipst->ips_ill_g_lock);
19080 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19081 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19082 	    (int)optp->level, (int)optp->name, (int)optp->len));
19083 	qreply(q, mpctl);
19084 	return (mp2ctl);
19085 }
19086 
19087 /* IPv6 multicast group membership. */
19088 static mblk_t *
19089 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19090 {
19091 	struct opthdr		*optp;
19092 	mblk_t			*mp2ctl;
19093 	ill_t			*ill;
19094 	ilm_t			*ilm;
19095 	ipv6_member_t		ipm6;
19096 	mblk_t			*mp_tail = NULL;
19097 	ill_walk_context_t	ctx;
19098 	zoneid_t		zoneid;
19099 	ilm_walker_t		ilw;
19100 
19101 	/*
19102 	 * make a copy of the original message
19103 	 */
19104 	mp2ctl = copymsg(mpctl);
19105 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19106 
19107 	/* ip6GroupMember table */
19108 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19109 	optp->level = MIB2_IP6;
19110 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19111 
19112 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19113 	ill = ILL_START_WALK_V6(&ctx, ipst);
19114 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19115 		if (IS_UNDER_IPMP(ill))
19116 			continue;
19117 
19118 		ilm = ilm_walker_start(&ilw, ill);
19119 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19120 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19121 			ASSERT(ilm->ilm_ipif == NULL);
19122 			ASSERT(ilm->ilm_ill != NULL);
19123 			if (ilm->ilm_zoneid != zoneid)
19124 				continue;	/* not this zone */
19125 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19126 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19127 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19128 			if (!snmp_append_data2(mpctl->b_cont,
19129 			    &mp_tail,
19130 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19131 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19132 				    "failed to allocate %u bytes\n",
19133 				    (uint_t)sizeof (ipm6)));
19134 			}
19135 		}
19136 		ilm_walker_finish(&ilw);
19137 	}
19138 	rw_exit(&ipst->ips_ill_g_lock);
19139 
19140 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19141 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19142 	    (int)optp->level, (int)optp->name, (int)optp->len));
19143 	qreply(q, mpctl);
19144 	return (mp2ctl);
19145 }
19146 
19147 /* IP multicast filtered sources */
19148 static mblk_t *
19149 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19150 {
19151 	struct opthdr		*optp;
19152 	mblk_t			*mp2ctl;
19153 	ill_t			*ill;
19154 	ipif_t			*ipif;
19155 	ilm_t			*ilm;
19156 	ip_grpsrc_t		ips;
19157 	mblk_t			*mp_tail = NULL;
19158 	ill_walk_context_t	ctx;
19159 	zoneid_t		zoneid;
19160 	int			i;
19161 	slist_t			*sl;
19162 	ilm_walker_t		ilw;
19163 
19164 	/*
19165 	 * make a copy of the original message
19166 	 */
19167 	mp2ctl = copymsg(mpctl);
19168 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19169 
19170 	/* ipGroupSource table */
19171 	optp = (struct opthdr *)&mpctl->b_rptr[
19172 	    sizeof (struct T_optmgmt_ack)];
19173 	optp->level = MIB2_IP;
19174 	optp->name = EXPER_IP_GROUP_SOURCES;
19175 
19176 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19177 	ill = ILL_START_WALK_V4(&ctx, ipst);
19178 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19179 		if (IS_UNDER_IPMP(ill))
19180 			continue;
19181 
19182 		ilm = ilm_walker_start(&ilw, ill);
19183 		for (ipif = ill->ill_ipif; ipif != NULL;
19184 		    ipif = ipif->ipif_next) {
19185 			if (ipif->ipif_zoneid != zoneid)
19186 				continue;	/* not this zone */
19187 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19188 			    OCTET_LENGTH);
19189 			ips.ipGroupSourceIfIndex.o_length =
19190 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19191 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19192 				ASSERT(ilm->ilm_ipif != NULL);
19193 				ASSERT(ilm->ilm_ill == NULL);
19194 				sl = ilm->ilm_filter;
19195 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19196 					continue;
19197 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19198 				for (i = 0; i < sl->sl_numsrc; i++) {
19199 					if (!IN6_IS_ADDR_V4MAPPED(
19200 					    &sl->sl_addr[i]))
19201 						continue;
19202 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19203 					    ips.ipGroupSourceAddress);
19204 					if (snmp_append_data2(mpctl->b_cont,
19205 					    &mp_tail, (char *)&ips,
19206 					    (int)sizeof (ips)) == 0) {
19207 						ip1dbg(("ip_snmp_get_mib2_"
19208 						    "ip_group_src: failed to "
19209 						    "allocate %u bytes\n",
19210 						    (uint_t)sizeof (ips)));
19211 					}
19212 				}
19213 			}
19214 		}
19215 		ilm_walker_finish(&ilw);
19216 	}
19217 	rw_exit(&ipst->ips_ill_g_lock);
19218 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19219 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19220 	    (int)optp->level, (int)optp->name, (int)optp->len));
19221 	qreply(q, mpctl);
19222 	return (mp2ctl);
19223 }
19224 
19225 /* IPv6 multicast filtered sources. */
19226 static mblk_t *
19227 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19228 {
19229 	struct opthdr		*optp;
19230 	mblk_t			*mp2ctl;
19231 	ill_t			*ill;
19232 	ilm_t			*ilm;
19233 	ipv6_grpsrc_t		ips6;
19234 	mblk_t			*mp_tail = NULL;
19235 	ill_walk_context_t	ctx;
19236 	zoneid_t		zoneid;
19237 	int			i;
19238 	slist_t			*sl;
19239 	ilm_walker_t		ilw;
19240 
19241 	/*
19242 	 * make a copy of the original message
19243 	 */
19244 	mp2ctl = copymsg(mpctl);
19245 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19246 
19247 	/* ip6GroupMember table */
19248 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19249 	optp->level = MIB2_IP6;
19250 	optp->name = EXPER_IP6_GROUP_SOURCES;
19251 
19252 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19253 	ill = ILL_START_WALK_V6(&ctx, ipst);
19254 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19255 		if (IS_UNDER_IPMP(ill))
19256 			continue;
19257 
19258 		ilm = ilm_walker_start(&ilw, ill);
19259 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19260 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19261 			ASSERT(ilm->ilm_ipif == NULL);
19262 			ASSERT(ilm->ilm_ill != NULL);
19263 			sl = ilm->ilm_filter;
19264 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19265 				continue;
19266 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19267 			for (i = 0; i < sl->sl_numsrc; i++) {
19268 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19269 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19270 				    (char *)&ips6, (int)sizeof (ips6))) {
19271 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19272 					    "group_src: failed to allocate "
19273 					    "%u bytes\n",
19274 					    (uint_t)sizeof (ips6)));
19275 				}
19276 			}
19277 		}
19278 		ilm_walker_finish(&ilw);
19279 	}
19280 	rw_exit(&ipst->ips_ill_g_lock);
19281 
19282 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19283 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19284 	    (int)optp->level, (int)optp->name, (int)optp->len));
19285 	qreply(q, mpctl);
19286 	return (mp2ctl);
19287 }
19288 
19289 /* Multicast routing virtual interface table. */
19290 static mblk_t *
19291 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19292 {
19293 	struct opthdr		*optp;
19294 	mblk_t			*mp2ctl;
19295 
19296 	/*
19297 	 * make a copy of the original message
19298 	 */
19299 	mp2ctl = copymsg(mpctl);
19300 
19301 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19302 	optp->level = EXPER_DVMRP;
19303 	optp->name = EXPER_DVMRP_VIF;
19304 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19305 		ip0dbg(("ip_mroute_vif: failed\n"));
19306 	}
19307 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19308 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19309 	    (int)optp->level, (int)optp->name, (int)optp->len));
19310 	qreply(q, mpctl);
19311 	return (mp2ctl);
19312 }
19313 
19314 /* Multicast routing table. */
19315 static mblk_t *
19316 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19317 {
19318 	struct opthdr		*optp;
19319 	mblk_t			*mp2ctl;
19320 
19321 	/*
19322 	 * make a copy of the original message
19323 	 */
19324 	mp2ctl = copymsg(mpctl);
19325 
19326 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19327 	optp->level = EXPER_DVMRP;
19328 	optp->name = EXPER_DVMRP_MRT;
19329 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19330 		ip0dbg(("ip_mroute_mrt: failed\n"));
19331 	}
19332 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19333 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19334 	    (int)optp->level, (int)optp->name, (int)optp->len));
19335 	qreply(q, mpctl);
19336 	return (mp2ctl);
19337 }
19338 
19339 /*
19340  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19341  * in one IRE walk.
19342  */
19343 static mblk_t *
19344 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19345     ip_stack_t *ipst)
19346 {
19347 	struct opthdr	*optp;
19348 	mblk_t		*mp2ctl;	/* Returned */
19349 	mblk_t		*mp3ctl;	/* nettomedia */
19350 	mblk_t		*mp4ctl;	/* routeattrs */
19351 	iproutedata_t	ird;
19352 	zoneid_t	zoneid;
19353 
19354 	/*
19355 	 * make copies of the original message
19356 	 *	- mp2ctl is returned unchanged to the caller for his use
19357 	 *	- mpctl is sent upstream as ipRouteEntryTable
19358 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19359 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19360 	 */
19361 	mp2ctl = copymsg(mpctl);
19362 	mp3ctl = copymsg(mpctl);
19363 	mp4ctl = copymsg(mpctl);
19364 	if (mp3ctl == NULL || mp4ctl == NULL) {
19365 		freemsg(mp4ctl);
19366 		freemsg(mp3ctl);
19367 		freemsg(mp2ctl);
19368 		freemsg(mpctl);
19369 		return (NULL);
19370 	}
19371 
19372 	bzero(&ird, sizeof (ird));
19373 
19374 	ird.ird_route.lp_head = mpctl->b_cont;
19375 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19376 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19377 	/*
19378 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19379 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19380 	 * intended a temporary solution until a proper MIB API is provided
19381 	 * that provides complete filtering/caller-opt-in.
19382 	 */
19383 	if (level == EXPER_IP_AND_TESTHIDDEN)
19384 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19385 
19386 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19387 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19388 
19389 	/* ipRouteEntryTable in mpctl */
19390 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19391 	optp->level = MIB2_IP;
19392 	optp->name = MIB2_IP_ROUTE;
19393 	optp->len = msgdsize(ird.ird_route.lp_head);
19394 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19395 	    (int)optp->level, (int)optp->name, (int)optp->len));
19396 	qreply(q, mpctl);
19397 
19398 	/* ipNetToMediaEntryTable in mp3ctl */
19399 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19400 	optp->level = MIB2_IP;
19401 	optp->name = MIB2_IP_MEDIA;
19402 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19403 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19404 	    (int)optp->level, (int)optp->name, (int)optp->len));
19405 	qreply(q, mp3ctl);
19406 
19407 	/* ipRouteAttributeTable in mp4ctl */
19408 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19409 	optp->level = MIB2_IP;
19410 	optp->name = EXPER_IP_RTATTR;
19411 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19412 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19413 	    (int)optp->level, (int)optp->name, (int)optp->len));
19414 	if (optp->len == 0)
19415 		freemsg(mp4ctl);
19416 	else
19417 		qreply(q, mp4ctl);
19418 
19419 	return (mp2ctl);
19420 }
19421 
19422 /*
19423  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19424  * ipv6NetToMediaEntryTable in an NDP walk.
19425  */
19426 static mblk_t *
19427 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19428     ip_stack_t *ipst)
19429 {
19430 	struct opthdr	*optp;
19431 	mblk_t		*mp2ctl;	/* Returned */
19432 	mblk_t		*mp3ctl;	/* nettomedia */
19433 	mblk_t		*mp4ctl;	/* routeattrs */
19434 	iproutedata_t	ird;
19435 	zoneid_t	zoneid;
19436 
19437 	/*
19438 	 * make copies of the original message
19439 	 *	- mp2ctl is returned unchanged to the caller for his use
19440 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19441 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19442 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19443 	 */
19444 	mp2ctl = copymsg(mpctl);
19445 	mp3ctl = copymsg(mpctl);
19446 	mp4ctl = copymsg(mpctl);
19447 	if (mp3ctl == NULL || mp4ctl == NULL) {
19448 		freemsg(mp4ctl);
19449 		freemsg(mp3ctl);
19450 		freemsg(mp2ctl);
19451 		freemsg(mpctl);
19452 		return (NULL);
19453 	}
19454 
19455 	bzero(&ird, sizeof (ird));
19456 
19457 	ird.ird_route.lp_head = mpctl->b_cont;
19458 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19459 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19460 	/*
19461 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19462 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19463 	 * intended a temporary solution until a proper MIB API is provided
19464 	 * that provides complete filtering/caller-opt-in.
19465 	 */
19466 	if (level == EXPER_IP_AND_TESTHIDDEN)
19467 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19468 
19469 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19470 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19471 
19472 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19473 	optp->level = MIB2_IP6;
19474 	optp->name = MIB2_IP6_ROUTE;
19475 	optp->len = msgdsize(ird.ird_route.lp_head);
19476 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19477 	    (int)optp->level, (int)optp->name, (int)optp->len));
19478 	qreply(q, mpctl);
19479 
19480 	/* ipv6NetToMediaEntryTable in mp3ctl */
19481 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19482 
19483 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19484 	optp->level = MIB2_IP6;
19485 	optp->name = MIB2_IP6_MEDIA;
19486 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19487 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19488 	    (int)optp->level, (int)optp->name, (int)optp->len));
19489 	qreply(q, mp3ctl);
19490 
19491 	/* ipv6RouteAttributeTable in mp4ctl */
19492 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19493 	optp->level = MIB2_IP6;
19494 	optp->name = EXPER_IP_RTATTR;
19495 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19496 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19497 	    (int)optp->level, (int)optp->name, (int)optp->len));
19498 	if (optp->len == 0)
19499 		freemsg(mp4ctl);
19500 	else
19501 		qreply(q, mp4ctl);
19502 
19503 	return (mp2ctl);
19504 }
19505 
19506 /*
19507  * IPv6 mib: One per ill
19508  */
19509 static mblk_t *
19510 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19511 {
19512 	struct opthdr		*optp;
19513 	mblk_t			*mp2ctl;
19514 	ill_t			*ill;
19515 	ill_walk_context_t	ctx;
19516 	mblk_t			*mp_tail = NULL;
19517 
19518 	/*
19519 	 * Make a copy of the original message
19520 	 */
19521 	mp2ctl = copymsg(mpctl);
19522 
19523 	/* fixed length IPv6 structure ... */
19524 
19525 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19526 	optp->level = MIB2_IP6;
19527 	optp->name = 0;
19528 	/* Include "unknown interface" ip6_mib */
19529 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19530 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19531 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19532 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19533 	    ipst->ips_ipv6_forward ? 1 : 2);
19534 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19535 	    ipst->ips_ipv6_def_hops);
19536 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19537 	    sizeof (mib2_ipIfStatsEntry_t));
19538 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19539 	    sizeof (mib2_ipv6AddrEntry_t));
19540 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19541 	    sizeof (mib2_ipv6RouteEntry_t));
19542 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19543 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19544 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19545 	    sizeof (ipv6_member_t));
19546 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19547 	    sizeof (ipv6_grpsrc_t));
19548 
19549 	/*
19550 	 * Synchronize 64- and 32-bit counters
19551 	 */
19552 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19553 	    ipIfStatsHCInReceives);
19554 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19555 	    ipIfStatsHCInDelivers);
19556 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19557 	    ipIfStatsHCOutRequests);
19558 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19559 	    ipIfStatsHCOutForwDatagrams);
19560 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19561 	    ipIfStatsHCOutMcastPkts);
19562 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19563 	    ipIfStatsHCInMcastPkts);
19564 
19565 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19566 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19567 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19568 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19569 	}
19570 
19571 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19572 	ill = ILL_START_WALK_V6(&ctx, ipst);
19573 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19574 		ill->ill_ip_mib->ipIfStatsIfIndex =
19575 		    ill->ill_phyint->phyint_ifindex;
19576 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19577 		    ipst->ips_ipv6_forward ? 1 : 2);
19578 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19579 		    ill->ill_max_hops);
19580 
19581 		/*
19582 		 * Synchronize 64- and 32-bit counters
19583 		 */
19584 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19585 		    ipIfStatsHCInReceives);
19586 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19587 		    ipIfStatsHCInDelivers);
19588 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19589 		    ipIfStatsHCOutRequests);
19590 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19591 		    ipIfStatsHCOutForwDatagrams);
19592 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19593 		    ipIfStatsHCOutMcastPkts);
19594 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19595 		    ipIfStatsHCInMcastPkts);
19596 
19597 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19598 		    (char *)ill->ill_ip_mib,
19599 		    (int)sizeof (*ill->ill_ip_mib))) {
19600 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19601 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19602 		}
19603 	}
19604 	rw_exit(&ipst->ips_ill_g_lock);
19605 
19606 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19607 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19608 	    (int)optp->level, (int)optp->name, (int)optp->len));
19609 	qreply(q, mpctl);
19610 	return (mp2ctl);
19611 }
19612 
19613 /*
19614  * ICMPv6 mib: One per ill
19615  */
19616 static mblk_t *
19617 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19618 {
19619 	struct opthdr		*optp;
19620 	mblk_t			*mp2ctl;
19621 	ill_t			*ill;
19622 	ill_walk_context_t	ctx;
19623 	mblk_t			*mp_tail = NULL;
19624 	/*
19625 	 * Make a copy of the original message
19626 	 */
19627 	mp2ctl = copymsg(mpctl);
19628 
19629 	/* fixed length ICMPv6 structure ... */
19630 
19631 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19632 	optp->level = MIB2_ICMP6;
19633 	optp->name = 0;
19634 	/* Include "unknown interface" icmp6_mib */
19635 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19636 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19637 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19638 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19639 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19640 	    (char *)&ipst->ips_icmp6_mib,
19641 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19642 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19643 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19644 	}
19645 
19646 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19647 	ill = ILL_START_WALK_V6(&ctx, ipst);
19648 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19649 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19650 		    ill->ill_phyint->phyint_ifindex;
19651 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19652 		    (char *)ill->ill_icmp6_mib,
19653 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19654 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19655 			    "%u bytes\n",
19656 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19657 		}
19658 	}
19659 	rw_exit(&ipst->ips_ill_g_lock);
19660 
19661 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19662 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19663 	    (int)optp->level, (int)optp->name, (int)optp->len));
19664 	qreply(q, mpctl);
19665 	return (mp2ctl);
19666 }
19667 
19668 /*
19669  * ire_walk routine to create both ipRouteEntryTable and
19670  * ipRouteAttributeTable in one IRE walk
19671  */
19672 static void
19673 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19674 {
19675 	ill_t				*ill;
19676 	ipif_t				*ipif;
19677 	mib2_ipRouteEntry_t		*re;
19678 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19679 	ipaddr_t			gw_addr;
19680 	tsol_ire_gw_secattr_t		*attrp;
19681 	tsol_gc_t			*gc = NULL;
19682 	tsol_gcgrp_t			*gcgrp = NULL;
19683 	uint_t				sacnt = 0;
19684 	int				i;
19685 
19686 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19687 
19688 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19689 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19690 		return;
19691 	}
19692 
19693 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19694 		return;
19695 
19696 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19697 		mutex_enter(&attrp->igsa_lock);
19698 		if ((gc = attrp->igsa_gc) != NULL) {
19699 			gcgrp = gc->gc_grp;
19700 			ASSERT(gcgrp != NULL);
19701 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19702 			sacnt = 1;
19703 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19704 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19705 			gc = gcgrp->gcgrp_head;
19706 			sacnt = gcgrp->gcgrp_count;
19707 		}
19708 		mutex_exit(&attrp->igsa_lock);
19709 
19710 		/* do nothing if there's no gc to report */
19711 		if (gc == NULL) {
19712 			ASSERT(sacnt == 0);
19713 			if (gcgrp != NULL) {
19714 				/* we might as well drop the lock now */
19715 				rw_exit(&gcgrp->gcgrp_rwlock);
19716 				gcgrp = NULL;
19717 			}
19718 			attrp = NULL;
19719 		}
19720 
19721 		ASSERT(gc == NULL || (gcgrp != NULL &&
19722 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19723 	}
19724 	ASSERT(sacnt == 0 || gc != NULL);
19725 
19726 	if (sacnt != 0 &&
19727 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19728 		kmem_free(re, sizeof (*re));
19729 		rw_exit(&gcgrp->gcgrp_rwlock);
19730 		return;
19731 	}
19732 
19733 	/*
19734 	 * Return all IRE types for route table... let caller pick and choose
19735 	 */
19736 	re->ipRouteDest = ire->ire_addr;
19737 	ipif = ire->ire_ipif;
19738 	re->ipRouteIfIndex.o_length = 0;
19739 	if (ire->ire_type == IRE_CACHE) {
19740 		ill = (ill_t *)ire->ire_stq->q_ptr;
19741 		re->ipRouteIfIndex.o_length =
19742 		    ill->ill_name_length == 0 ? 0 :
19743 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19744 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19745 		    re->ipRouteIfIndex.o_length);
19746 	} else if (ipif != NULL) {
19747 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19748 		re->ipRouteIfIndex.o_length =
19749 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19750 	}
19751 	re->ipRouteMetric1 = -1;
19752 	re->ipRouteMetric2 = -1;
19753 	re->ipRouteMetric3 = -1;
19754 	re->ipRouteMetric4 = -1;
19755 
19756 	gw_addr = ire->ire_gateway_addr;
19757 
19758 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19759 		re->ipRouteNextHop = ire->ire_src_addr;
19760 	else
19761 		re->ipRouteNextHop = gw_addr;
19762 	/* indirect(4), direct(3), or invalid(2) */
19763 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19764 		re->ipRouteType = 2;
19765 	else
19766 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19767 	re->ipRouteProto = -1;
19768 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19769 	re->ipRouteMask = ire->ire_mask;
19770 	re->ipRouteMetric5 = -1;
19771 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19772 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19773 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19774 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19775 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19776 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19777 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19778 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19779 
19780 	if (ire->ire_flags & RTF_DYNAMIC) {
19781 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19782 	} else {
19783 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19784 	}
19785 
19786 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19787 	    (char *)re, (int)sizeof (*re))) {
19788 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19789 		    (uint_t)sizeof (*re)));
19790 	}
19791 
19792 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19793 		iaeptr->iae_routeidx = ird->ird_idx;
19794 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19795 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19796 	}
19797 
19798 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19799 	    (char *)iae, sacnt * sizeof (*iae))) {
19800 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19801 		    (unsigned)(sacnt * sizeof (*iae))));
19802 	}
19803 
19804 	/* bump route index for next pass */
19805 	ird->ird_idx++;
19806 
19807 	kmem_free(re, sizeof (*re));
19808 	if (sacnt != 0)
19809 		kmem_free(iae, sacnt * sizeof (*iae));
19810 
19811 	if (gcgrp != NULL)
19812 		rw_exit(&gcgrp->gcgrp_rwlock);
19813 }
19814 
19815 /*
19816  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19817  */
19818 static void
19819 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19820 {
19821 	ill_t				*ill;
19822 	ipif_t				*ipif;
19823 	mib2_ipv6RouteEntry_t		*re;
19824 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19825 	in6_addr_t			gw_addr_v6;
19826 	tsol_ire_gw_secattr_t		*attrp;
19827 	tsol_gc_t			*gc = NULL;
19828 	tsol_gcgrp_t			*gcgrp = NULL;
19829 	uint_t				sacnt = 0;
19830 	int				i;
19831 
19832 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19833 
19834 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19835 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19836 		return;
19837 	}
19838 
19839 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19840 		return;
19841 
19842 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19843 		mutex_enter(&attrp->igsa_lock);
19844 		if ((gc = attrp->igsa_gc) != NULL) {
19845 			gcgrp = gc->gc_grp;
19846 			ASSERT(gcgrp != NULL);
19847 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19848 			sacnt = 1;
19849 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19850 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19851 			gc = gcgrp->gcgrp_head;
19852 			sacnt = gcgrp->gcgrp_count;
19853 		}
19854 		mutex_exit(&attrp->igsa_lock);
19855 
19856 		/* do nothing if there's no gc to report */
19857 		if (gc == NULL) {
19858 			ASSERT(sacnt == 0);
19859 			if (gcgrp != NULL) {
19860 				/* we might as well drop the lock now */
19861 				rw_exit(&gcgrp->gcgrp_rwlock);
19862 				gcgrp = NULL;
19863 			}
19864 			attrp = NULL;
19865 		}
19866 
19867 		ASSERT(gc == NULL || (gcgrp != NULL &&
19868 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19869 	}
19870 	ASSERT(sacnt == 0 || gc != NULL);
19871 
19872 	if (sacnt != 0 &&
19873 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19874 		kmem_free(re, sizeof (*re));
19875 		rw_exit(&gcgrp->gcgrp_rwlock);
19876 		return;
19877 	}
19878 
19879 	/*
19880 	 * Return all IRE types for route table... let caller pick and choose
19881 	 */
19882 	re->ipv6RouteDest = ire->ire_addr_v6;
19883 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19884 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19885 	re->ipv6RouteIfIndex.o_length = 0;
19886 	ipif = ire->ire_ipif;
19887 	if (ire->ire_type == IRE_CACHE) {
19888 		ill = (ill_t *)ire->ire_stq->q_ptr;
19889 		re->ipv6RouteIfIndex.o_length =
19890 		    ill->ill_name_length == 0 ? 0 :
19891 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19892 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19893 		    re->ipv6RouteIfIndex.o_length);
19894 	} else if (ipif != NULL) {
19895 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19896 		re->ipv6RouteIfIndex.o_length =
19897 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19898 	}
19899 
19900 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19901 
19902 	mutex_enter(&ire->ire_lock);
19903 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19904 	mutex_exit(&ire->ire_lock);
19905 
19906 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19907 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19908 	else
19909 		re->ipv6RouteNextHop = gw_addr_v6;
19910 
19911 	/* remote(4), local(3), or discard(2) */
19912 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19913 		re->ipv6RouteType = 2;
19914 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19915 		re->ipv6RouteType = 3;
19916 	else
19917 		re->ipv6RouteType = 4;
19918 
19919 	re->ipv6RouteProtocol	= -1;
19920 	re->ipv6RoutePolicy	= 0;
19921 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19922 	re->ipv6RouteNextHopRDI	= 0;
19923 	re->ipv6RouteWeight	= 0;
19924 	re->ipv6RouteMetric	= 0;
19925 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19926 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19927 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19928 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19929 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19930 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19931 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19932 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19933 
19934 	if (ire->ire_flags & RTF_DYNAMIC) {
19935 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19936 	} else {
19937 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19938 	}
19939 
19940 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19941 	    (char *)re, (int)sizeof (*re))) {
19942 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19943 		    (uint_t)sizeof (*re)));
19944 	}
19945 
19946 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19947 		iaeptr->iae_routeidx = ird->ird_idx;
19948 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19949 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19950 	}
19951 
19952 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19953 	    (char *)iae, sacnt * sizeof (*iae))) {
19954 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19955 		    (unsigned)(sacnt * sizeof (*iae))));
19956 	}
19957 
19958 	/* bump route index for next pass */
19959 	ird->ird_idx++;
19960 
19961 	kmem_free(re, sizeof (*re));
19962 	if (sacnt != 0)
19963 		kmem_free(iae, sacnt * sizeof (*iae));
19964 
19965 	if (gcgrp != NULL)
19966 		rw_exit(&gcgrp->gcgrp_rwlock);
19967 }
19968 
19969 /*
19970  * ndp_walk routine to create ipv6NetToMediaEntryTable
19971  */
19972 static int
19973 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19974 {
19975 	ill_t				*ill;
19976 	mib2_ipv6NetToMediaEntry_t	ntme;
19977 	dl_unitdata_req_t		*dl;
19978 
19979 	ill = nce->nce_ill;
19980 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19981 		return (0);
19982 
19983 	/*
19984 	 * Neighbor cache entry attached to IRE with on-link
19985 	 * destination.
19986 	 */
19987 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19988 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19989 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19990 	    (nce->nce_res_mp != NULL)) {
19991 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19992 		ntme.ipv6NetToMediaPhysAddress.o_length =
19993 		    dl->dl_dest_addr_length;
19994 	} else {
19995 		ntme.ipv6NetToMediaPhysAddress.o_length =
19996 		    ill->ill_phys_addr_length;
19997 	}
19998 	if (nce->nce_res_mp != NULL) {
19999 		bcopy((char *)nce->nce_res_mp->b_rptr +
20000 		    NCE_LL_ADDR_OFFSET(ill),
20001 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
20002 		    ntme.ipv6NetToMediaPhysAddress.o_length);
20003 	} else {
20004 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
20005 		    ill->ill_phys_addr_length);
20006 	}
20007 	/*
20008 	 * Note: Returns ND_* states. Should be:
20009 	 * reachable(1), stale(2), delay(3), probe(4),
20010 	 * invalid(5), unknown(6)
20011 	 */
20012 	ntme.ipv6NetToMediaState = nce->nce_state;
20013 	ntme.ipv6NetToMediaLastUpdated = 0;
20014 
20015 	/* other(1), dynamic(2), static(3), local(4) */
20016 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
20017 		ntme.ipv6NetToMediaType = 4;
20018 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
20019 		ntme.ipv6NetToMediaType = 1;
20020 	} else {
20021 		ntme.ipv6NetToMediaType = 2;
20022 	}
20023 
20024 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
20025 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
20026 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
20027 		    (uint_t)sizeof (ntme)));
20028 	}
20029 	return (0);
20030 }
20031 
20032 /*
20033  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
20034  */
20035 /* ARGSUSED */
20036 int
20037 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
20038 {
20039 	switch (level) {
20040 	case MIB2_IP:
20041 	case MIB2_ICMP:
20042 		switch (name) {
20043 		default:
20044 			break;
20045 		}
20046 		return (1);
20047 	default:
20048 		return (1);
20049 	}
20050 }
20051 
20052 /*
20053  * When there exists both a 64- and 32-bit counter of a particular type
20054  * (i.e., InReceives), only the 64-bit counters are added.
20055  */
20056 void
20057 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
20058 {
20059 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
20060 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
20061 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
20062 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
20063 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
20064 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
20065 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
20066 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
20067 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
20068 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
20069 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
20070 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
20071 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
20072 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
20073 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
20074 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
20075 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
20076 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
20077 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
20078 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
20079 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
20080 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
20081 	    o2->ipIfStatsInWrongIPVersion);
20082 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
20083 	    o2->ipIfStatsInWrongIPVersion);
20084 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
20085 	    o2->ipIfStatsOutSwitchIPVersion);
20086 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
20087 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
20088 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
20089 	    o2->ipIfStatsHCInForwDatagrams);
20090 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
20091 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
20092 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
20093 	    o2->ipIfStatsHCOutForwDatagrams);
20094 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20095 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20096 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20097 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20098 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20099 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20100 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20101 	    o2->ipIfStatsHCOutMcastOctets);
20102 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20103 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20104 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20105 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20106 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20107 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20108 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20109 }
20110 
20111 void
20112 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20113 {
20114 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20115 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20116 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20117 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20118 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20119 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20120 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20121 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20122 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20123 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20124 	    o2->ipv6IfIcmpInRouterSolicits);
20125 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20126 	    o2->ipv6IfIcmpInRouterAdvertisements);
20127 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20128 	    o2->ipv6IfIcmpInNeighborSolicits);
20129 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20130 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20131 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20132 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20133 	    o2->ipv6IfIcmpInGroupMembQueries);
20134 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20135 	    o2->ipv6IfIcmpInGroupMembResponses);
20136 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20137 	    o2->ipv6IfIcmpInGroupMembReductions);
20138 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20139 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20140 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20141 	    o2->ipv6IfIcmpOutDestUnreachs);
20142 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20143 	    o2->ipv6IfIcmpOutAdminProhibs);
20144 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20145 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20146 	    o2->ipv6IfIcmpOutParmProblems);
20147 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20148 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20149 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20150 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20151 	    o2->ipv6IfIcmpOutRouterSolicits);
20152 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20153 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20154 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20155 	    o2->ipv6IfIcmpOutNeighborSolicits);
20156 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20157 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20158 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20159 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20160 	    o2->ipv6IfIcmpOutGroupMembQueries);
20161 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20162 	    o2->ipv6IfIcmpOutGroupMembResponses);
20163 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20164 	    o2->ipv6IfIcmpOutGroupMembReductions);
20165 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20166 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20167 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20168 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20169 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20170 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20171 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20172 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20173 	    o2->ipv6IfIcmpInGroupMembTotal);
20174 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20175 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20176 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20177 	    o2->ipv6IfIcmpInGroupMembBadReports);
20178 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20179 	    o2->ipv6IfIcmpInGroupMembOurReports);
20180 }
20181 
20182 /*
20183  * Called before the options are updated to check if this packet will
20184  * be source routed from here.
20185  * This routine assumes that the options are well formed i.e. that they
20186  * have already been checked.
20187  */
20188 static boolean_t
20189 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20190 {
20191 	ipoptp_t	opts;
20192 	uchar_t		*opt;
20193 	uint8_t		optval;
20194 	uint8_t		optlen;
20195 	ipaddr_t	dst;
20196 	ire_t		*ire;
20197 
20198 	if (IS_SIMPLE_IPH(ipha)) {
20199 		ip2dbg(("not source routed\n"));
20200 		return (B_FALSE);
20201 	}
20202 	dst = ipha->ipha_dst;
20203 	for (optval = ipoptp_first(&opts, ipha);
20204 	    optval != IPOPT_EOL;
20205 	    optval = ipoptp_next(&opts)) {
20206 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20207 		opt = opts.ipoptp_cur;
20208 		optlen = opts.ipoptp_len;
20209 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20210 		    optval, optlen));
20211 		switch (optval) {
20212 			uint32_t off;
20213 		case IPOPT_SSRR:
20214 		case IPOPT_LSRR:
20215 			/*
20216 			 * If dst is one of our addresses and there are some
20217 			 * entries left in the source route return (true).
20218 			 */
20219 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20220 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20221 			if (ire == NULL) {
20222 				ip2dbg(("ip_source_routed: not next"
20223 				    " source route 0x%x\n",
20224 				    ntohl(dst)));
20225 				return (B_FALSE);
20226 			}
20227 			ire_refrele(ire);
20228 			off = opt[IPOPT_OFFSET];
20229 			off--;
20230 			if (optlen < IP_ADDR_LEN ||
20231 			    off > optlen - IP_ADDR_LEN) {
20232 				/* End of source route */
20233 				ip1dbg(("ip_source_routed: end of SR\n"));
20234 				return (B_FALSE);
20235 			}
20236 			return (B_TRUE);
20237 		}
20238 	}
20239 	ip2dbg(("not source routed\n"));
20240 	return (B_FALSE);
20241 }
20242 
20243 /*
20244  * Check if the packet contains any source route.
20245  */
20246 static boolean_t
20247 ip_source_route_included(ipha_t *ipha)
20248 {
20249 	ipoptp_t	opts;
20250 	uint8_t		optval;
20251 
20252 	if (IS_SIMPLE_IPH(ipha))
20253 		return (B_FALSE);
20254 	for (optval = ipoptp_first(&opts, ipha);
20255 	    optval != IPOPT_EOL;
20256 	    optval = ipoptp_next(&opts)) {
20257 		switch (optval) {
20258 		case IPOPT_SSRR:
20259 		case IPOPT_LSRR:
20260 			return (B_TRUE);
20261 		}
20262 	}
20263 	return (B_FALSE);
20264 }
20265 
20266 /*
20267  * Called when the IRE expiration timer fires.
20268  */
20269 void
20270 ip_trash_timer_expire(void *args)
20271 {
20272 	int			flush_flag = 0;
20273 	ire_expire_arg_t	iea;
20274 	ip_stack_t		*ipst = (ip_stack_t *)args;
20275 
20276 	iea.iea_ipst = ipst;	/* No netstack_hold */
20277 
20278 	/*
20279 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20280 	 * This lock makes sure that a new invocation of this function
20281 	 * that occurs due to an almost immediate timer firing will not
20282 	 * progress beyond this point until the current invocation is done
20283 	 */
20284 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20285 	ipst->ips_ip_ire_expire_id = 0;
20286 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20287 
20288 	/* Periodic timer */
20289 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20290 	    ipst->ips_ip_ire_arp_interval) {
20291 		/*
20292 		 * Remove all IRE_CACHE entries since they might
20293 		 * contain arp information.
20294 		 */
20295 		flush_flag |= FLUSH_ARP_TIME;
20296 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20297 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20298 	}
20299 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20300 	    ipst->ips_ip_ire_redir_interval) {
20301 		/* Remove all redirects */
20302 		flush_flag |= FLUSH_REDIRECT_TIME;
20303 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20304 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20305 	}
20306 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20307 	    ipst->ips_ip_ire_pathmtu_interval) {
20308 		/* Increase path mtu */
20309 		flush_flag |= FLUSH_MTU_TIME;
20310 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20311 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20312 	}
20313 
20314 	/*
20315 	 * Optimize for the case when there are no redirects in the
20316 	 * ftable, that is, no need to walk the ftable in that case.
20317 	 */
20318 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20319 		iea.iea_flush_flag = flush_flag;
20320 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20321 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20322 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20323 		    NULL, ALL_ZONES, ipst);
20324 	}
20325 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20326 	    ipst->ips_ip_redirect_cnt > 0) {
20327 		iea.iea_flush_flag = flush_flag;
20328 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20329 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20330 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20331 	}
20332 	if (flush_flag & FLUSH_MTU_TIME) {
20333 		/*
20334 		 * Walk all IPv6 IRE's and update them
20335 		 * Note that ARP and redirect timers are not
20336 		 * needed since NUD handles stale entries.
20337 		 */
20338 		flush_flag = FLUSH_MTU_TIME;
20339 		iea.iea_flush_flag = flush_flag;
20340 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20341 		    ALL_ZONES, ipst);
20342 	}
20343 
20344 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20345 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20346 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20347 
20348 	/*
20349 	 * Hold the lock to serialize timeout calls and prevent
20350 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20351 	 * for the timer to fire and a new invocation of this function
20352 	 * to start before the return value of timeout has been stored
20353 	 * in ip_ire_expire_id by the current invocation.
20354 	 */
20355 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20356 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20357 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20358 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20359 }
20360 
20361 /*
20362  * Called by the memory allocator subsystem directly, when the system
20363  * is running low on memory.
20364  */
20365 /* ARGSUSED */
20366 void
20367 ip_trash_ire_reclaim(void *args)
20368 {
20369 	netstack_handle_t nh;
20370 	netstack_t *ns;
20371 
20372 	netstack_next_init(&nh);
20373 	while ((ns = netstack_next(&nh)) != NULL) {
20374 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20375 		netstack_rele(ns);
20376 	}
20377 	netstack_next_fini(&nh);
20378 }
20379 
20380 static void
20381 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20382 {
20383 	ire_cache_count_t icc;
20384 	ire_cache_reclaim_t icr;
20385 	ncc_cache_count_t ncc;
20386 	nce_cache_reclaim_t ncr;
20387 	uint_t delete_cnt;
20388 	/*
20389 	 * Memory reclaim call back.
20390 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20391 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20392 	 * entries, determine what fraction to free for
20393 	 * each category of IRE_CACHE entries giving absolute priority
20394 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20395 	 * entry will be freed unless all offlink entries are freed).
20396 	 */
20397 	icc.icc_total = 0;
20398 	icc.icc_unused = 0;
20399 	icc.icc_offlink = 0;
20400 	icc.icc_pmtu = 0;
20401 	icc.icc_onlink = 0;
20402 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20403 
20404 	/*
20405 	 * Free NCEs for IPv6 like the onlink ires.
20406 	 */
20407 	ncc.ncc_total = 0;
20408 	ncc.ncc_host = 0;
20409 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20410 
20411 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20412 	    icc.icc_pmtu + icc.icc_onlink);
20413 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20414 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20415 	if (delete_cnt == 0)
20416 		return;
20417 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20418 	/* Always delete all unused offlink entries */
20419 	icr.icr_ipst = ipst;
20420 	icr.icr_unused = 1;
20421 	if (delete_cnt <= icc.icc_unused) {
20422 		/*
20423 		 * Only need to free unused entries.  In other words,
20424 		 * there are enough unused entries to free to meet our
20425 		 * target number of freed ire cache entries.
20426 		 */
20427 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20428 		ncr.ncr_host = 0;
20429 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20430 		/*
20431 		 * Only need to free unused entries, plus a fraction of offlink
20432 		 * entries.  It follows from the first if statement that
20433 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20434 		 */
20435 		delete_cnt -= icc.icc_unused;
20436 		/* Round up # deleted by truncating fraction */
20437 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20438 		icr.icr_pmtu = icr.icr_onlink = 0;
20439 		ncr.ncr_host = 0;
20440 	} else if (delete_cnt <=
20441 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20442 		/*
20443 		 * Free all unused and offlink entries, plus a fraction of
20444 		 * pmtu entries.  It follows from the previous if statement
20445 		 * that icc_pmtu is non-zero, and that
20446 		 * delete_cnt != icc_unused + icc_offlink.
20447 		 */
20448 		icr.icr_offlink = 1;
20449 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20450 		/* Round up # deleted by truncating fraction */
20451 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20452 		icr.icr_onlink = 0;
20453 		ncr.ncr_host = 0;
20454 	} else {
20455 		/*
20456 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20457 		 * of onlink entries.  If we're here, then we know that
20458 		 * icc_onlink is non-zero, and that
20459 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20460 		 */
20461 		icr.icr_offlink = icr.icr_pmtu = 1;
20462 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20463 		    icc.icc_pmtu;
20464 		/* Round up # deleted by truncating fraction */
20465 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20466 		/* Using the same delete fraction as for onlink IREs */
20467 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20468 	}
20469 #ifdef DEBUG
20470 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20471 	    "fractions %d/%d/%d/%d\n",
20472 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20473 	    icc.icc_unused, icc.icc_offlink,
20474 	    icc.icc_pmtu, icc.icc_onlink,
20475 	    icr.icr_unused, icr.icr_offlink,
20476 	    icr.icr_pmtu, icr.icr_onlink));
20477 #endif
20478 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20479 	if (ncr.ncr_host != 0)
20480 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20481 		    (uchar_t *)&ncr, ipst);
20482 #ifdef DEBUG
20483 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20484 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20485 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20486 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20487 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20488 	    icc.icc_pmtu, icc.icc_onlink));
20489 #endif
20490 }
20491 
20492 /*
20493  * ip_unbind is called when a copy of an unbind request is received from the
20494  * upper level protocol.  We remove this conn from any fanout hash list it is
20495  * on, and zero out the bind information.  No reply is expected up above.
20496  */
20497 void
20498 ip_unbind(conn_t *connp)
20499 {
20500 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20501 
20502 	if (is_system_labeled() && connp->conn_anon_port) {
20503 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20504 		    connp->conn_mlp_type, connp->conn_ulp,
20505 		    ntohs(connp->conn_lport), B_FALSE);
20506 		connp->conn_anon_port = 0;
20507 	}
20508 	connp->conn_mlp_type = mlptSingle;
20509 
20510 	ipcl_hash_remove(connp);
20511 
20512 }
20513 
20514 /*
20515  * Write side put procedure.  Outbound data, IOCTLs, responses from
20516  * resolvers, etc, come down through here.
20517  *
20518  * arg2 is always a queue_t *.
20519  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20520  * the zoneid.
20521  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20522  */
20523 void
20524 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20525 {
20526 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20527 }
20528 
20529 void
20530 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20531     ip_opt_info_t *infop)
20532 {
20533 	conn_t		*connp = NULL;
20534 	queue_t		*q = (queue_t *)arg2;
20535 	ipha_t		*ipha;
20536 #define	rptr	((uchar_t *)ipha)
20537 	ire_t		*ire = NULL;
20538 	ire_t		*sctp_ire = NULL;
20539 	uint32_t	v_hlen_tos_len;
20540 	ipaddr_t	dst;
20541 	mblk_t		*first_mp = NULL;
20542 	boolean_t	mctl_present;
20543 	ipsec_out_t	*io;
20544 	int		match_flags;
20545 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20546 	ipif_t		*dst_ipif;
20547 	boolean_t	multirt_need_resolve = B_FALSE;
20548 	mblk_t		*copy_mp = NULL;
20549 	int		err = 0;
20550 	zoneid_t	zoneid;
20551 	boolean_t	need_decref = B_FALSE;
20552 	boolean_t	ignore_dontroute = B_FALSE;
20553 	boolean_t	ignore_nexthop = B_FALSE;
20554 	boolean_t	ip_nexthop = B_FALSE;
20555 	ipaddr_t	nexthop_addr;
20556 	ip_stack_t	*ipst;
20557 
20558 #ifdef	_BIG_ENDIAN
20559 #define	V_HLEN	(v_hlen_tos_len >> 24)
20560 #else
20561 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20562 #endif
20563 
20564 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20565 	    "ip_wput_start: q %p", q);
20566 
20567 	/*
20568 	 * ip_wput fast path
20569 	 */
20570 
20571 	/* is packet from ARP ? */
20572 	if (q->q_next != NULL) {
20573 		zoneid = (zoneid_t)(uintptr_t)arg;
20574 		goto qnext;
20575 	}
20576 
20577 	connp = (conn_t *)arg;
20578 	ASSERT(connp != NULL);
20579 	zoneid = connp->conn_zoneid;
20580 	ipst = connp->conn_netstack->netstack_ip;
20581 	ASSERT(ipst != NULL);
20582 
20583 	/* is queue flow controlled? */
20584 	if ((q->q_first != NULL || connp->conn_draining) &&
20585 	    (caller == IP_WPUT)) {
20586 		ASSERT(!need_decref);
20587 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20588 		(void) putq(q, mp);
20589 		return;
20590 	}
20591 
20592 	/* Multidata transmit? */
20593 	if (DB_TYPE(mp) == M_MULTIDATA) {
20594 		/*
20595 		 * We should never get here, since all Multidata messages
20596 		 * originating from tcp should have been directed over to
20597 		 * tcp_multisend() in the first place.
20598 		 */
20599 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20600 		freemsg(mp);
20601 		return;
20602 	} else if (DB_TYPE(mp) != M_DATA)
20603 		goto notdata;
20604 
20605 	if (mp->b_flag & MSGHASREF) {
20606 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20607 		mp->b_flag &= ~MSGHASREF;
20608 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20609 		need_decref = B_TRUE;
20610 	}
20611 	ipha = (ipha_t *)mp->b_rptr;
20612 
20613 	/* is IP header non-aligned or mblk smaller than basic IP header */
20614 #ifndef SAFETY_BEFORE_SPEED
20615 	if (!OK_32PTR(rptr) ||
20616 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20617 		goto hdrtoosmall;
20618 #endif
20619 
20620 	ASSERT(OK_32PTR(ipha));
20621 
20622 	/*
20623 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20624 	 * wrong version, we'll catch it again in ip_output_v6.
20625 	 *
20626 	 * Note that this is *only* locally-generated output here, and never
20627 	 * forwarded data, and that we need to deal only with transports that
20628 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20629 	 * label.)
20630 	 */
20631 	if (is_system_labeled() &&
20632 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20633 	    !connp->conn_ulp_labeled) {
20634 		cred_t	*credp;
20635 		pid_t	pid;
20636 
20637 		credp = BEST_CRED(mp, connp, &pid);
20638 		err = tsol_check_label(credp, &mp,
20639 		    connp->conn_mac_exempt, ipst, pid);
20640 		ipha = (ipha_t *)mp->b_rptr;
20641 		if (err != 0) {
20642 			first_mp = mp;
20643 			if (err == EINVAL)
20644 				goto icmp_parameter_problem;
20645 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20646 			goto discard_pkt;
20647 		}
20648 	}
20649 
20650 	ASSERT(infop != NULL);
20651 
20652 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20653 		/*
20654 		 * IP_PKTINFO ancillary option is present.
20655 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20656 		 * allows using address of any zone as the source address.
20657 		 */
20658 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20659 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20660 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20661 		if (ire == NULL)
20662 			goto drop_pkt;
20663 		ire_refrele(ire);
20664 		ire = NULL;
20665 	}
20666 
20667 	/*
20668 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20669 	 */
20670 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20671 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20672 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20673 
20674 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20675 			goto drop_pkt;
20676 		/*
20677 		 * check that there is an ipif belonging
20678 		 * to our zone. IPCL_ZONEID is not used because
20679 		 * IP_ALLZONES option is valid only when the ill is
20680 		 * accessible from all zones i.e has a valid ipif in
20681 		 * all zones.
20682 		 */
20683 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20684 			goto drop_pkt;
20685 		}
20686 	}
20687 
20688 	/*
20689 	 * If there is a policy, try to attach an ipsec_out in
20690 	 * the front. At the end, first_mp either points to a
20691 	 * M_DATA message or IPSEC_OUT message linked to a
20692 	 * M_DATA message. We have to do it now as we might
20693 	 * lose the "conn" if we go through ip_newroute.
20694 	 */
20695 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20696 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20697 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20698 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20699 			if (need_decref)
20700 				CONN_DEC_REF(connp);
20701 			return;
20702 		} else {
20703 			ASSERT(mp->b_datap->db_type == M_CTL);
20704 			first_mp = mp;
20705 			mp = mp->b_cont;
20706 			mctl_present = B_TRUE;
20707 		}
20708 	} else {
20709 		first_mp = mp;
20710 		mctl_present = B_FALSE;
20711 	}
20712 
20713 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20714 
20715 	/* is wrong version or IP options present */
20716 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20717 		goto version_hdrlen_check;
20718 	dst = ipha->ipha_dst;
20719 
20720 	/* If IP_BOUND_IF has been set, use that ill. */
20721 	if (connp->conn_outgoing_ill != NULL) {
20722 		xmit_ill = conn_get_held_ill(connp,
20723 		    &connp->conn_outgoing_ill, &err);
20724 		if (err == ILL_LOOKUP_FAILED)
20725 			goto drop_pkt;
20726 
20727 		goto send_from_ill;
20728 	}
20729 
20730 	/* is packet multicast? */
20731 	if (CLASSD(dst))
20732 		goto multicast;
20733 
20734 	/*
20735 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20736 	 * takes precedence over conn_dontroute and conn_nexthop_set
20737 	 */
20738 	if (xmit_ill != NULL)
20739 		goto send_from_ill;
20740 
20741 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20742 		/*
20743 		 * If the destination is a broadcast, local, or loopback
20744 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20745 		 * standard path.
20746 		 */
20747 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20748 		if ((ire == NULL) || (ire->ire_type &
20749 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20750 			if (ire != NULL) {
20751 				ire_refrele(ire);
20752 				/* No more access to ire */
20753 				ire = NULL;
20754 			}
20755 			/*
20756 			 * bypass routing checks and go directly to interface.
20757 			 */
20758 			if (connp->conn_dontroute)
20759 				goto dontroute;
20760 
20761 			ASSERT(connp->conn_nexthop_set);
20762 			ip_nexthop = B_TRUE;
20763 			nexthop_addr = connp->conn_nexthop_v4;
20764 			goto send_from_ill;
20765 		}
20766 
20767 		/* Must be a broadcast, a loopback or a local ire */
20768 		ire_refrele(ire);
20769 		/* No more access to ire */
20770 		ire = NULL;
20771 	}
20772 
20773 	/*
20774 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20775 	 * this for the tcp global queue and listen end point
20776 	 * as it does not really have a real destination to
20777 	 * talk to.  This is also true for SCTP.
20778 	 */
20779 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20780 	    !connp->conn_fully_bound) {
20781 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20782 		if (ire == NULL)
20783 			goto noirefound;
20784 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20785 		    "ip_wput_end: q %p (%S)", q, "end");
20786 
20787 		/*
20788 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20789 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20790 		 */
20791 		if (ire->ire_flags & RTF_MULTIRT) {
20792 
20793 			/*
20794 			 * Force the TTL of multirouted packets if required.
20795 			 * The TTL of such packets is bounded by the
20796 			 * ip_multirt_ttl ndd variable.
20797 			 */
20798 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20799 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20800 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20801 				    "(was %d), dst 0x%08x\n",
20802 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20803 				    ntohl(ire->ire_addr)));
20804 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20805 			}
20806 			/*
20807 			 * We look at this point if there are pending
20808 			 * unresolved routes. ire_multirt_resolvable()
20809 			 * checks in O(n) that all IRE_OFFSUBNET ire
20810 			 * entries for the packet's destination and
20811 			 * flagged RTF_MULTIRT are currently resolved.
20812 			 * If some remain unresolved, we make a copy
20813 			 * of the current message. It will be used
20814 			 * to initiate additional route resolutions.
20815 			 */
20816 			multirt_need_resolve =
20817 			    ire_multirt_need_resolve(ire->ire_addr,
20818 			    msg_getlabel(first_mp), ipst);
20819 			ip2dbg(("ip_wput[TCP]: ire %p, "
20820 			    "multirt_need_resolve %d, first_mp %p\n",
20821 			    (void *)ire, multirt_need_resolve,
20822 			    (void *)first_mp));
20823 			if (multirt_need_resolve) {
20824 				copy_mp = copymsg(first_mp);
20825 				if (copy_mp != NULL) {
20826 					MULTIRT_DEBUG_TAG(copy_mp);
20827 				}
20828 			}
20829 		}
20830 
20831 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20832 
20833 		/*
20834 		 * Try to resolve another multiroute if
20835 		 * ire_multirt_need_resolve() deemed it necessary.
20836 		 */
20837 		if (copy_mp != NULL)
20838 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20839 		if (need_decref)
20840 			CONN_DEC_REF(connp);
20841 		return;
20842 	}
20843 
20844 	/*
20845 	 * Access to conn_ire_cache. (protected by conn_lock)
20846 	 *
20847 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20848 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20849 	 * send a packet or two with the IRE_CACHE that is going away.
20850 	 * Access to the ire requires an ire refhold on the ire prior to
20851 	 * its use since an interface unplumb thread may delete the cached
20852 	 * ire and release the refhold at any time.
20853 	 *
20854 	 * Caching an ire in the conn_ire_cache
20855 	 *
20856 	 * o Caching an ire pointer in the conn requires a strict check for
20857 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20858 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20859 	 * in the conn is done after making sure under the bucket lock that the
20860 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20861 	 * caching an ire after the unplumb thread has cleaned up the conn.
20862 	 * If the conn does not send a packet subsequently the unplumb thread
20863 	 * will be hanging waiting for the ire count to drop to zero.
20864 	 *
20865 	 * o We also need to atomically test for a null conn_ire_cache and
20866 	 * set the conn_ire_cache under the the protection of the conn_lock
20867 	 * to avoid races among concurrent threads trying to simultaneously
20868 	 * cache an ire in the conn_ire_cache.
20869 	 */
20870 	mutex_enter(&connp->conn_lock);
20871 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20872 
20873 	if (ire != NULL && ire->ire_addr == dst &&
20874 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20875 
20876 		IRE_REFHOLD(ire);
20877 		mutex_exit(&connp->conn_lock);
20878 
20879 	} else {
20880 		boolean_t cached = B_FALSE;
20881 		connp->conn_ire_cache = NULL;
20882 		mutex_exit(&connp->conn_lock);
20883 		/* Release the old ire */
20884 		if (ire != NULL && sctp_ire == NULL)
20885 			IRE_REFRELE_NOTR(ire);
20886 
20887 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20888 		if (ire == NULL)
20889 			goto noirefound;
20890 		IRE_REFHOLD_NOTR(ire);
20891 
20892 		mutex_enter(&connp->conn_lock);
20893 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20894 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20895 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20896 				if (connp->conn_ulp == IPPROTO_TCP)
20897 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20898 				connp->conn_ire_cache = ire;
20899 				cached = B_TRUE;
20900 			}
20901 			rw_exit(&ire->ire_bucket->irb_lock);
20902 		}
20903 		mutex_exit(&connp->conn_lock);
20904 
20905 		/*
20906 		 * We can continue to use the ire but since it was
20907 		 * not cached, we should drop the extra reference.
20908 		 */
20909 		if (!cached)
20910 			IRE_REFRELE_NOTR(ire);
20911 	}
20912 
20913 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20914 	    "ip_wput_end: q %p (%S)", q, "end");
20915 
20916 	/*
20917 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20918 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20919 	 */
20920 	if (ire->ire_flags & RTF_MULTIRT) {
20921 		/*
20922 		 * Force the TTL of multirouted packets if required.
20923 		 * The TTL of such packets is bounded by the
20924 		 * ip_multirt_ttl ndd variable.
20925 		 */
20926 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20927 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20928 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20929 			    "(was %d), dst 0x%08x\n",
20930 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20931 			    ntohl(ire->ire_addr)));
20932 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20933 		}
20934 
20935 		/*
20936 		 * At this point, we check to see if there are any pending
20937 		 * unresolved routes. ire_multirt_resolvable()
20938 		 * checks in O(n) that all IRE_OFFSUBNET ire
20939 		 * entries for the packet's destination and
20940 		 * flagged RTF_MULTIRT are currently resolved.
20941 		 * If some remain unresolved, we make a copy
20942 		 * of the current message. It will be used
20943 		 * to initiate additional route resolutions.
20944 		 */
20945 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20946 		    msg_getlabel(first_mp), ipst);
20947 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20948 		    "multirt_need_resolve %d, first_mp %p\n",
20949 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20950 		if (multirt_need_resolve) {
20951 			copy_mp = copymsg(first_mp);
20952 			if (copy_mp != NULL) {
20953 				MULTIRT_DEBUG_TAG(copy_mp);
20954 			}
20955 		}
20956 	}
20957 
20958 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20959 
20960 	/*
20961 	 * Try to resolve another multiroute if
20962 	 * ire_multirt_resolvable() deemed it necessary
20963 	 */
20964 	if (copy_mp != NULL)
20965 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20966 	if (need_decref)
20967 		CONN_DEC_REF(connp);
20968 	return;
20969 
20970 qnext:
20971 	/*
20972 	 * Upper Level Protocols pass down complete IP datagrams
20973 	 * as M_DATA messages.	Everything else is a sideshow.
20974 	 *
20975 	 * 1) We could be re-entering ip_wput because of ip_neworute
20976 	 *    in which case we could have a IPSEC_OUT message. We
20977 	 *    need to pass through ip_wput like other datagrams and
20978 	 *    hence cannot branch to ip_wput_nondata.
20979 	 *
20980 	 * 2) ARP, AH, ESP, and other clients who are on the module
20981 	 *    instance of IP stream, give us something to deal with.
20982 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20983 	 *
20984 	 * 3) ICMP replies also could come here.
20985 	 */
20986 	ipst = ILLQ_TO_IPST(q);
20987 
20988 	if (DB_TYPE(mp) != M_DATA) {
20989 notdata:
20990 		if (DB_TYPE(mp) == M_CTL) {
20991 			/*
20992 			 * M_CTL messages are used by ARP, AH and ESP to
20993 			 * communicate with IP. We deal with IPSEC_IN and
20994 			 * IPSEC_OUT here. ip_wput_nondata handles other
20995 			 * cases.
20996 			 */
20997 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20998 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20999 				first_mp = mp->b_cont;
21000 				first_mp->b_flag &= ~MSGHASREF;
21001 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
21002 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
21003 				CONN_DEC_REF(connp);
21004 				connp = NULL;
21005 			}
21006 			if (ii->ipsec_info_type == IPSEC_IN) {
21007 				/*
21008 				 * Either this message goes back to
21009 				 * IPsec for further processing or to
21010 				 * ULP after policy checks.
21011 				 */
21012 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
21013 				return;
21014 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
21015 				io = (ipsec_out_t *)ii;
21016 				if (io->ipsec_out_proc_begin) {
21017 					/*
21018 					 * IPsec processing has already started.
21019 					 * Complete it.
21020 					 * IPQoS notes: We don't care what is
21021 					 * in ipsec_out_ill_index since this
21022 					 * won't be processed for IPQoS policies
21023 					 * in ipsec_out_process.
21024 					 */
21025 					ipsec_out_process(q, mp, NULL,
21026 					    io->ipsec_out_ill_index);
21027 					return;
21028 				} else {
21029 					connp = (q->q_next != NULL) ?
21030 					    NULL : Q_TO_CONN(q);
21031 					first_mp = mp;
21032 					mp = mp->b_cont;
21033 					mctl_present = B_TRUE;
21034 				}
21035 				zoneid = io->ipsec_out_zoneid;
21036 				ASSERT(zoneid != ALL_ZONES);
21037 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
21038 				/*
21039 				 * It's an IPsec control message requesting
21040 				 * an SADB update to be sent to the IPsec
21041 				 * hardware acceleration capable ills.
21042 				 */
21043 				ipsec_ctl_t *ipsec_ctl =
21044 				    (ipsec_ctl_t *)mp->b_rptr;
21045 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
21046 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
21047 				mblk_t *cmp = mp->b_cont;
21048 
21049 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
21050 				ASSERT(cmp != NULL);
21051 
21052 				freeb(mp);
21053 				ill_ipsec_capab_send_all(satype, cmp, sa,
21054 				    ipst->ips_netstack);
21055 				return;
21056 			} else {
21057 				/*
21058 				 * This must be ARP or special TSOL signaling.
21059 				 */
21060 				ip_wput_nondata(NULL, q, mp, NULL);
21061 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21062 				    "ip_wput_end: q %p (%S)", q, "nondata");
21063 				return;
21064 			}
21065 		} else {
21066 			/*
21067 			 * This must be non-(ARP/AH/ESP) messages.
21068 			 */
21069 			ASSERT(!need_decref);
21070 			ip_wput_nondata(NULL, q, mp, NULL);
21071 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21072 			    "ip_wput_end: q %p (%S)", q, "nondata");
21073 			return;
21074 		}
21075 	} else {
21076 		first_mp = mp;
21077 		mctl_present = B_FALSE;
21078 	}
21079 
21080 	ASSERT(first_mp != NULL);
21081 
21082 	if (mctl_present) {
21083 		io = (ipsec_out_t *)first_mp->b_rptr;
21084 		if (io->ipsec_out_ip_nexthop) {
21085 			/*
21086 			 * We may have lost the conn context if we are
21087 			 * coming here from ip_newroute(). Copy the
21088 			 * nexthop information.
21089 			 */
21090 			ip_nexthop = B_TRUE;
21091 			nexthop_addr = io->ipsec_out_nexthop_addr;
21092 
21093 			ipha = (ipha_t *)mp->b_rptr;
21094 			dst = ipha->ipha_dst;
21095 			goto send_from_ill;
21096 		}
21097 	}
21098 
21099 	ASSERT(xmit_ill == NULL);
21100 
21101 	/* We have a complete IP datagram heading outbound. */
21102 	ipha = (ipha_t *)mp->b_rptr;
21103 
21104 #ifndef SPEED_BEFORE_SAFETY
21105 	/*
21106 	 * Make sure we have a full-word aligned message and that at least
21107 	 * a simple IP header is accessible in the first message.  If not,
21108 	 * try a pullup.  For labeled systems we need to always take this
21109 	 * path as M_CTLs are "notdata" but have trailing data to process.
21110 	 */
21111 	if (!OK_32PTR(rptr) ||
21112 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21113 hdrtoosmall:
21114 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21115 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21116 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21117 			if (first_mp == NULL)
21118 				first_mp = mp;
21119 			goto discard_pkt;
21120 		}
21121 
21122 		/* This function assumes that mp points to an IPv4 packet. */
21123 		if (is_system_labeled() &&
21124 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21125 		    (connp == NULL || !connp->conn_ulp_labeled)) {
21126 			cred_t	*credp;
21127 			pid_t	pid;
21128 
21129 			if (connp != NULL) {
21130 				credp = BEST_CRED(mp, connp, &pid);
21131 				err = tsol_check_label(credp, &mp,
21132 				    connp->conn_mac_exempt, ipst, pid);
21133 			} else if ((credp = msg_getcred(mp, &pid)) != NULL) {
21134 				err = tsol_check_label(credp, &mp,
21135 				    B_FALSE, ipst, pid);
21136 			}
21137 			ipha = (ipha_t *)mp->b_rptr;
21138 			if (mctl_present)
21139 				first_mp->b_cont = mp;
21140 			else
21141 				first_mp = mp;
21142 			if (err != 0) {
21143 				if (err == EINVAL)
21144 					goto icmp_parameter_problem;
21145 				ip2dbg(("ip_wput: label check failed (%d)\n",
21146 				    err));
21147 				goto discard_pkt;
21148 			}
21149 		}
21150 
21151 		ipha = (ipha_t *)mp->b_rptr;
21152 		if (first_mp == NULL) {
21153 			ASSERT(xmit_ill == NULL);
21154 			/*
21155 			 * If we got here because of "goto hdrtoosmall"
21156 			 * We need to attach a IPSEC_OUT.
21157 			 */
21158 			if (connp->conn_out_enforce_policy) {
21159 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21160 				    NULL, ipha->ipha_protocol,
21161 				    ipst->ips_netstack)) == NULL)) {
21162 					BUMP_MIB(&ipst->ips_ip_mib,
21163 					    ipIfStatsOutDiscards);
21164 					if (need_decref)
21165 						CONN_DEC_REF(connp);
21166 					return;
21167 				} else {
21168 					ASSERT(mp->b_datap->db_type == M_CTL);
21169 					first_mp = mp;
21170 					mp = mp->b_cont;
21171 					mctl_present = B_TRUE;
21172 				}
21173 			} else {
21174 				first_mp = mp;
21175 				mctl_present = B_FALSE;
21176 			}
21177 		}
21178 	}
21179 #endif
21180 
21181 	/* Most of the code below is written for speed, not readability */
21182 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21183 
21184 	/*
21185 	 * If ip_newroute() fails, we're going to need a full
21186 	 * header for the icmp wraparound.
21187 	 */
21188 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21189 		uint_t	v_hlen;
21190 version_hdrlen_check:
21191 		ASSERT(first_mp != NULL);
21192 		v_hlen = V_HLEN;
21193 		/*
21194 		 * siphon off IPv6 packets coming down from transport
21195 		 * layer modules here.
21196 		 * Note: high-order bit carries NUD reachability confirmation
21197 		 */
21198 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21199 			/*
21200 			 * FIXME: assume that callers of ip_output* call
21201 			 * the right version?
21202 			 */
21203 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21204 			ASSERT(xmit_ill == NULL);
21205 			if (need_decref)
21206 				mp->b_flag |= MSGHASREF;
21207 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21208 			return;
21209 		}
21210 
21211 		if ((v_hlen >> 4) != IP_VERSION) {
21212 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21213 			    "ip_wput_end: q %p (%S)", q, "badvers");
21214 			goto discard_pkt;
21215 		}
21216 		/*
21217 		 * Is the header length at least 20 bytes?
21218 		 *
21219 		 * Are there enough bytes accessible in the header?  If
21220 		 * not, try a pullup.
21221 		 */
21222 		v_hlen &= 0xF;
21223 		v_hlen <<= 2;
21224 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21225 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21226 			    "ip_wput_end: q %p (%S)", q, "badlen");
21227 			goto discard_pkt;
21228 		}
21229 		if (v_hlen > (mp->b_wptr - rptr)) {
21230 			if (!pullupmsg(mp, v_hlen)) {
21231 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21232 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21233 				goto discard_pkt;
21234 			}
21235 			ipha = (ipha_t *)mp->b_rptr;
21236 		}
21237 		/*
21238 		 * Move first entry from any source route into ipha_dst and
21239 		 * verify the options
21240 		 */
21241 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21242 		    zoneid, ipst)) {
21243 			ASSERT(xmit_ill == NULL);
21244 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21245 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21246 			    "ip_wput_end: q %p (%S)", q, "badopts");
21247 			if (need_decref)
21248 				CONN_DEC_REF(connp);
21249 			return;
21250 		}
21251 	}
21252 	dst = ipha->ipha_dst;
21253 
21254 	/*
21255 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21256 	 * we have to run the packet through ip_newroute which will take
21257 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21258 	 * a resolver, or assigning a default gateway, etc.
21259 	 */
21260 	if (CLASSD(dst)) {
21261 		ipif_t	*ipif;
21262 		uint32_t setsrc = 0;
21263 
21264 multicast:
21265 		ASSERT(first_mp != NULL);
21266 		ip2dbg(("ip_wput: CLASSD\n"));
21267 		if (connp == NULL) {
21268 			/*
21269 			 * Use the first good ipif on the ill.
21270 			 * XXX Should this ever happen? (Appears
21271 			 * to show up with just ppp and no ethernet due
21272 			 * to in.rdisc.)
21273 			 * However, ire_send should be able to
21274 			 * call ip_wput_ire directly.
21275 			 *
21276 			 * XXX Also, this can happen for ICMP and other packets
21277 			 * with multicast source addresses.  Perhaps we should
21278 			 * fix things so that we drop the packet in question,
21279 			 * but for now, just run with it.
21280 			 */
21281 			ill_t *ill = (ill_t *)q->q_ptr;
21282 
21283 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21284 			if (ipif == NULL) {
21285 				if (need_decref)
21286 					CONN_DEC_REF(connp);
21287 				freemsg(first_mp);
21288 				return;
21289 			}
21290 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21291 			    ntohl(dst), ill->ill_name));
21292 		} else {
21293 			/*
21294 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21295 			 * and IP_MULTICAST_IF.  The block comment above this
21296 			 * function explains the locking mechanism used here.
21297 			 */
21298 			if (xmit_ill == NULL) {
21299 				xmit_ill = conn_get_held_ill(connp,
21300 				    &connp->conn_outgoing_ill, &err);
21301 				if (err == ILL_LOOKUP_FAILED) {
21302 					ip1dbg(("ip_wput: No ill for "
21303 					    "IP_BOUND_IF\n"));
21304 					BUMP_MIB(&ipst->ips_ip_mib,
21305 					    ipIfStatsOutNoRoutes);
21306 					goto drop_pkt;
21307 				}
21308 			}
21309 
21310 			if (xmit_ill == NULL) {
21311 				ipif = conn_get_held_ipif(connp,
21312 				    &connp->conn_multicast_ipif, &err);
21313 				if (err == IPIF_LOOKUP_FAILED) {
21314 					ip1dbg(("ip_wput: No ipif for "
21315 					    "multicast\n"));
21316 					BUMP_MIB(&ipst->ips_ip_mib,
21317 					    ipIfStatsOutNoRoutes);
21318 					goto drop_pkt;
21319 				}
21320 			}
21321 			if (xmit_ill != NULL) {
21322 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21323 				if (ipif == NULL) {
21324 					ip1dbg(("ip_wput: No ipif for "
21325 					    "xmit_ill\n"));
21326 					BUMP_MIB(&ipst->ips_ip_mib,
21327 					    ipIfStatsOutNoRoutes);
21328 					goto drop_pkt;
21329 				}
21330 			} else if (ipif == NULL || ipif->ipif_isv6) {
21331 				/*
21332 				 * We must do this ipif determination here
21333 				 * else we could pass through ip_newroute
21334 				 * and come back here without the conn context.
21335 				 *
21336 				 * Note: we do late binding i.e. we bind to
21337 				 * the interface when the first packet is sent.
21338 				 * For performance reasons we do not rebind on
21339 				 * each packet but keep the binding until the
21340 				 * next IP_MULTICAST_IF option.
21341 				 *
21342 				 * conn_multicast_{ipif,ill} are shared between
21343 				 * IPv4 and IPv6 and AF_INET6 sockets can
21344 				 * send both IPv4 and IPv6 packets. Hence
21345 				 * we have to check that "isv6" matches above.
21346 				 */
21347 				if (ipif != NULL)
21348 					ipif_refrele(ipif);
21349 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21350 				if (ipif == NULL) {
21351 					ip1dbg(("ip_wput: No ipif for "
21352 					    "multicast\n"));
21353 					BUMP_MIB(&ipst->ips_ip_mib,
21354 					    ipIfStatsOutNoRoutes);
21355 					goto drop_pkt;
21356 				}
21357 				err = conn_set_held_ipif(connp,
21358 				    &connp->conn_multicast_ipif, ipif);
21359 				if (err == IPIF_LOOKUP_FAILED) {
21360 					ipif_refrele(ipif);
21361 					ip1dbg(("ip_wput: No ipif for "
21362 					    "multicast\n"));
21363 					BUMP_MIB(&ipst->ips_ip_mib,
21364 					    ipIfStatsOutNoRoutes);
21365 					goto drop_pkt;
21366 				}
21367 			}
21368 		}
21369 		ASSERT(!ipif->ipif_isv6);
21370 		/*
21371 		 * As we may lose the conn by the time we reach ip_wput_ire,
21372 		 * we copy conn_multicast_loop and conn_dontroute on to an
21373 		 * ipsec_out. In case if this datagram goes out secure,
21374 		 * we need the ill_index also. Copy that also into the
21375 		 * ipsec_out.
21376 		 */
21377 		if (mctl_present) {
21378 			io = (ipsec_out_t *)first_mp->b_rptr;
21379 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21380 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21381 		} else {
21382 			ASSERT(mp == first_mp);
21383 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21384 			    BPRI_HI)) == NULL) {
21385 				ipif_refrele(ipif);
21386 				first_mp = mp;
21387 				goto discard_pkt;
21388 			}
21389 			first_mp->b_datap->db_type = M_CTL;
21390 			first_mp->b_wptr += sizeof (ipsec_info_t);
21391 			/* ipsec_out_secure is B_FALSE now */
21392 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21393 			io = (ipsec_out_t *)first_mp->b_rptr;
21394 			io->ipsec_out_type = IPSEC_OUT;
21395 			io->ipsec_out_len = sizeof (ipsec_out_t);
21396 			io->ipsec_out_use_global_policy = B_TRUE;
21397 			io->ipsec_out_ns = ipst->ips_netstack;
21398 			first_mp->b_cont = mp;
21399 			mctl_present = B_TRUE;
21400 		}
21401 
21402 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21403 		io->ipsec_out_ill_index =
21404 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21405 
21406 		if (connp != NULL) {
21407 			io->ipsec_out_multicast_loop =
21408 			    connp->conn_multicast_loop;
21409 			io->ipsec_out_dontroute = connp->conn_dontroute;
21410 			io->ipsec_out_zoneid = connp->conn_zoneid;
21411 		}
21412 		/*
21413 		 * If the application uses IP_MULTICAST_IF with
21414 		 * different logical addresses of the same ILL, we
21415 		 * need to make sure that the soruce address of
21416 		 * the packet matches the logical IP address used
21417 		 * in the option. We do it by initializing ipha_src
21418 		 * here. This should keep IPsec also happy as
21419 		 * when we return from IPsec processing, we don't
21420 		 * have to worry about getting the right address on
21421 		 * the packet. Thus it is sufficient to look for
21422 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21423 		 * MATCH_IRE_IPIF.
21424 		 *
21425 		 * NOTE : We need to do it for non-secure case also as
21426 		 * this might go out secure if there is a global policy
21427 		 * match in ip_wput_ire.
21428 		 *
21429 		 * As we do not have the ire yet, it is possible that
21430 		 * we set the source address here and then later discover
21431 		 * that the ire implies the source address to be assigned
21432 		 * through the RTF_SETSRC flag.
21433 		 * In that case, the setsrc variable will remind us
21434 		 * that overwritting the source address by the one
21435 		 * of the RTF_SETSRC-flagged ire is allowed.
21436 		 */
21437 		if (ipha->ipha_src == INADDR_ANY &&
21438 		    (connp == NULL || !connp->conn_unspec_src)) {
21439 			ipha->ipha_src = ipif->ipif_src_addr;
21440 			setsrc = RTF_SETSRC;
21441 		}
21442 		/*
21443 		 * Find an IRE which matches the destination and the outgoing
21444 		 * queue (i.e. the outgoing interface.)
21445 		 * For loopback use a unicast IP address for
21446 		 * the ire lookup.
21447 		 */
21448 		if (IS_LOOPBACK(ipif->ipif_ill))
21449 			dst = ipif->ipif_lcl_addr;
21450 
21451 		/*
21452 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21453 		 * We don't need to lookup ire in ctable as the packet
21454 		 * needs to be sent to the destination through the specified
21455 		 * ill irrespective of ires in the cache table.
21456 		 */
21457 		ire = NULL;
21458 		if (xmit_ill == NULL) {
21459 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21460 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21461 		}
21462 
21463 		if (ire == NULL) {
21464 			/*
21465 			 * Multicast loopback and multicast forwarding is
21466 			 * done in ip_wput_ire.
21467 			 *
21468 			 * Mark this packet to make it be delivered to
21469 			 * ip_wput_ire after the new ire has been
21470 			 * created.
21471 			 *
21472 			 * The call to ip_newroute_ipif takes into account
21473 			 * the setsrc reminder. In any case, we take care
21474 			 * of the RTF_MULTIRT flag.
21475 			 */
21476 			mp->b_prev = mp->b_next = NULL;
21477 			if (xmit_ill == NULL ||
21478 			    xmit_ill->ill_ipif_up_count > 0) {
21479 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21480 				    setsrc | RTF_MULTIRT, zoneid, infop);
21481 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21482 				    "ip_wput_end: q %p (%S)", q, "noire");
21483 			} else {
21484 				freemsg(first_mp);
21485 			}
21486 			ipif_refrele(ipif);
21487 			if (xmit_ill != NULL)
21488 				ill_refrele(xmit_ill);
21489 			if (need_decref)
21490 				CONN_DEC_REF(connp);
21491 			return;
21492 		}
21493 
21494 		ipif_refrele(ipif);
21495 		ipif = NULL;
21496 		ASSERT(xmit_ill == NULL);
21497 
21498 		/*
21499 		 * Honor the RTF_SETSRC flag for multicast packets,
21500 		 * if allowed by the setsrc reminder.
21501 		 */
21502 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21503 			ipha->ipha_src = ire->ire_src_addr;
21504 		}
21505 
21506 		/*
21507 		 * Unconditionally force the TTL to 1 for
21508 		 * multirouted multicast packets:
21509 		 * multirouted multicast should not cross
21510 		 * multicast routers.
21511 		 */
21512 		if (ire->ire_flags & RTF_MULTIRT) {
21513 			if (ipha->ipha_ttl > 1) {
21514 				ip2dbg(("ip_wput: forcing multicast "
21515 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21516 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21517 				ipha->ipha_ttl = 1;
21518 			}
21519 		}
21520 	} else {
21521 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21522 		if ((ire != NULL) && (ire->ire_type &
21523 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21524 			ignore_dontroute = B_TRUE;
21525 			ignore_nexthop = B_TRUE;
21526 		}
21527 		if (ire != NULL) {
21528 			ire_refrele(ire);
21529 			ire = NULL;
21530 		}
21531 		/*
21532 		 * Guard against coming in from arp in which case conn is NULL.
21533 		 * Also guard against non M_DATA with dontroute set but
21534 		 * destined to local, loopback or broadcast addresses.
21535 		 */
21536 		if (connp != NULL && connp->conn_dontroute &&
21537 		    !ignore_dontroute) {
21538 dontroute:
21539 			/*
21540 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21541 			 * routing protocols from seeing false direct
21542 			 * connectivity.
21543 			 */
21544 			ipha->ipha_ttl = 1;
21545 			/* If suitable ipif not found, drop packet */
21546 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21547 			if (dst_ipif == NULL) {
21548 noroute:
21549 				ip1dbg(("ip_wput: no route for dst using"
21550 				    " SO_DONTROUTE\n"));
21551 				BUMP_MIB(&ipst->ips_ip_mib,
21552 				    ipIfStatsOutNoRoutes);
21553 				mp->b_prev = mp->b_next = NULL;
21554 				if (first_mp == NULL)
21555 					first_mp = mp;
21556 				goto drop_pkt;
21557 			} else {
21558 				/*
21559 				 * If suitable ipif has been found, set
21560 				 * xmit_ill to the corresponding
21561 				 * ipif_ill because we'll be using the
21562 				 * send_from_ill logic below.
21563 				 */
21564 				ASSERT(xmit_ill == NULL);
21565 				xmit_ill = dst_ipif->ipif_ill;
21566 				mutex_enter(&xmit_ill->ill_lock);
21567 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21568 					mutex_exit(&xmit_ill->ill_lock);
21569 					xmit_ill = NULL;
21570 					ipif_refrele(dst_ipif);
21571 					goto noroute;
21572 				}
21573 				ill_refhold_locked(xmit_ill);
21574 				mutex_exit(&xmit_ill->ill_lock);
21575 				ipif_refrele(dst_ipif);
21576 			}
21577 		}
21578 
21579 send_from_ill:
21580 		if (xmit_ill != NULL) {
21581 			ipif_t *ipif;
21582 
21583 			/*
21584 			 * Mark this packet as originated locally
21585 			 */
21586 			mp->b_prev = mp->b_next = NULL;
21587 
21588 			/*
21589 			 * Could be SO_DONTROUTE case also.
21590 			 * Verify that at least one ipif is up on the ill.
21591 			 */
21592 			if (xmit_ill->ill_ipif_up_count == 0) {
21593 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21594 				    xmit_ill->ill_name));
21595 				goto drop_pkt;
21596 			}
21597 
21598 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21599 			if (ipif == NULL) {
21600 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21601 				    xmit_ill->ill_name));
21602 				goto drop_pkt;
21603 			}
21604 
21605 			match_flags = 0;
21606 			if (IS_UNDER_IPMP(xmit_ill))
21607 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21608 
21609 			/*
21610 			 * Look for a ire that is part of the group,
21611 			 * if found use it else call ip_newroute_ipif.
21612 			 * IPCL_ZONEID is not used for matching because
21613 			 * IP_ALLZONES option is valid only when the
21614 			 * ill is accessible from all zones i.e has a
21615 			 * valid ipif in all zones.
21616 			 */
21617 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21618 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21619 			    msg_getlabel(mp), match_flags, ipst);
21620 			/*
21621 			 * If an ire exists use it or else create
21622 			 * an ire but don't add it to the cache.
21623 			 * Adding an ire may cause issues with
21624 			 * asymmetric routing.
21625 			 * In case of multiroute always act as if
21626 			 * ire does not exist.
21627 			 */
21628 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21629 				if (ire != NULL)
21630 					ire_refrele(ire);
21631 				ip_newroute_ipif(q, first_mp, ipif,
21632 				    dst, connp, 0, zoneid, infop);
21633 				ipif_refrele(ipif);
21634 				ip1dbg(("ip_output: xmit_ill via %s\n",
21635 				    xmit_ill->ill_name));
21636 				ill_refrele(xmit_ill);
21637 				if (need_decref)
21638 					CONN_DEC_REF(connp);
21639 				return;
21640 			}
21641 			ipif_refrele(ipif);
21642 		} else if (ip_nexthop || (connp != NULL &&
21643 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21644 			if (!ip_nexthop) {
21645 				ip_nexthop = B_TRUE;
21646 				nexthop_addr = connp->conn_nexthop_v4;
21647 			}
21648 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21649 			    MATCH_IRE_GW;
21650 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21651 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21652 		} else {
21653 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21654 			    ipst);
21655 		}
21656 		if (!ire) {
21657 			if (ip_nexthop && !ignore_nexthop) {
21658 				if (mctl_present) {
21659 					io = (ipsec_out_t *)first_mp->b_rptr;
21660 					ASSERT(first_mp->b_datap->db_type ==
21661 					    M_CTL);
21662 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21663 				} else {
21664 					ASSERT(mp == first_mp);
21665 					first_mp = allocb(
21666 					    sizeof (ipsec_info_t), BPRI_HI);
21667 					if (first_mp == NULL) {
21668 						first_mp = mp;
21669 						goto discard_pkt;
21670 					}
21671 					first_mp->b_datap->db_type = M_CTL;
21672 					first_mp->b_wptr +=
21673 					    sizeof (ipsec_info_t);
21674 					/* ipsec_out_secure is B_FALSE now */
21675 					bzero(first_mp->b_rptr,
21676 					    sizeof (ipsec_info_t));
21677 					io = (ipsec_out_t *)first_mp->b_rptr;
21678 					io->ipsec_out_type = IPSEC_OUT;
21679 					io->ipsec_out_len =
21680 					    sizeof (ipsec_out_t);
21681 					io->ipsec_out_use_global_policy =
21682 					    B_TRUE;
21683 					io->ipsec_out_ns = ipst->ips_netstack;
21684 					first_mp->b_cont = mp;
21685 					mctl_present = B_TRUE;
21686 				}
21687 				io->ipsec_out_ip_nexthop = ip_nexthop;
21688 				io->ipsec_out_nexthop_addr = nexthop_addr;
21689 			}
21690 noirefound:
21691 			/*
21692 			 * Mark this packet as having originated on
21693 			 * this machine.  This will be noted in
21694 			 * ire_add_then_send, which needs to know
21695 			 * whether to run it back through ip_wput or
21696 			 * ip_rput following successful resolution.
21697 			 */
21698 			mp->b_prev = NULL;
21699 			mp->b_next = NULL;
21700 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21701 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21702 			    "ip_wput_end: q %p (%S)", q, "newroute");
21703 			if (xmit_ill != NULL)
21704 				ill_refrele(xmit_ill);
21705 			if (need_decref)
21706 				CONN_DEC_REF(connp);
21707 			return;
21708 		}
21709 	}
21710 
21711 	/* We now know where we are going with it. */
21712 
21713 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21714 	    "ip_wput_end: q %p (%S)", q, "end");
21715 
21716 	/*
21717 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21718 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21719 	 */
21720 	if (ire->ire_flags & RTF_MULTIRT) {
21721 		/*
21722 		 * Force the TTL of multirouted packets if required.
21723 		 * The TTL of such packets is bounded by the
21724 		 * ip_multirt_ttl ndd variable.
21725 		 */
21726 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21727 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21728 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21729 			    "(was %d), dst 0x%08x\n",
21730 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21731 			    ntohl(ire->ire_addr)));
21732 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21733 		}
21734 		/*
21735 		 * At this point, we check to see if there are any pending
21736 		 * unresolved routes. ire_multirt_resolvable()
21737 		 * checks in O(n) that all IRE_OFFSUBNET ire
21738 		 * entries for the packet's destination and
21739 		 * flagged RTF_MULTIRT are currently resolved.
21740 		 * If some remain unresolved, we make a copy
21741 		 * of the current message. It will be used
21742 		 * to initiate additional route resolutions.
21743 		 */
21744 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21745 		    msg_getlabel(first_mp), ipst);
21746 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21747 		    "multirt_need_resolve %d, first_mp %p\n",
21748 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21749 		if (multirt_need_resolve) {
21750 			copy_mp = copymsg(first_mp);
21751 			if (copy_mp != NULL) {
21752 				MULTIRT_DEBUG_TAG(copy_mp);
21753 			}
21754 		}
21755 	}
21756 
21757 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21758 	/*
21759 	 * Try to resolve another multiroute if
21760 	 * ire_multirt_resolvable() deemed it necessary.
21761 	 * At this point, we need to distinguish
21762 	 * multicasts from other packets. For multicasts,
21763 	 * we call ip_newroute_ipif() and request that both
21764 	 * multirouting and setsrc flags are checked.
21765 	 */
21766 	if (copy_mp != NULL) {
21767 		if (CLASSD(dst)) {
21768 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21769 			if (ipif) {
21770 				ASSERT(infop->ip_opt_ill_index == 0);
21771 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21772 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21773 				ipif_refrele(ipif);
21774 			} else {
21775 				MULTIRT_DEBUG_UNTAG(copy_mp);
21776 				freemsg(copy_mp);
21777 				copy_mp = NULL;
21778 			}
21779 		} else {
21780 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21781 		}
21782 	}
21783 	if (xmit_ill != NULL)
21784 		ill_refrele(xmit_ill);
21785 	if (need_decref)
21786 		CONN_DEC_REF(connp);
21787 	return;
21788 
21789 icmp_parameter_problem:
21790 	/* could not have originated externally */
21791 	ASSERT(mp->b_prev == NULL);
21792 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21793 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21794 		/* it's the IP header length that's in trouble */
21795 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21796 		first_mp = NULL;
21797 	}
21798 
21799 discard_pkt:
21800 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21801 drop_pkt:
21802 	ip1dbg(("ip_wput: dropped packet\n"));
21803 	if (ire != NULL)
21804 		ire_refrele(ire);
21805 	if (need_decref)
21806 		CONN_DEC_REF(connp);
21807 	freemsg(first_mp);
21808 	if (xmit_ill != NULL)
21809 		ill_refrele(xmit_ill);
21810 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21811 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21812 }
21813 
21814 /*
21815  * If this is a conn_t queue, then we pass in the conn. This includes the
21816  * zoneid.
21817  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21818  * in which case we use the global zoneid since those are all part of
21819  * the global zone.
21820  */
21821 void
21822 ip_wput(queue_t *q, mblk_t *mp)
21823 {
21824 	if (CONN_Q(q))
21825 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21826 	else
21827 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21828 }
21829 
21830 /*
21831  *
21832  * The following rules must be observed when accessing any ipif or ill
21833  * that has been cached in the conn. Typically conn_outgoing_ill,
21834  * conn_multicast_ipif and conn_multicast_ill.
21835  *
21836  * Access: The ipif or ill pointed to from the conn can be accessed under
21837  * the protection of the conn_lock or after it has been refheld under the
21838  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21839  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21840  * The reason for this is that a concurrent unplumb could actually be
21841  * cleaning up these cached pointers by walking the conns and might have
21842  * finished cleaning up the conn in question. The macros check that an
21843  * unplumb has not yet started on the ipif or ill.
21844  *
21845  * Caching: An ipif or ill pointer may be cached in the conn only after
21846  * making sure that an unplumb has not started. So the caching is done
21847  * while holding both the conn_lock and the ill_lock and after using the
21848  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21849  * flag before starting the cleanup of conns.
21850  *
21851  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21852  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21853  * or a reference to the ipif or a reference to an ire that references the
21854  * ipif. An ipif only changes its ill when migrating from an underlying ill
21855  * to an IPMP ill in ipif_up().
21856  */
21857 ipif_t *
21858 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21859 {
21860 	ipif_t	*ipif;
21861 	ill_t	*ill;
21862 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21863 
21864 	*err = 0;
21865 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21866 	mutex_enter(&connp->conn_lock);
21867 	ipif = *ipifp;
21868 	if (ipif != NULL) {
21869 		ill = ipif->ipif_ill;
21870 		mutex_enter(&ill->ill_lock);
21871 		if (IPIF_CAN_LOOKUP(ipif)) {
21872 			ipif_refhold_locked(ipif);
21873 			mutex_exit(&ill->ill_lock);
21874 			mutex_exit(&connp->conn_lock);
21875 			rw_exit(&ipst->ips_ill_g_lock);
21876 			return (ipif);
21877 		} else {
21878 			*err = IPIF_LOOKUP_FAILED;
21879 		}
21880 		mutex_exit(&ill->ill_lock);
21881 	}
21882 	mutex_exit(&connp->conn_lock);
21883 	rw_exit(&ipst->ips_ill_g_lock);
21884 	return (NULL);
21885 }
21886 
21887 ill_t *
21888 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21889 {
21890 	ill_t	*ill;
21891 
21892 	*err = 0;
21893 	mutex_enter(&connp->conn_lock);
21894 	ill = *illp;
21895 	if (ill != NULL) {
21896 		mutex_enter(&ill->ill_lock);
21897 		if (ILL_CAN_LOOKUP(ill)) {
21898 			ill_refhold_locked(ill);
21899 			mutex_exit(&ill->ill_lock);
21900 			mutex_exit(&connp->conn_lock);
21901 			return (ill);
21902 		} else {
21903 			*err = ILL_LOOKUP_FAILED;
21904 		}
21905 		mutex_exit(&ill->ill_lock);
21906 	}
21907 	mutex_exit(&connp->conn_lock);
21908 	return (NULL);
21909 }
21910 
21911 static int
21912 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21913 {
21914 	ill_t	*ill;
21915 
21916 	ill = ipif->ipif_ill;
21917 	mutex_enter(&connp->conn_lock);
21918 	mutex_enter(&ill->ill_lock);
21919 	if (IPIF_CAN_LOOKUP(ipif)) {
21920 		*ipifp = ipif;
21921 		mutex_exit(&ill->ill_lock);
21922 		mutex_exit(&connp->conn_lock);
21923 		return (0);
21924 	}
21925 	mutex_exit(&ill->ill_lock);
21926 	mutex_exit(&connp->conn_lock);
21927 	return (IPIF_LOOKUP_FAILED);
21928 }
21929 
21930 /*
21931  * This is called if the outbound datagram needs fragmentation.
21932  *
21933  * NOTE : This function does not ire_refrele the ire argument passed in.
21934  */
21935 static void
21936 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21937     ip_stack_t *ipst, conn_t *connp)
21938 {
21939 	ipha_t		*ipha;
21940 	mblk_t		*mp;
21941 	uint32_t	v_hlen_tos_len;
21942 	uint32_t	max_frag;
21943 	uint32_t	frag_flag;
21944 	boolean_t	dont_use;
21945 
21946 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21947 		mp = ipsec_mp->b_cont;
21948 	} else {
21949 		mp = ipsec_mp;
21950 	}
21951 
21952 	ipha = (ipha_t *)mp->b_rptr;
21953 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21954 
21955 #ifdef	_BIG_ENDIAN
21956 #define	V_HLEN	(v_hlen_tos_len >> 24)
21957 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21958 #else
21959 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21960 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21961 #endif
21962 
21963 #ifndef SPEED_BEFORE_SAFETY
21964 	/*
21965 	 * Check that ipha_length is consistent with
21966 	 * the mblk length
21967 	 */
21968 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21969 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21970 		    LENGTH, msgdsize(mp)));
21971 		freemsg(ipsec_mp);
21972 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21973 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21974 		    "packet length mismatch");
21975 		return;
21976 	}
21977 #endif
21978 	/*
21979 	 * Don't use frag_flag if pre-built packet or source
21980 	 * routed or if multicast (since multicast packets do not solicit
21981 	 * ICMP "packet too big" messages). Get the values of
21982 	 * max_frag and frag_flag atomically by acquiring the
21983 	 * ire_lock.
21984 	 */
21985 	mutex_enter(&ire->ire_lock);
21986 	max_frag = ire->ire_max_frag;
21987 	frag_flag = ire->ire_frag_flag;
21988 	mutex_exit(&ire->ire_lock);
21989 
21990 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21991 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21992 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21993 
21994 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21995 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21996 }
21997 
21998 /*
21999  * Used for deciding the MSS size for the upper layer. Thus
22000  * we need to check the outbound policy values in the conn.
22001  */
22002 int
22003 conn_ipsec_length(conn_t *connp)
22004 {
22005 	ipsec_latch_t *ipl;
22006 
22007 	ipl = connp->conn_latch;
22008 	if (ipl == NULL)
22009 		return (0);
22010 
22011 	if (ipl->ipl_out_policy == NULL)
22012 		return (0);
22013 
22014 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
22015 }
22016 
22017 /*
22018  * Returns an estimate of the IPsec headers size. This is used if
22019  * we don't want to call into IPsec to get the exact size.
22020  */
22021 int
22022 ipsec_out_extra_length(mblk_t *ipsec_mp)
22023 {
22024 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
22025 	ipsec_action_t *a;
22026 
22027 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
22028 	if (!io->ipsec_out_secure)
22029 		return (0);
22030 
22031 	a = io->ipsec_out_act;
22032 
22033 	if (a == NULL) {
22034 		ASSERT(io->ipsec_out_policy != NULL);
22035 		a = io->ipsec_out_policy->ipsp_act;
22036 	}
22037 	ASSERT(a != NULL);
22038 
22039 	return (a->ipa_ovhd);
22040 }
22041 
22042 /*
22043  * Returns an estimate of the IPsec headers size. This is used if
22044  * we don't want to call into IPsec to get the exact size.
22045  */
22046 int
22047 ipsec_in_extra_length(mblk_t *ipsec_mp)
22048 {
22049 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22050 	ipsec_action_t *a;
22051 
22052 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
22053 
22054 	a = ii->ipsec_in_action;
22055 	return (a == NULL ? 0 : a->ipa_ovhd);
22056 }
22057 
22058 /*
22059  * If there are any source route options, return the true final
22060  * destination. Otherwise, return the destination.
22061  */
22062 ipaddr_t
22063 ip_get_dst(ipha_t *ipha)
22064 {
22065 	ipoptp_t	opts;
22066 	uchar_t		*opt;
22067 	uint8_t		optval;
22068 	uint8_t		optlen;
22069 	ipaddr_t	dst;
22070 	uint32_t off;
22071 
22072 	dst = ipha->ipha_dst;
22073 
22074 	if (IS_SIMPLE_IPH(ipha))
22075 		return (dst);
22076 
22077 	for (optval = ipoptp_first(&opts, ipha);
22078 	    optval != IPOPT_EOL;
22079 	    optval = ipoptp_next(&opts)) {
22080 		opt = opts.ipoptp_cur;
22081 		optlen = opts.ipoptp_len;
22082 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22083 		switch (optval) {
22084 		case IPOPT_SSRR:
22085 		case IPOPT_LSRR:
22086 			off = opt[IPOPT_OFFSET];
22087 			/*
22088 			 * If one of the conditions is true, it means
22089 			 * end of options and dst already has the right
22090 			 * value.
22091 			 */
22092 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22093 				off = optlen - IP_ADDR_LEN;
22094 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22095 			}
22096 			return (dst);
22097 		default:
22098 			break;
22099 		}
22100 	}
22101 
22102 	return (dst);
22103 }
22104 
22105 mblk_t *
22106 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22107     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22108 {
22109 	ipsec_out_t	*io;
22110 	mblk_t		*first_mp;
22111 	boolean_t policy_present;
22112 	ip_stack_t	*ipst;
22113 	ipsec_stack_t	*ipss;
22114 
22115 	ASSERT(ire != NULL);
22116 	ipst = ire->ire_ipst;
22117 	ipss = ipst->ips_netstack->netstack_ipsec;
22118 
22119 	first_mp = mp;
22120 	if (mp->b_datap->db_type == M_CTL) {
22121 		io = (ipsec_out_t *)first_mp->b_rptr;
22122 		/*
22123 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22124 		 *
22125 		 * 1) There is per-socket policy (including cached global
22126 		 *    policy) or a policy on the IP-in-IP tunnel.
22127 		 * 2) There is no per-socket policy, but it is
22128 		 *    a multicast packet that needs to go out
22129 		 *    on a specific interface. This is the case
22130 		 *    where (ip_wput and ip_wput_multicast) attaches
22131 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22132 		 *
22133 		 * In case (2) we check with global policy to
22134 		 * see if there is a match and set the ill_index
22135 		 * appropriately so that we can lookup the ire
22136 		 * properly in ip_wput_ipsec_out.
22137 		 */
22138 
22139 		/*
22140 		 * ipsec_out_use_global_policy is set to B_FALSE
22141 		 * in ipsec_in_to_out(). Refer to that function for
22142 		 * details.
22143 		 */
22144 		if ((io->ipsec_out_latch == NULL) &&
22145 		    (io->ipsec_out_use_global_policy)) {
22146 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22147 			    ire, connp, unspec_src, zoneid));
22148 		}
22149 		if (!io->ipsec_out_secure) {
22150 			/*
22151 			 * If this is not a secure packet, drop
22152 			 * the IPSEC_OUT mp and treat it as a clear
22153 			 * packet. This happens when we are sending
22154 			 * a ICMP reply back to a clear packet. See
22155 			 * ipsec_in_to_out() for details.
22156 			 */
22157 			mp = first_mp->b_cont;
22158 			freeb(first_mp);
22159 		}
22160 		return (mp);
22161 	}
22162 	/*
22163 	 * See whether we need to attach a global policy here. We
22164 	 * don't depend on the conn (as it could be null) for deciding
22165 	 * what policy this datagram should go through because it
22166 	 * should have happened in ip_wput if there was some
22167 	 * policy. This normally happens for connections which are not
22168 	 * fully bound preventing us from caching policies in
22169 	 * ip_bind. Packets coming from the TCP listener/global queue
22170 	 * - which are non-hard_bound - could also be affected by
22171 	 * applying policy here.
22172 	 *
22173 	 * If this packet is coming from tcp global queue or listener,
22174 	 * we will be applying policy here.  This may not be *right*
22175 	 * if these packets are coming from the detached connection as
22176 	 * it could have gone in clear before. This happens only if a
22177 	 * TCP connection started when there is no policy and somebody
22178 	 * added policy before it became detached. Thus packets of the
22179 	 * detached connection could go out secure and the other end
22180 	 * would drop it because it will be expecting in clear. The
22181 	 * converse is not true i.e if somebody starts a TCP
22182 	 * connection and deletes the policy, all the packets will
22183 	 * still go out with the policy that existed before deleting
22184 	 * because ip_unbind sends up policy information which is used
22185 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22186 	 * TCP to attach a dummy IPSEC_OUT and set
22187 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22188 	 * affect performance for normal cases, we are not doing it.
22189 	 * Thus, set policy before starting any TCP connections.
22190 	 *
22191 	 * NOTE - We might apply policy even for a hard bound connection
22192 	 * - for which we cached policy in ip_bind - if somebody added
22193 	 * global policy after we inherited the policy in ip_bind.
22194 	 * This means that the packets that were going out in clear
22195 	 * previously would start going secure and hence get dropped
22196 	 * on the other side. To fix this, TCP attaches a dummy
22197 	 * ipsec_out and make sure that we don't apply global policy.
22198 	 */
22199 	if (ipha != NULL)
22200 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22201 	else
22202 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22203 	if (!policy_present)
22204 		return (mp);
22205 
22206 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22207 	    zoneid));
22208 }
22209 
22210 /*
22211  * This function does the ire_refrele of the ire passed in as the
22212  * argument. As this function looks up more ires i.e broadcast ires,
22213  * it needs to REFRELE them. Currently, for simplicity we don't
22214  * differentiate the one passed in and looked up here. We always
22215  * REFRELE.
22216  * IPQoS Notes:
22217  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22218  * IPsec packets are done in ipsec_out_process.
22219  */
22220 void
22221 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22222     zoneid_t zoneid)
22223 {
22224 	ipha_t		*ipha;
22225 #define	rptr	((uchar_t *)ipha)
22226 	queue_t		*stq;
22227 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22228 	uint32_t	v_hlen_tos_len;
22229 	uint32_t	ttl_protocol;
22230 	ipaddr_t	src;
22231 	ipaddr_t	dst;
22232 	uint32_t	cksum;
22233 	ipaddr_t	orig_src;
22234 	ire_t		*ire1;
22235 	mblk_t		*next_mp;
22236 	uint_t		hlen;
22237 	uint16_t	*up;
22238 	uint32_t	max_frag = ire->ire_max_frag;
22239 	ill_t		*ill = ire_to_ill(ire);
22240 	int		clusterwide;
22241 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22242 	int		ipsec_len;
22243 	mblk_t		*first_mp;
22244 	ipsec_out_t	*io;
22245 	boolean_t	conn_dontroute;		/* conn value for multicast */
22246 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22247 	boolean_t	multicast_forward;	/* Should we forward ? */
22248 	boolean_t	unspec_src;
22249 	ill_t		*conn_outgoing_ill = NULL;
22250 	ill_t		*ire_ill;
22251 	ill_t		*ire1_ill;
22252 	ill_t		*out_ill;
22253 	uint32_t 	ill_index = 0;
22254 	boolean_t	multirt_send = B_FALSE;
22255 	int		err;
22256 	ipxmit_state_t	pktxmit_state;
22257 	ip_stack_t	*ipst = ire->ire_ipst;
22258 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22259 
22260 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22261 	    "ip_wput_ire_start: q %p", q);
22262 
22263 	multicast_forward = B_FALSE;
22264 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22265 
22266 	if (ire->ire_flags & RTF_MULTIRT) {
22267 		/*
22268 		 * Multirouting case. The bucket where ire is stored
22269 		 * probably holds other RTF_MULTIRT flagged ire
22270 		 * to the destination. In this call to ip_wput_ire,
22271 		 * we attempt to send the packet through all
22272 		 * those ires. Thus, we first ensure that ire is the
22273 		 * first RTF_MULTIRT ire in the bucket,
22274 		 * before walking the ire list.
22275 		 */
22276 		ire_t *first_ire;
22277 		irb_t *irb = ire->ire_bucket;
22278 		ASSERT(irb != NULL);
22279 
22280 		/* Make sure we do not omit any multiroute ire. */
22281 		IRB_REFHOLD(irb);
22282 		for (first_ire = irb->irb_ire;
22283 		    first_ire != NULL;
22284 		    first_ire = first_ire->ire_next) {
22285 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22286 			    (first_ire->ire_addr == ire->ire_addr) &&
22287 			    !(first_ire->ire_marks &
22288 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22289 				break;
22290 		}
22291 
22292 		if ((first_ire != NULL) && (first_ire != ire)) {
22293 			IRE_REFHOLD(first_ire);
22294 			ire_refrele(ire);
22295 			ire = first_ire;
22296 			ill = ire_to_ill(ire);
22297 		}
22298 		IRB_REFRELE(irb);
22299 	}
22300 
22301 	/*
22302 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22303 	 * for performance we don't grab the mutexs in the fastpath
22304 	 */
22305 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22306 	    connp->conn_outgoing_ill != NULL) {
22307 		conn_outgoing_ill = conn_get_held_ill(connp,
22308 		    &connp->conn_outgoing_ill, &err);
22309 		if (err == ILL_LOOKUP_FAILED) {
22310 			ire_refrele(ire);
22311 			freemsg(mp);
22312 			return;
22313 		}
22314 	}
22315 
22316 	if (mp->b_datap->db_type != M_CTL) {
22317 		ipha = (ipha_t *)mp->b_rptr;
22318 	} else {
22319 		io = (ipsec_out_t *)mp->b_rptr;
22320 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22321 		ASSERT(zoneid == io->ipsec_out_zoneid);
22322 		ASSERT(zoneid != ALL_ZONES);
22323 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22324 		dst = ipha->ipha_dst;
22325 		/*
22326 		 * For the multicast case, ipsec_out carries conn_dontroute and
22327 		 * conn_multicast_loop as conn may not be available here. We
22328 		 * need this for multicast loopback and forwarding which is done
22329 		 * later in the code.
22330 		 */
22331 		if (CLASSD(dst)) {
22332 			conn_dontroute = io->ipsec_out_dontroute;
22333 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22334 			/*
22335 			 * If conn_dontroute is not set or conn_multicast_loop
22336 			 * is set, we need to do forwarding/loopback. For
22337 			 * datagrams from ip_wput_multicast, conn_dontroute is
22338 			 * set to B_TRUE and conn_multicast_loop is set to
22339 			 * B_FALSE so that we neither do forwarding nor
22340 			 * loopback.
22341 			 */
22342 			if (!conn_dontroute || conn_multicast_loop)
22343 				multicast_forward = B_TRUE;
22344 		}
22345 	}
22346 
22347 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22348 	    ire->ire_zoneid != ALL_ZONES) {
22349 		/*
22350 		 * When a zone sends a packet to another zone, we try to deliver
22351 		 * the packet under the same conditions as if the destination
22352 		 * was a real node on the network. To do so, we look for a
22353 		 * matching route in the forwarding table.
22354 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22355 		 * ip_newroute() does.
22356 		 * Note that IRE_LOCAL are special, since they are used
22357 		 * when the zoneid doesn't match in some cases. This means that
22358 		 * we need to handle ipha_src differently since ire_src_addr
22359 		 * belongs to the receiving zone instead of the sending zone.
22360 		 * When ip_restrict_interzone_loopback is set, then
22361 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22362 		 * for loopback between zones when the logical "Ethernet" would
22363 		 * have looped them back.
22364 		 */
22365 		ire_t *src_ire;
22366 
22367 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22368 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22369 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22370 		if (src_ire != NULL &&
22371 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22372 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22373 		    ire_local_same_lan(ire, src_ire))) {
22374 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22375 				ipha->ipha_src = src_ire->ire_src_addr;
22376 			ire_refrele(src_ire);
22377 		} else {
22378 			ire_refrele(ire);
22379 			if (conn_outgoing_ill != NULL)
22380 				ill_refrele(conn_outgoing_ill);
22381 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22382 			if (src_ire != NULL) {
22383 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22384 					ire_refrele(src_ire);
22385 					freemsg(mp);
22386 					return;
22387 				}
22388 				ire_refrele(src_ire);
22389 			}
22390 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22391 				/* Failed */
22392 				freemsg(mp);
22393 				return;
22394 			}
22395 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22396 			    ipst);
22397 			return;
22398 		}
22399 	}
22400 
22401 	if (mp->b_datap->db_type == M_CTL ||
22402 	    ipss->ipsec_outbound_v4_policy_present) {
22403 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22404 		    unspec_src, zoneid);
22405 		if (mp == NULL) {
22406 			ire_refrele(ire);
22407 			if (conn_outgoing_ill != NULL)
22408 				ill_refrele(conn_outgoing_ill);
22409 			return;
22410 		}
22411 		/*
22412 		 * Trusted Extensions supports all-zones interfaces, so
22413 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22414 		 * the global zone.
22415 		 */
22416 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22417 			io = (ipsec_out_t *)mp->b_rptr;
22418 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22419 			zoneid = io->ipsec_out_zoneid;
22420 		}
22421 	}
22422 
22423 	first_mp = mp;
22424 	ipsec_len = 0;
22425 
22426 	if (first_mp->b_datap->db_type == M_CTL) {
22427 		io = (ipsec_out_t *)first_mp->b_rptr;
22428 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22429 		mp = first_mp->b_cont;
22430 		ipsec_len = ipsec_out_extra_length(first_mp);
22431 		ASSERT(ipsec_len >= 0);
22432 		/* We already picked up the zoneid from the M_CTL above */
22433 		ASSERT(zoneid == io->ipsec_out_zoneid);
22434 		ASSERT(zoneid != ALL_ZONES);
22435 
22436 		/*
22437 		 * Drop M_CTL here if IPsec processing is not needed.
22438 		 * (Non-IPsec use of M_CTL extracted any information it
22439 		 * needed above).
22440 		 */
22441 		if (ipsec_len == 0) {
22442 			freeb(first_mp);
22443 			first_mp = mp;
22444 		}
22445 	}
22446 
22447 	/*
22448 	 * Fast path for ip_wput_ire
22449 	 */
22450 
22451 	ipha = (ipha_t *)mp->b_rptr;
22452 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22453 	dst = ipha->ipha_dst;
22454 
22455 	/*
22456 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22457 	 * if the socket is a SOCK_RAW type. The transport checksum should
22458 	 * be provided in the pre-built packet, so we don't need to compute it.
22459 	 * Also, other application set flags, like DF, should not be altered.
22460 	 * Other transport MUST pass down zero.
22461 	 */
22462 	ip_hdr_included = ipha->ipha_ident;
22463 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22464 
22465 	if (CLASSD(dst)) {
22466 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22467 		    ntohl(dst),
22468 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22469 		    ntohl(ire->ire_addr)));
22470 	}
22471 
22472 /* Macros to extract header fields from data already in registers */
22473 #ifdef	_BIG_ENDIAN
22474 #define	V_HLEN	(v_hlen_tos_len >> 24)
22475 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22476 #define	PROTO	(ttl_protocol & 0xFF)
22477 #else
22478 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22479 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22480 #define	PROTO	(ttl_protocol >> 8)
22481 #endif
22482 
22483 	orig_src = src = ipha->ipha_src;
22484 	/* (The loop back to "another" is explained down below.) */
22485 another:;
22486 	/*
22487 	 * Assign an ident value for this packet.  We assign idents on
22488 	 * a per destination basis out of the IRE.  There could be
22489 	 * other threads targeting the same destination, so we have to
22490 	 * arrange for a atomic increment.  Note that we use a 32-bit
22491 	 * atomic add because it has better performance than its
22492 	 * 16-bit sibling.
22493 	 *
22494 	 * If running in cluster mode and if the source address
22495 	 * belongs to a replicated service then vector through
22496 	 * cl_inet_ipident vector to allocate ip identifier
22497 	 * NOTE: This is a contract private interface with the
22498 	 * clustering group.
22499 	 */
22500 	clusterwide = 0;
22501 	if (cl_inet_ipident) {
22502 		ASSERT(cl_inet_isclusterwide);
22503 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22504 
22505 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22506 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22507 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22508 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22509 			    (uint8_t *)(uintptr_t)dst, NULL);
22510 			clusterwide = 1;
22511 		}
22512 	}
22513 	if (!clusterwide) {
22514 		ipha->ipha_ident =
22515 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22516 	}
22517 
22518 #ifndef _BIG_ENDIAN
22519 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22520 #endif
22521 
22522 	/*
22523 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22524 	 * This is needed to obey conn_unspec_src when packets go through
22525 	 * ip_newroute + arp.
22526 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22527 	 */
22528 	if (src == INADDR_ANY && !unspec_src) {
22529 		/*
22530 		 * Assign the appropriate source address from the IRE if none
22531 		 * was specified.
22532 		 */
22533 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22534 
22535 		src = ire->ire_src_addr;
22536 		if (connp == NULL) {
22537 			ip1dbg(("ip_wput_ire: no connp and no src "
22538 			    "address for dst 0x%x, using src 0x%x\n",
22539 			    ntohl(dst),
22540 			    ntohl(src)));
22541 		}
22542 		ipha->ipha_src = src;
22543 	}
22544 	stq = ire->ire_stq;
22545 
22546 	/*
22547 	 * We only allow ire chains for broadcasts since there will
22548 	 * be multiple IRE_CACHE entries for the same multicast
22549 	 * address (one per ipif).
22550 	 */
22551 	next_mp = NULL;
22552 
22553 	/* broadcast packet */
22554 	if (ire->ire_type == IRE_BROADCAST)
22555 		goto broadcast;
22556 
22557 	/* loopback ? */
22558 	if (stq == NULL)
22559 		goto nullstq;
22560 
22561 	/* The ill_index for outbound ILL */
22562 	ill_index = Q_TO_INDEX(stq);
22563 
22564 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22565 	ttl_protocol = ((uint16_t *)ipha)[4];
22566 
22567 	/* pseudo checksum (do it in parts for IP header checksum) */
22568 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22569 
22570 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22571 		queue_t *dev_q = stq->q_next;
22572 
22573 		/*
22574 		 * For DIRECT_CAPABLE, we do flow control at
22575 		 * the time of sending the packet. See
22576 		 * ILL_SEND_TX().
22577 		 */
22578 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22579 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22580 			goto blocked;
22581 
22582 		if ((PROTO == IPPROTO_UDP) &&
22583 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22584 			hlen = (V_HLEN & 0xF) << 2;
22585 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22586 			if (*up != 0) {
22587 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22588 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22589 				/* Software checksum? */
22590 				if (DB_CKSUMFLAGS(mp) == 0) {
22591 					IP_STAT(ipst, ip_out_sw_cksum);
22592 					IP_STAT_UPDATE(ipst,
22593 					    ip_udp_out_sw_cksum_bytes,
22594 					    LENGTH - hlen);
22595 				}
22596 			}
22597 		}
22598 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22599 		hlen = (V_HLEN & 0xF) << 2;
22600 		if (PROTO == IPPROTO_TCP) {
22601 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22602 			/*
22603 			 * The packet header is processed once and for all, even
22604 			 * in the multirouting case. We disable hardware
22605 			 * checksum if the packet is multirouted, as it will be
22606 			 * replicated via several interfaces, and not all of
22607 			 * them may have this capability.
22608 			 */
22609 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22610 			    LENGTH, max_frag, ipsec_len, cksum);
22611 			/* Software checksum? */
22612 			if (DB_CKSUMFLAGS(mp) == 0) {
22613 				IP_STAT(ipst, ip_out_sw_cksum);
22614 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22615 				    LENGTH - hlen);
22616 			}
22617 		} else {
22618 			sctp_hdr_t	*sctph;
22619 
22620 			ASSERT(PROTO == IPPROTO_SCTP);
22621 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22622 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22623 			/*
22624 			 * Zero out the checksum field to ensure proper
22625 			 * checksum calculation.
22626 			 */
22627 			sctph->sh_chksum = 0;
22628 #ifdef	DEBUG
22629 			if (!skip_sctp_cksum)
22630 #endif
22631 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22632 		}
22633 	}
22634 
22635 	/*
22636 	 * If this is a multicast packet and originated from ip_wput
22637 	 * we need to do loopback and forwarding checks. If it comes
22638 	 * from ip_wput_multicast, we SHOULD not do this.
22639 	 */
22640 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22641 
22642 	/* checksum */
22643 	cksum += ttl_protocol;
22644 
22645 	/* fragment the packet */
22646 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22647 		goto fragmentit;
22648 	/*
22649 	 * Don't use frag_flag if packet is pre-built or source
22650 	 * routed or if multicast (since multicast packets do
22651 	 * not solicit ICMP "packet too big" messages).
22652 	 */
22653 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22654 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22655 	    !ip_source_route_included(ipha)) &&
22656 	    !CLASSD(ipha->ipha_dst))
22657 		ipha->ipha_fragment_offset_and_flags |=
22658 		    htons(ire->ire_frag_flag);
22659 
22660 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22661 		/* calculate IP header checksum */
22662 		cksum += ipha->ipha_ident;
22663 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22664 		cksum += ipha->ipha_fragment_offset_and_flags;
22665 
22666 		/* IP options present */
22667 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22668 		if (hlen)
22669 			goto checksumoptions;
22670 
22671 		/* calculate hdr checksum */
22672 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22673 		cksum = ~(cksum + (cksum >> 16));
22674 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22675 	}
22676 	if (ipsec_len != 0) {
22677 		/*
22678 		 * We will do the rest of the processing after
22679 		 * we come back from IPsec in ip_wput_ipsec_out().
22680 		 */
22681 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22682 
22683 		io = (ipsec_out_t *)first_mp->b_rptr;
22684 		io->ipsec_out_ill_index =
22685 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22686 		ipsec_out_process(q, first_mp, ire, 0);
22687 		ire_refrele(ire);
22688 		if (conn_outgoing_ill != NULL)
22689 			ill_refrele(conn_outgoing_ill);
22690 		return;
22691 	}
22692 
22693 	/*
22694 	 * In most cases, the emission loop below is entered only
22695 	 * once. Only in the case where the ire holds the
22696 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22697 	 * flagged ires in the bucket, and send the packet
22698 	 * through all crossed RTF_MULTIRT routes.
22699 	 */
22700 	if (ire->ire_flags & RTF_MULTIRT) {
22701 		multirt_send = B_TRUE;
22702 	}
22703 	do {
22704 		if (multirt_send) {
22705 			irb_t *irb;
22706 			/*
22707 			 * We are in a multiple send case, need to get
22708 			 * the next ire and make a duplicate of the packet.
22709 			 * ire1 holds here the next ire to process in the
22710 			 * bucket. If multirouting is expected,
22711 			 * any non-RTF_MULTIRT ire that has the
22712 			 * right destination address is ignored.
22713 			 */
22714 			irb = ire->ire_bucket;
22715 			ASSERT(irb != NULL);
22716 
22717 			IRB_REFHOLD(irb);
22718 			for (ire1 = ire->ire_next;
22719 			    ire1 != NULL;
22720 			    ire1 = ire1->ire_next) {
22721 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22722 					continue;
22723 				if (ire1->ire_addr != ire->ire_addr)
22724 					continue;
22725 				if (ire1->ire_marks &
22726 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22727 					continue;
22728 
22729 				/* Got one */
22730 				IRE_REFHOLD(ire1);
22731 				break;
22732 			}
22733 			IRB_REFRELE(irb);
22734 
22735 			if (ire1 != NULL) {
22736 				next_mp = copyb(mp);
22737 				if ((next_mp == NULL) ||
22738 				    ((mp->b_cont != NULL) &&
22739 				    ((next_mp->b_cont =
22740 				    dupmsg(mp->b_cont)) == NULL))) {
22741 					freemsg(next_mp);
22742 					next_mp = NULL;
22743 					ire_refrele(ire1);
22744 					ire1 = NULL;
22745 				}
22746 			}
22747 
22748 			/* Last multiroute ire; don't loop anymore. */
22749 			if (ire1 == NULL) {
22750 				multirt_send = B_FALSE;
22751 			}
22752 		}
22753 
22754 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22755 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22756 		    mblk_t *, mp);
22757 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22758 		    ipst->ips_ipv4firewall_physical_out,
22759 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22760 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22761 
22762 		if (mp == NULL)
22763 			goto release_ire_and_ill;
22764 
22765 		if (ipst->ips_ipobs_enabled) {
22766 			zoneid_t szone;
22767 
22768 			/*
22769 			 * On the outbound path the destination zone will be
22770 			 * unknown as we're sending this packet out on the
22771 			 * wire.
22772 			 */
22773 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22774 			    ALL_ZONES);
22775 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22776 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22777 		}
22778 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22779 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22780 
22781 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22782 
22783 		if ((pktxmit_state == SEND_FAILED) ||
22784 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22785 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22786 			    "- packet dropped\n"));
22787 release_ire_and_ill:
22788 			ire_refrele(ire);
22789 			if (next_mp != NULL) {
22790 				freemsg(next_mp);
22791 				ire_refrele(ire1);
22792 			}
22793 			if (conn_outgoing_ill != NULL)
22794 				ill_refrele(conn_outgoing_ill);
22795 			return;
22796 		}
22797 
22798 		if (CLASSD(dst)) {
22799 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22800 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22801 			    LENGTH);
22802 		}
22803 
22804 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22805 		    "ip_wput_ire_end: q %p (%S)",
22806 		    q, "last copy out");
22807 		IRE_REFRELE(ire);
22808 
22809 		if (multirt_send) {
22810 			ASSERT(ire1);
22811 			/*
22812 			 * Proceed with the next RTF_MULTIRT ire,
22813 			 * Also set up the send-to queue accordingly.
22814 			 */
22815 			ire = ire1;
22816 			ire1 = NULL;
22817 			stq = ire->ire_stq;
22818 			mp = next_mp;
22819 			next_mp = NULL;
22820 			ipha = (ipha_t *)mp->b_rptr;
22821 			ill_index = Q_TO_INDEX(stq);
22822 			ill = (ill_t *)stq->q_ptr;
22823 		}
22824 	} while (multirt_send);
22825 	if (conn_outgoing_ill != NULL)
22826 		ill_refrele(conn_outgoing_ill);
22827 	return;
22828 
22829 	/*
22830 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22831 	 */
22832 broadcast:
22833 	{
22834 		/*
22835 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22836 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22837 		 * can be overridden stack-wide through the ip_broadcast_ttl
22838 		 * ndd tunable, or on a per-connection basis through the
22839 		 * IP_BROADCAST_TTL socket option.
22840 		 *
22841 		 * In the event that we are replying to incoming ICMP packets,
22842 		 * connp could be NULL.
22843 		 */
22844 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22845 		if (connp != NULL) {
22846 			if (connp->conn_dontroute)
22847 				ipha->ipha_ttl = 1;
22848 			else if (connp->conn_broadcast_ttl != 0)
22849 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22850 		}
22851 
22852 		/*
22853 		 * Note that we are not doing a IRB_REFHOLD here.
22854 		 * Actually we don't care if the list changes i.e
22855 		 * if somebody deletes an IRE from the list while
22856 		 * we drop the lock, the next time we come around
22857 		 * ire_next will be NULL and hence we won't send
22858 		 * out multiple copies which is fine.
22859 		 */
22860 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22861 		ire1 = ire->ire_next;
22862 		if (conn_outgoing_ill != NULL) {
22863 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22864 				ASSERT(ire1 == ire->ire_next);
22865 				if (ire1 != NULL && ire1->ire_addr == dst) {
22866 					ire_refrele(ire);
22867 					ire = ire1;
22868 					IRE_REFHOLD(ire);
22869 					ire1 = ire->ire_next;
22870 					continue;
22871 				}
22872 				rw_exit(&ire->ire_bucket->irb_lock);
22873 				/* Did not find a matching ill */
22874 				ip1dbg(("ip_wput_ire: broadcast with no "
22875 				    "matching IP_BOUND_IF ill %s dst %x\n",
22876 				    conn_outgoing_ill->ill_name, dst));
22877 				freemsg(first_mp);
22878 				if (ire != NULL)
22879 					ire_refrele(ire);
22880 				ill_refrele(conn_outgoing_ill);
22881 				return;
22882 			}
22883 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22884 			/*
22885 			 * If the next IRE has the same address and is not one
22886 			 * of the two copies that we need to send, try to see
22887 			 * whether this copy should be sent at all. This
22888 			 * assumes that we insert loopbacks first and then
22889 			 * non-loopbacks. This is acheived by inserting the
22890 			 * loopback always before non-loopback.
22891 			 * This is used to send a single copy of a broadcast
22892 			 * packet out all physical interfaces that have an
22893 			 * matching IRE_BROADCAST while also looping
22894 			 * back one copy (to ip_wput_local) for each
22895 			 * matching physical interface. However, we avoid
22896 			 * sending packets out different logical that match by
22897 			 * having ipif_up/ipif_down supress duplicate
22898 			 * IRE_BROADCASTS.
22899 			 *
22900 			 * This feature is currently used to get broadcasts
22901 			 * sent to multiple interfaces, when the broadcast
22902 			 * address being used applies to multiple interfaces.
22903 			 * For example, a whole net broadcast will be
22904 			 * replicated on every connected subnet of
22905 			 * the target net.
22906 			 *
22907 			 * Each zone has its own set of IRE_BROADCASTs, so that
22908 			 * we're able to distribute inbound packets to multiple
22909 			 * zones who share a broadcast address. We avoid looping
22910 			 * back outbound packets in different zones but on the
22911 			 * same ill, as the application would see duplicates.
22912 			 *
22913 			 * This logic assumes that ire_add_v4() groups the
22914 			 * IRE_BROADCAST entries so that those with the same
22915 			 * ire_addr are kept together.
22916 			 */
22917 			ire_ill = ire->ire_ipif->ipif_ill;
22918 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22919 				while (ire1 != NULL && ire1->ire_addr == dst) {
22920 					ire1_ill = ire1->ire_ipif->ipif_ill;
22921 					if (ire1_ill != ire_ill)
22922 						break;
22923 					ire1 = ire1->ire_next;
22924 				}
22925 			}
22926 		}
22927 		ASSERT(multirt_send == B_FALSE);
22928 		if (ire1 != NULL && ire1->ire_addr == dst) {
22929 			if ((ire->ire_flags & RTF_MULTIRT) &&
22930 			    (ire1->ire_flags & RTF_MULTIRT)) {
22931 				/*
22932 				 * We are in the multirouting case.
22933 				 * The message must be sent at least
22934 				 * on both ires. These ires have been
22935 				 * inserted AFTER the standard ones
22936 				 * in ip_rt_add(). There are thus no
22937 				 * other ire entries for the destination
22938 				 * address in the rest of the bucket
22939 				 * that do not have the RTF_MULTIRT
22940 				 * flag. We don't process a copy
22941 				 * of the message here. This will be
22942 				 * done in the final sending loop.
22943 				 */
22944 				multirt_send = B_TRUE;
22945 			} else {
22946 				next_mp = ip_copymsg(first_mp);
22947 				if (next_mp != NULL)
22948 					IRE_REFHOLD(ire1);
22949 			}
22950 		}
22951 		rw_exit(&ire->ire_bucket->irb_lock);
22952 	}
22953 
22954 	if (stq) {
22955 		/*
22956 		 * A non-NULL send-to queue means this packet is going
22957 		 * out of this machine.
22958 		 */
22959 		out_ill = (ill_t *)stq->q_ptr;
22960 
22961 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22962 		ttl_protocol = ((uint16_t *)ipha)[4];
22963 		/*
22964 		 * We accumulate the pseudo header checksum in cksum.
22965 		 * This is pretty hairy code, so watch close.  One
22966 		 * thing to keep in mind is that UDP and TCP have
22967 		 * stored their respective datagram lengths in their
22968 		 * checksum fields.  This lines things up real nice.
22969 		 */
22970 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22971 		    (src >> 16) + (src & 0xFFFF);
22972 		/*
22973 		 * We assume the udp checksum field contains the
22974 		 * length, so to compute the pseudo header checksum,
22975 		 * all we need is the protocol number and src/dst.
22976 		 */
22977 		/* Provide the checksums for UDP and TCP. */
22978 		if ((PROTO == IPPROTO_TCP) &&
22979 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22980 			/* hlen gets the number of uchar_ts in the IP header */
22981 			hlen = (V_HLEN & 0xF) << 2;
22982 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22983 			IP_STAT(ipst, ip_out_sw_cksum);
22984 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22985 			    LENGTH - hlen);
22986 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22987 		} else if (PROTO == IPPROTO_SCTP &&
22988 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22989 			sctp_hdr_t	*sctph;
22990 
22991 			hlen = (V_HLEN & 0xF) << 2;
22992 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22993 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22994 			sctph->sh_chksum = 0;
22995 #ifdef	DEBUG
22996 			if (!skip_sctp_cksum)
22997 #endif
22998 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22999 		} else {
23000 			queue_t	*dev_q = stq->q_next;
23001 
23002 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
23003 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
23004 blocked:
23005 				ipha->ipha_ident = ip_hdr_included;
23006 				/*
23007 				 * If we don't have a conn to apply
23008 				 * backpressure, free the message.
23009 				 * In the ire_send path, we don't know
23010 				 * the position to requeue the packet. Rather
23011 				 * than reorder packets, we just drop this
23012 				 * packet.
23013 				 */
23014 				if (ipst->ips_ip_output_queue &&
23015 				    connp != NULL &&
23016 				    caller != IRE_SEND) {
23017 					if (caller == IP_WSRV) {
23018 						idl_tx_list_t *idl_txl;
23019 
23020 						idl_txl =
23021 						    &ipst->ips_idl_tx_list[0];
23022 						connp->conn_did_putbq = 1;
23023 						(void) putbq(connp->conn_wq,
23024 						    first_mp);
23025 						conn_drain_insert(connp,
23026 						    idl_txl);
23027 						/*
23028 						 * This is the service thread,
23029 						 * and the queue is already
23030 						 * noenabled. The check for
23031 						 * canput and the putbq is not
23032 						 * atomic. So we need to check
23033 						 * again.
23034 						 */
23035 						if (canput(stq->q_next))
23036 							connp->conn_did_putbq
23037 							    = 0;
23038 						IP_STAT(ipst, ip_conn_flputbq);
23039 					} else {
23040 						/*
23041 						 * We are not the service proc.
23042 						 * ip_wsrv will be scheduled or
23043 						 * is already running.
23044 						 */
23045 
23046 						(void) putq(connp->conn_wq,
23047 						    first_mp);
23048 					}
23049 				} else {
23050 					out_ill = (ill_t *)stq->q_ptr;
23051 					BUMP_MIB(out_ill->ill_ip_mib,
23052 					    ipIfStatsOutDiscards);
23053 					freemsg(first_mp);
23054 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23055 					    "ip_wput_ire_end: q %p (%S)",
23056 					    q, "discard");
23057 				}
23058 				ire_refrele(ire);
23059 				if (next_mp) {
23060 					ire_refrele(ire1);
23061 					freemsg(next_mp);
23062 				}
23063 				if (conn_outgoing_ill != NULL)
23064 					ill_refrele(conn_outgoing_ill);
23065 				return;
23066 			}
23067 			if ((PROTO == IPPROTO_UDP) &&
23068 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23069 				/*
23070 				 * hlen gets the number of uchar_ts in the
23071 				 * IP header
23072 				 */
23073 				hlen = (V_HLEN & 0xF) << 2;
23074 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23075 				max_frag = ire->ire_max_frag;
23076 				if (*up != 0) {
23077 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
23078 					    up, PROTO, hlen, LENGTH, max_frag,
23079 					    ipsec_len, cksum);
23080 					/* Software checksum? */
23081 					if (DB_CKSUMFLAGS(mp) == 0) {
23082 						IP_STAT(ipst, ip_out_sw_cksum);
23083 						IP_STAT_UPDATE(ipst,
23084 						    ip_udp_out_sw_cksum_bytes,
23085 						    LENGTH - hlen);
23086 					}
23087 				}
23088 			}
23089 		}
23090 		/*
23091 		 * Need to do this even when fragmenting. The local
23092 		 * loopback can be done without computing checksums
23093 		 * but forwarding out other interface must be done
23094 		 * after the IP checksum (and ULP checksums) have been
23095 		 * computed.
23096 		 *
23097 		 * NOTE : multicast_forward is set only if this packet
23098 		 * originated from ip_wput. For packets originating from
23099 		 * ip_wput_multicast, it is not set.
23100 		 */
23101 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23102 multi_loopback:
23103 			ip2dbg(("ip_wput: multicast, loop %d\n",
23104 			    conn_multicast_loop));
23105 
23106 			/*  Forget header checksum offload */
23107 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23108 
23109 			/*
23110 			 * Local loopback of multicasts?  Check the
23111 			 * ill.
23112 			 *
23113 			 * Note that the loopback function will not come
23114 			 * in through ip_rput - it will only do the
23115 			 * client fanout thus we need to do an mforward
23116 			 * as well.  The is different from the BSD
23117 			 * logic.
23118 			 */
23119 			if (ill != NULL) {
23120 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
23121 				    ALL_ZONES) != NULL) {
23122 					/*
23123 					 * Pass along the virtual output q.
23124 					 * ip_wput_local() will distribute the
23125 					 * packet to all the matching zones,
23126 					 * except the sending zone when
23127 					 * IP_MULTICAST_LOOP is false.
23128 					 */
23129 					ip_multicast_loopback(q, ill, first_mp,
23130 					    conn_multicast_loop ? 0 :
23131 					    IP_FF_NO_MCAST_LOOP, zoneid);
23132 				}
23133 			}
23134 			if (ipha->ipha_ttl == 0) {
23135 				/*
23136 				 * 0 => only to this host i.e. we are
23137 				 * done. We are also done if this was the
23138 				 * loopback interface since it is sufficient
23139 				 * to loopback one copy of a multicast packet.
23140 				 */
23141 				freemsg(first_mp);
23142 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23143 				    "ip_wput_ire_end: q %p (%S)",
23144 				    q, "loopback");
23145 				ire_refrele(ire);
23146 				if (conn_outgoing_ill != NULL)
23147 					ill_refrele(conn_outgoing_ill);
23148 				return;
23149 			}
23150 			/*
23151 			 * ILLF_MULTICAST is checked in ip_newroute
23152 			 * i.e. we don't need to check it here since
23153 			 * all IRE_CACHEs come from ip_newroute.
23154 			 * For multicast traffic, SO_DONTROUTE is interpreted
23155 			 * to mean only send the packet out the interface
23156 			 * (optionally specified with IP_MULTICAST_IF)
23157 			 * and do not forward it out additional interfaces.
23158 			 * RSVP and the rsvp daemon is an example of a
23159 			 * protocol and user level process that
23160 			 * handles it's own routing. Hence, it uses the
23161 			 * SO_DONTROUTE option to accomplish this.
23162 			 */
23163 
23164 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23165 			    ill != NULL) {
23166 				/* Unconditionally redo the checksum */
23167 				ipha->ipha_hdr_checksum = 0;
23168 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23169 
23170 				/*
23171 				 * If this needs to go out secure, we need
23172 				 * to wait till we finish the IPsec
23173 				 * processing.
23174 				 */
23175 				if (ipsec_len == 0 &&
23176 				    ip_mforward(ill, ipha, mp)) {
23177 					freemsg(first_mp);
23178 					ip1dbg(("ip_wput: mforward failed\n"));
23179 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23180 					    "ip_wput_ire_end: q %p (%S)",
23181 					    q, "mforward failed");
23182 					ire_refrele(ire);
23183 					if (conn_outgoing_ill != NULL)
23184 						ill_refrele(conn_outgoing_ill);
23185 					return;
23186 				}
23187 			}
23188 		}
23189 		max_frag = ire->ire_max_frag;
23190 		cksum += ttl_protocol;
23191 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23192 			/* No fragmentation required for this one. */
23193 			/*
23194 			 * Don't use frag_flag if packet is pre-built or source
23195 			 * routed or if multicast (since multicast packets do
23196 			 * not solicit ICMP "packet too big" messages).
23197 			 */
23198 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23199 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23200 			    !ip_source_route_included(ipha)) &&
23201 			    !CLASSD(ipha->ipha_dst))
23202 				ipha->ipha_fragment_offset_and_flags |=
23203 				    htons(ire->ire_frag_flag);
23204 
23205 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23206 				/* Complete the IP header checksum. */
23207 				cksum += ipha->ipha_ident;
23208 				cksum += (v_hlen_tos_len >> 16)+
23209 				    (v_hlen_tos_len & 0xFFFF);
23210 				cksum += ipha->ipha_fragment_offset_and_flags;
23211 				hlen = (V_HLEN & 0xF) -
23212 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23213 				if (hlen) {
23214 checksumoptions:
23215 					/*
23216 					 * Account for the IP Options in the IP
23217 					 * header checksum.
23218 					 */
23219 					up = (uint16_t *)(rptr+
23220 					    IP_SIMPLE_HDR_LENGTH);
23221 					do {
23222 						cksum += up[0];
23223 						cksum += up[1];
23224 						up += 2;
23225 					} while (--hlen);
23226 				}
23227 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23228 				cksum = ~(cksum + (cksum >> 16));
23229 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23230 			}
23231 			if (ipsec_len != 0) {
23232 				ipsec_out_process(q, first_mp, ire, ill_index);
23233 				if (!next_mp) {
23234 					ire_refrele(ire);
23235 					if (conn_outgoing_ill != NULL)
23236 						ill_refrele(conn_outgoing_ill);
23237 					return;
23238 				}
23239 				goto next;
23240 			}
23241 
23242 			/*
23243 			 * multirt_send has already been handled
23244 			 * for broadcast, but not yet for multicast
23245 			 * or IP options.
23246 			 */
23247 			if (next_mp == NULL) {
23248 				if (ire->ire_flags & RTF_MULTIRT) {
23249 					multirt_send = B_TRUE;
23250 				}
23251 			}
23252 
23253 			/*
23254 			 * In most cases, the emission loop below is
23255 			 * entered only once. Only in the case where
23256 			 * the ire holds the RTF_MULTIRT flag, do we loop
23257 			 * to process all RTF_MULTIRT ires in the bucket,
23258 			 * and send the packet through all crossed
23259 			 * RTF_MULTIRT routes.
23260 			 */
23261 			do {
23262 				if (multirt_send) {
23263 					irb_t *irb;
23264 
23265 					irb = ire->ire_bucket;
23266 					ASSERT(irb != NULL);
23267 					/*
23268 					 * We are in a multiple send case,
23269 					 * need to get the next IRE and make
23270 					 * a duplicate of the packet.
23271 					 */
23272 					IRB_REFHOLD(irb);
23273 					for (ire1 = ire->ire_next;
23274 					    ire1 != NULL;
23275 					    ire1 = ire1->ire_next) {
23276 						if (!(ire1->ire_flags &
23277 						    RTF_MULTIRT))
23278 							continue;
23279 
23280 						if (ire1->ire_addr !=
23281 						    ire->ire_addr)
23282 							continue;
23283 
23284 						if (ire1->ire_marks &
23285 						    (IRE_MARK_CONDEMNED |
23286 						    IRE_MARK_TESTHIDDEN))
23287 							continue;
23288 
23289 						/* Got one */
23290 						IRE_REFHOLD(ire1);
23291 						break;
23292 					}
23293 					IRB_REFRELE(irb);
23294 
23295 					if (ire1 != NULL) {
23296 						next_mp = copyb(mp);
23297 						if ((next_mp == NULL) ||
23298 						    ((mp->b_cont != NULL) &&
23299 						    ((next_mp->b_cont =
23300 						    dupmsg(mp->b_cont))
23301 						    == NULL))) {
23302 							freemsg(next_mp);
23303 							next_mp = NULL;
23304 							ire_refrele(ire1);
23305 							ire1 = NULL;
23306 						}
23307 					}
23308 
23309 					/*
23310 					 * Last multiroute ire; don't loop
23311 					 * anymore. The emission is over
23312 					 * and next_mp is NULL.
23313 					 */
23314 					if (ire1 == NULL) {
23315 						multirt_send = B_FALSE;
23316 					}
23317 				}
23318 
23319 				out_ill = ire_to_ill(ire);
23320 				DTRACE_PROBE4(ip4__physical__out__start,
23321 				    ill_t *, NULL,
23322 				    ill_t *, out_ill,
23323 				    ipha_t *, ipha, mblk_t *, mp);
23324 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23325 				    ipst->ips_ipv4firewall_physical_out,
23326 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23327 				DTRACE_PROBE1(ip4__physical__out__end,
23328 				    mblk_t *, mp);
23329 				if (mp == NULL)
23330 					goto release_ire_and_ill_2;
23331 
23332 				ASSERT(ipsec_len == 0);
23333 				mp->b_prev =
23334 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23335 				DTRACE_PROBE2(ip__xmit__2,
23336 				    mblk_t *, mp, ire_t *, ire);
23337 				pktxmit_state = ip_xmit_v4(mp, ire,
23338 				    NULL, B_TRUE, connp);
23339 				if ((pktxmit_state == SEND_FAILED) ||
23340 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23341 release_ire_and_ill_2:
23342 					if (next_mp) {
23343 						freemsg(next_mp);
23344 						ire_refrele(ire1);
23345 					}
23346 					ire_refrele(ire);
23347 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23348 					    "ip_wput_ire_end: q %p (%S)",
23349 					    q, "discard MDATA");
23350 					if (conn_outgoing_ill != NULL)
23351 						ill_refrele(conn_outgoing_ill);
23352 					return;
23353 				}
23354 
23355 				if (CLASSD(dst)) {
23356 					BUMP_MIB(out_ill->ill_ip_mib,
23357 					    ipIfStatsHCOutMcastPkts);
23358 					UPDATE_MIB(out_ill->ill_ip_mib,
23359 					    ipIfStatsHCOutMcastOctets,
23360 					    LENGTH);
23361 				} else if (ire->ire_type == IRE_BROADCAST) {
23362 					BUMP_MIB(out_ill->ill_ip_mib,
23363 					    ipIfStatsHCOutBcastPkts);
23364 				}
23365 
23366 				if (multirt_send) {
23367 					/*
23368 					 * We are in a multiple send case,
23369 					 * need to re-enter the sending loop
23370 					 * using the next ire.
23371 					 */
23372 					ire_refrele(ire);
23373 					ire = ire1;
23374 					stq = ire->ire_stq;
23375 					mp = next_mp;
23376 					next_mp = NULL;
23377 					ipha = (ipha_t *)mp->b_rptr;
23378 					ill_index = Q_TO_INDEX(stq);
23379 				}
23380 			} while (multirt_send);
23381 
23382 			if (!next_mp) {
23383 				/*
23384 				 * Last copy going out (the ultra-common
23385 				 * case).  Note that we intentionally replicate
23386 				 * the putnext rather than calling it before
23387 				 * the next_mp check in hopes of a little
23388 				 * tail-call action out of the compiler.
23389 				 */
23390 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23391 				    "ip_wput_ire_end: q %p (%S)",
23392 				    q, "last copy out(1)");
23393 				ire_refrele(ire);
23394 				if (conn_outgoing_ill != NULL)
23395 					ill_refrele(conn_outgoing_ill);
23396 				return;
23397 			}
23398 			/* More copies going out below. */
23399 		} else {
23400 			int offset;
23401 fragmentit:
23402 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23403 			/*
23404 			 * If this would generate a icmp_frag_needed message,
23405 			 * we need to handle it before we do the IPsec
23406 			 * processing. Otherwise, we need to strip the IPsec
23407 			 * headers before we send up the message to the ULPs
23408 			 * which becomes messy and difficult.
23409 			 */
23410 			if (ipsec_len != 0) {
23411 				if ((max_frag < (unsigned int)(LENGTH +
23412 				    ipsec_len)) && (offset & IPH_DF)) {
23413 					out_ill = (ill_t *)stq->q_ptr;
23414 					BUMP_MIB(out_ill->ill_ip_mib,
23415 					    ipIfStatsOutFragFails);
23416 					BUMP_MIB(out_ill->ill_ip_mib,
23417 					    ipIfStatsOutFragReqds);
23418 					ipha->ipha_hdr_checksum = 0;
23419 					ipha->ipha_hdr_checksum =
23420 					    (uint16_t)ip_csum_hdr(ipha);
23421 					icmp_frag_needed(ire->ire_stq, first_mp,
23422 					    max_frag, zoneid, ipst);
23423 					if (!next_mp) {
23424 						ire_refrele(ire);
23425 						if (conn_outgoing_ill != NULL) {
23426 							ill_refrele(
23427 							    conn_outgoing_ill);
23428 						}
23429 						return;
23430 					}
23431 				} else {
23432 					/*
23433 					 * This won't cause a icmp_frag_needed
23434 					 * message. to be generated. Send it on
23435 					 * the wire. Note that this could still
23436 					 * cause fragmentation and all we
23437 					 * do is the generation of the message
23438 					 * to the ULP if needed before IPsec.
23439 					 */
23440 					if (!next_mp) {
23441 						ipsec_out_process(q, first_mp,
23442 						    ire, ill_index);
23443 						TRACE_2(TR_FAC_IP,
23444 						    TR_IP_WPUT_IRE_END,
23445 						    "ip_wput_ire_end: q %p "
23446 						    "(%S)", q,
23447 						    "last ipsec_out_process");
23448 						ire_refrele(ire);
23449 						if (conn_outgoing_ill != NULL) {
23450 							ill_refrele(
23451 							    conn_outgoing_ill);
23452 						}
23453 						return;
23454 					}
23455 					ipsec_out_process(q, first_mp,
23456 					    ire, ill_index);
23457 				}
23458 			} else {
23459 				/*
23460 				 * Initiate IPPF processing. For
23461 				 * fragmentable packets we finish
23462 				 * all QOS packet processing before
23463 				 * calling:
23464 				 * ip_wput_ire_fragmentit->ip_wput_frag
23465 				 */
23466 
23467 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23468 					ip_process(IPP_LOCAL_OUT, &mp,
23469 					    ill_index);
23470 					if (mp == NULL) {
23471 						out_ill = (ill_t *)stq->q_ptr;
23472 						BUMP_MIB(out_ill->ill_ip_mib,
23473 						    ipIfStatsOutDiscards);
23474 						if (next_mp != NULL) {
23475 							freemsg(next_mp);
23476 							ire_refrele(ire1);
23477 						}
23478 						ire_refrele(ire);
23479 						TRACE_2(TR_FAC_IP,
23480 						    TR_IP_WPUT_IRE_END,
23481 						    "ip_wput_ire: q %p (%S)",
23482 						    q, "discard MDATA");
23483 						if (conn_outgoing_ill != NULL) {
23484 							ill_refrele(
23485 							    conn_outgoing_ill);
23486 						}
23487 						return;
23488 					}
23489 				}
23490 				if (!next_mp) {
23491 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23492 					    "ip_wput_ire_end: q %p (%S)",
23493 					    q, "last fragmentation");
23494 					ip_wput_ire_fragmentit(mp, ire,
23495 					    zoneid, ipst, connp);
23496 					ire_refrele(ire);
23497 					if (conn_outgoing_ill != NULL)
23498 						ill_refrele(conn_outgoing_ill);
23499 					return;
23500 				}
23501 				ip_wput_ire_fragmentit(mp, ire,
23502 				    zoneid, ipst, connp);
23503 			}
23504 		}
23505 	} else {
23506 nullstq:
23507 		/* A NULL stq means the destination address is local. */
23508 		UPDATE_OB_PKT_COUNT(ire);
23509 		ire->ire_last_used_time = lbolt;
23510 		ASSERT(ire->ire_ipif != NULL);
23511 		if (!next_mp) {
23512 			/*
23513 			 * Is there an "in" and "out" for traffic local
23514 			 * to a host (loopback)?  The code in Solaris doesn't
23515 			 * explicitly draw a line in its code for in vs out,
23516 			 * so we've had to draw a line in the sand: ip_wput_ire
23517 			 * is considered to be the "output" side and
23518 			 * ip_wput_local to be the "input" side.
23519 			 */
23520 			out_ill = ire_to_ill(ire);
23521 
23522 			/*
23523 			 * DTrace this as ip:::send.  A blocked packet will
23524 			 * fire the send probe, but not the receive probe.
23525 			 */
23526 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23527 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23528 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23529 
23530 			DTRACE_PROBE4(ip4__loopback__out__start,
23531 			    ill_t *, NULL, ill_t *, out_ill,
23532 			    ipha_t *, ipha, mblk_t *, first_mp);
23533 
23534 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23535 			    ipst->ips_ipv4firewall_loopback_out,
23536 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23537 
23538 			DTRACE_PROBE1(ip4__loopback__out_end,
23539 			    mblk_t *, first_mp);
23540 
23541 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23542 			    "ip_wput_ire_end: q %p (%S)",
23543 			    q, "local address");
23544 
23545 			if (first_mp != NULL)
23546 				ip_wput_local(q, out_ill, ipha,
23547 				    first_mp, ire, 0, ire->ire_zoneid);
23548 			ire_refrele(ire);
23549 			if (conn_outgoing_ill != NULL)
23550 				ill_refrele(conn_outgoing_ill);
23551 			return;
23552 		}
23553 
23554 		out_ill = ire_to_ill(ire);
23555 
23556 		/*
23557 		 * DTrace this as ip:::send.  A blocked packet will fire the
23558 		 * send probe, but not the receive probe.
23559 		 */
23560 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23561 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23562 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23563 
23564 		DTRACE_PROBE4(ip4__loopback__out__start,
23565 		    ill_t *, NULL, ill_t *, out_ill,
23566 		    ipha_t *, ipha, mblk_t *, first_mp);
23567 
23568 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23569 		    ipst->ips_ipv4firewall_loopback_out,
23570 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23571 
23572 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23573 
23574 		if (first_mp != NULL)
23575 			ip_wput_local(q, out_ill, ipha,
23576 			    first_mp, ire, 0, ire->ire_zoneid);
23577 	}
23578 next:
23579 	/*
23580 	 * More copies going out to additional interfaces.
23581 	 * ire1 has already been held. We don't need the
23582 	 * "ire" anymore.
23583 	 */
23584 	ire_refrele(ire);
23585 	ire = ire1;
23586 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23587 	mp = next_mp;
23588 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23589 	ill = ire_to_ill(ire);
23590 	first_mp = mp;
23591 	if (ipsec_len != 0) {
23592 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23593 		mp = mp->b_cont;
23594 	}
23595 	dst = ire->ire_addr;
23596 	ipha = (ipha_t *)mp->b_rptr;
23597 	/*
23598 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23599 	 * Restore ipha_ident "no checksum" flag.
23600 	 */
23601 	src = orig_src;
23602 	ipha->ipha_ident = ip_hdr_included;
23603 	goto another;
23604 
23605 #undef	rptr
23606 #undef	Q_TO_INDEX
23607 }
23608 
23609 /*
23610  * Routine to allocate a message that is used to notify the ULP about MDT.
23611  * The caller may provide a pointer to the link-layer MDT capabilities,
23612  * or NULL if MDT is to be disabled on the stream.
23613  */
23614 mblk_t *
23615 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23616 {
23617 	mblk_t *mp;
23618 	ip_mdt_info_t *mdti;
23619 	ill_mdt_capab_t *idst;
23620 
23621 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23622 		DB_TYPE(mp) = M_CTL;
23623 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23624 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23625 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23626 		idst = &(mdti->mdt_capab);
23627 
23628 		/*
23629 		 * If the caller provides us with the capability, copy
23630 		 * it over into our notification message; otherwise
23631 		 * we zero out the capability portion.
23632 		 */
23633 		if (isrc != NULL)
23634 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23635 		else
23636 			bzero((caddr_t)idst, sizeof (*idst));
23637 	}
23638 	return (mp);
23639 }
23640 
23641 /*
23642  * Routine which determines whether MDT can be enabled on the destination
23643  * IRE and IPC combination, and if so, allocates and returns the MDT
23644  * notification mblk that may be used by ULP.  We also check if we need to
23645  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23646  * MDT usage in the past have been lifted.  This gets called during IP
23647  * and ULP binding.
23648  */
23649 mblk_t *
23650 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23651     ill_mdt_capab_t *mdt_cap)
23652 {
23653 	mblk_t *mp;
23654 	boolean_t rc = B_FALSE;
23655 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23656 
23657 	ASSERT(dst_ire != NULL);
23658 	ASSERT(connp != NULL);
23659 	ASSERT(mdt_cap != NULL);
23660 
23661 	/*
23662 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23663 	 * Multidata, which is handled in tcp_multisend().  This
23664 	 * is the reason why we do all these checks here, to ensure
23665 	 * that we don't enable Multidata for the cases which we
23666 	 * can't handle at the moment.
23667 	 */
23668 	do {
23669 		/* Only do TCP at the moment */
23670 		if (connp->conn_ulp != IPPROTO_TCP)
23671 			break;
23672 
23673 		/*
23674 		 * IPsec outbound policy present?  Note that we get here
23675 		 * after calling ipsec_conn_cache_policy() where the global
23676 		 * policy checking is performed.  conn_latch will be
23677 		 * non-NULL as long as there's a policy defined,
23678 		 * i.e. conn_out_enforce_policy may be NULL in such case
23679 		 * when the connection is non-secure, and hence we check
23680 		 * further if the latch refers to an outbound policy.
23681 		 */
23682 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23683 			break;
23684 
23685 		/* CGTP (multiroute) is enabled? */
23686 		if (dst_ire->ire_flags & RTF_MULTIRT)
23687 			break;
23688 
23689 		/* Outbound IPQoS enabled? */
23690 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23691 			/*
23692 			 * In this case, we disable MDT for this and all
23693 			 * future connections going over the interface.
23694 			 */
23695 			mdt_cap->ill_mdt_on = 0;
23696 			break;
23697 		}
23698 
23699 		/* socket option(s) present? */
23700 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23701 			break;
23702 
23703 		rc = B_TRUE;
23704 	/* CONSTCOND */
23705 	} while (0);
23706 
23707 	/* Remember the result */
23708 	connp->conn_mdt_ok = rc;
23709 
23710 	if (!rc)
23711 		return (NULL);
23712 	else if (!mdt_cap->ill_mdt_on) {
23713 		/*
23714 		 * If MDT has been previously turned off in the past, and we
23715 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23716 		 * then enable it for this interface.
23717 		 */
23718 		mdt_cap->ill_mdt_on = 1;
23719 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23720 		    "interface %s\n", ill_name));
23721 	}
23722 
23723 	/* Allocate the MDT info mblk */
23724 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23725 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23726 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23727 		return (NULL);
23728 	}
23729 	return (mp);
23730 }
23731 
23732 /*
23733  * Routine to allocate a message that is used to notify the ULP about LSO.
23734  * The caller may provide a pointer to the link-layer LSO capabilities,
23735  * or NULL if LSO is to be disabled on the stream.
23736  */
23737 mblk_t *
23738 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23739 {
23740 	mblk_t *mp;
23741 	ip_lso_info_t *lsoi;
23742 	ill_lso_capab_t *idst;
23743 
23744 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23745 		DB_TYPE(mp) = M_CTL;
23746 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23747 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23748 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23749 		idst = &(lsoi->lso_capab);
23750 
23751 		/*
23752 		 * If the caller provides us with the capability, copy
23753 		 * it over into our notification message; otherwise
23754 		 * we zero out the capability portion.
23755 		 */
23756 		if (isrc != NULL)
23757 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23758 		else
23759 			bzero((caddr_t)idst, sizeof (*idst));
23760 	}
23761 	return (mp);
23762 }
23763 
23764 /*
23765  * Routine which determines whether LSO can be enabled on the destination
23766  * IRE and IPC combination, and if so, allocates and returns the LSO
23767  * notification mblk that may be used by ULP.  We also check if we need to
23768  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23769  * LSO usage in the past have been lifted.  This gets called during IP
23770  * and ULP binding.
23771  */
23772 mblk_t *
23773 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23774     ill_lso_capab_t *lso_cap)
23775 {
23776 	mblk_t *mp;
23777 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23778 
23779 	ASSERT(dst_ire != NULL);
23780 	ASSERT(connp != NULL);
23781 	ASSERT(lso_cap != NULL);
23782 
23783 	connp->conn_lso_ok = B_TRUE;
23784 
23785 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23786 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23787 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23788 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23789 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23790 		connp->conn_lso_ok = B_FALSE;
23791 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23792 			/*
23793 			 * Disable LSO for this and all future connections going
23794 			 * over the interface.
23795 			 */
23796 			lso_cap->ill_lso_on = 0;
23797 		}
23798 	}
23799 
23800 	if (!connp->conn_lso_ok)
23801 		return (NULL);
23802 	else if (!lso_cap->ill_lso_on) {
23803 		/*
23804 		 * If LSO has been previously turned off in the past, and we
23805 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23806 		 * then enable it for this interface.
23807 		 */
23808 		lso_cap->ill_lso_on = 1;
23809 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23810 		    ill_name));
23811 	}
23812 
23813 	/* Allocate the LSO info mblk */
23814 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23815 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23816 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23817 
23818 	return (mp);
23819 }
23820 
23821 /*
23822  * Create destination address attribute, and fill it with the physical
23823  * destination address and SAP taken from the template DL_UNITDATA_REQ
23824  * message block.
23825  */
23826 boolean_t
23827 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23828 {
23829 	dl_unitdata_req_t *dlurp;
23830 	pattr_t *pa;
23831 	pattrinfo_t pa_info;
23832 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23833 	uint_t das_len, das_off;
23834 
23835 	ASSERT(dlmp != NULL);
23836 
23837 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23838 	das_len = dlurp->dl_dest_addr_length;
23839 	das_off = dlurp->dl_dest_addr_offset;
23840 
23841 	pa_info.type = PATTR_DSTADDRSAP;
23842 	pa_info.len = sizeof (**das) + das_len - 1;
23843 
23844 	/* create and associate the attribute */
23845 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23846 	if (pa != NULL) {
23847 		ASSERT(*das != NULL);
23848 		(*das)->addr_is_group = 0;
23849 		(*das)->addr_len = (uint8_t)das_len;
23850 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23851 	}
23852 
23853 	return (pa != NULL);
23854 }
23855 
23856 /*
23857  * Create hardware checksum attribute and fill it with the values passed.
23858  */
23859 boolean_t
23860 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23861     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23862 {
23863 	pattr_t *pa;
23864 	pattrinfo_t pa_info;
23865 
23866 	ASSERT(mmd != NULL);
23867 
23868 	pa_info.type = PATTR_HCKSUM;
23869 	pa_info.len = sizeof (pattr_hcksum_t);
23870 
23871 	/* create and associate the attribute */
23872 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23873 	if (pa != NULL) {
23874 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23875 
23876 		hck->hcksum_start_offset = start_offset;
23877 		hck->hcksum_stuff_offset = stuff_offset;
23878 		hck->hcksum_end_offset = end_offset;
23879 		hck->hcksum_flags = flags;
23880 	}
23881 	return (pa != NULL);
23882 }
23883 
23884 /*
23885  * Create zerocopy attribute and fill it with the specified flags
23886  */
23887 boolean_t
23888 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23889 {
23890 	pattr_t *pa;
23891 	pattrinfo_t pa_info;
23892 
23893 	ASSERT(mmd != NULL);
23894 	pa_info.type = PATTR_ZCOPY;
23895 	pa_info.len = sizeof (pattr_zcopy_t);
23896 
23897 	/* create and associate the attribute */
23898 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23899 	if (pa != NULL) {
23900 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23901 
23902 		zcopy->zcopy_flags = flags;
23903 	}
23904 	return (pa != NULL);
23905 }
23906 
23907 /*
23908  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23909  * block chain. We could rewrite to handle arbitrary message block chains but
23910  * that would make the code complicated and slow. Right now there three
23911  * restrictions:
23912  *
23913  *   1. The first message block must contain the complete IP header and
23914  *	at least 1 byte of payload data.
23915  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23916  *	so that we can use a single Multidata message.
23917  *   3. No frag must be distributed over two or more message blocks so
23918  *	that we don't need more than two packet descriptors per frag.
23919  *
23920  * The above restrictions allow us to support userland applications (which
23921  * will send down a single message block) and NFS over UDP (which will
23922  * send down a chain of at most three message blocks).
23923  *
23924  * We also don't use MDT for payloads with less than or equal to
23925  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23926  */
23927 boolean_t
23928 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23929 {
23930 	int	blocks;
23931 	ssize_t	total, missing, size;
23932 
23933 	ASSERT(mp != NULL);
23934 	ASSERT(hdr_len > 0);
23935 
23936 	size = MBLKL(mp) - hdr_len;
23937 	if (size <= 0)
23938 		return (B_FALSE);
23939 
23940 	/* The first mblk contains the header and some payload. */
23941 	blocks = 1;
23942 	total = size;
23943 	size %= len;
23944 	missing = (size == 0) ? 0 : (len - size);
23945 	mp = mp->b_cont;
23946 
23947 	while (mp != NULL) {
23948 		/*
23949 		 * Give up if we encounter a zero length message block.
23950 		 * In practice, this should rarely happen and therefore
23951 		 * not worth the trouble of freeing and re-linking the
23952 		 * mblk from the chain to handle such case.
23953 		 */
23954 		if ((size = MBLKL(mp)) == 0)
23955 			return (B_FALSE);
23956 
23957 		/* Too many payload buffers for a single Multidata message? */
23958 		if (++blocks > MULTIDATA_MAX_PBUFS)
23959 			return (B_FALSE);
23960 
23961 		total += size;
23962 		/* Is a frag distributed over two or more message blocks? */
23963 		if (missing > size)
23964 			return (B_FALSE);
23965 		size -= missing;
23966 
23967 		size %= len;
23968 		missing = (size == 0) ? 0 : (len - size);
23969 
23970 		mp = mp->b_cont;
23971 	}
23972 
23973 	return (total > ip_wput_frag_mdt_min);
23974 }
23975 
23976 /*
23977  * Outbound IPv4 fragmentation routine using MDT.
23978  */
23979 static void
23980 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23981     uint32_t frag_flag, int offset)
23982 {
23983 	ipha_t		*ipha_orig;
23984 	int		i1, ip_data_end;
23985 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23986 	mblk_t		*hdr_mp, *md_mp = NULL;
23987 	unsigned char	*hdr_ptr, *pld_ptr;
23988 	multidata_t	*mmd;
23989 	ip_pdescinfo_t	pdi;
23990 	ill_t		*ill;
23991 	ip_stack_t	*ipst = ire->ire_ipst;
23992 
23993 	ASSERT(DB_TYPE(mp) == M_DATA);
23994 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23995 
23996 	ill = ire_to_ill(ire);
23997 	ASSERT(ill != NULL);
23998 
23999 	ipha_orig = (ipha_t *)mp->b_rptr;
24000 	mp->b_rptr += sizeof (ipha_t);
24001 
24002 	/* Calculate how many packets we will send out */
24003 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24004 	pkts = (i1 + len - 1) / len;
24005 	ASSERT(pkts > 1);
24006 
24007 	/* Allocate a message block which will hold all the IP Headers. */
24008 	wroff = ipst->ips_ip_wroff_extra;
24009 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24010 
24011 	i1 = pkts * hdr_chunk_len;
24012 	/*
24013 	 * Create the header buffer, Multidata and destination address
24014 	 * and SAP attribute that should be associated with it.
24015 	 */
24016 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24017 	    ((hdr_mp->b_wptr += i1),
24018 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24019 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24020 		freemsg(mp);
24021 		if (md_mp == NULL) {
24022 			freemsg(hdr_mp);
24023 		} else {
24024 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24025 			freemsg(md_mp);
24026 		}
24027 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24028 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24029 		return;
24030 	}
24031 	IP_STAT(ipst, ip_frag_mdt_allocd);
24032 
24033 	/*
24034 	 * Add a payload buffer to the Multidata; this operation must not
24035 	 * fail, or otherwise our logic in this routine is broken.  There
24036 	 * is no memory allocation done by the routine, so any returned
24037 	 * failure simply tells us that we've done something wrong.
24038 	 *
24039 	 * A failure tells us that either we're adding the same payload
24040 	 * buffer more than once, or we're trying to add more buffers than
24041 	 * allowed.  None of the above cases should happen, and we panic
24042 	 * because either there's horrible heap corruption, and/or
24043 	 * programming mistake.
24044 	 */
24045 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24046 		goto pbuf_panic;
24047 
24048 	hdr_ptr = hdr_mp->b_rptr;
24049 	pld_ptr = mp->b_rptr;
24050 
24051 	/* Establish the ending byte offset, based on the starting offset. */
24052 	offset <<= 3;
24053 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24054 	    IP_SIMPLE_HDR_LENGTH;
24055 
24056 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24057 
24058 	while (pld_ptr < mp->b_wptr) {
24059 		ipha_t		*ipha;
24060 		uint16_t	offset_and_flags;
24061 		uint16_t	ip_len;
24062 		int		error;
24063 
24064 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24065 		ipha = (ipha_t *)(hdr_ptr + wroff);
24066 		ASSERT(OK_32PTR(ipha));
24067 		*ipha = *ipha_orig;
24068 
24069 		if (ip_data_end - offset > len) {
24070 			offset_and_flags = IPH_MF;
24071 		} else {
24072 			/*
24073 			 * Last frag. Set len to the length of this last piece.
24074 			 */
24075 			len = ip_data_end - offset;
24076 			/* A frag of a frag might have IPH_MF non-zero */
24077 			offset_and_flags =
24078 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24079 			    IPH_MF;
24080 		}
24081 		offset_and_flags |= (uint16_t)(offset >> 3);
24082 		offset_and_flags |= (uint16_t)frag_flag;
24083 		/* Store the offset and flags in the IP header. */
24084 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24085 
24086 		/* Store the length in the IP header. */
24087 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24088 		ipha->ipha_length = htons(ip_len);
24089 
24090 		/*
24091 		 * Set the IP header checksum.  Note that mp is just
24092 		 * the header, so this is easy to pass to ip_csum.
24093 		 */
24094 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24095 
24096 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24097 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24098 		    NULL, int, 0);
24099 
24100 		/*
24101 		 * Record offset and size of header and data of the next packet
24102 		 * in the multidata message.
24103 		 */
24104 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24105 		PDESC_PLD_INIT(&pdi);
24106 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24107 		ASSERT(i1 > 0);
24108 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24109 		if (i1 == len) {
24110 			pld_ptr += len;
24111 		} else {
24112 			i1 = len - i1;
24113 			mp = mp->b_cont;
24114 			ASSERT(mp != NULL);
24115 			ASSERT(MBLKL(mp) >= i1);
24116 			/*
24117 			 * Attach the next payload message block to the
24118 			 * multidata message.
24119 			 */
24120 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24121 				goto pbuf_panic;
24122 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24123 			pld_ptr = mp->b_rptr + i1;
24124 		}
24125 
24126 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24127 		    KM_NOSLEEP)) == NULL) {
24128 			/*
24129 			 * Any failure other than ENOMEM indicates that we
24130 			 * have passed in invalid pdesc info or parameters
24131 			 * to mmd_addpdesc, which must not happen.
24132 			 *
24133 			 * EINVAL is a result of failure on boundary checks
24134 			 * against the pdesc info contents.  It should not
24135 			 * happen, and we panic because either there's
24136 			 * horrible heap corruption, and/or programming
24137 			 * mistake.
24138 			 */
24139 			if (error != ENOMEM) {
24140 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24141 				    "pdesc logic error detected for "
24142 				    "mmd %p pinfo %p (%d)\n",
24143 				    (void *)mmd, (void *)&pdi, error);
24144 				/* NOTREACHED */
24145 			}
24146 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24147 			/* Free unattached payload message blocks as well */
24148 			md_mp->b_cont = mp->b_cont;
24149 			goto free_mmd;
24150 		}
24151 
24152 		/* Advance fragment offset. */
24153 		offset += len;
24154 
24155 		/* Advance to location for next header in the buffer. */
24156 		hdr_ptr += hdr_chunk_len;
24157 
24158 		/* Did we reach the next payload message block? */
24159 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24160 			mp = mp->b_cont;
24161 			/*
24162 			 * Attach the next message block with payload
24163 			 * data to the multidata message.
24164 			 */
24165 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24166 				goto pbuf_panic;
24167 			pld_ptr = mp->b_rptr;
24168 		}
24169 	}
24170 
24171 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24172 	ASSERT(mp->b_wptr == pld_ptr);
24173 
24174 	/* Update IP statistics */
24175 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24176 
24177 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24178 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24179 
24180 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24181 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24182 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24183 
24184 	if (pkt_type == OB_PKT) {
24185 		ire->ire_ob_pkt_count += pkts;
24186 		if (ire->ire_ipif != NULL)
24187 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24188 	} else {
24189 		/* The type is IB_PKT in the forwarding path. */
24190 		ire->ire_ib_pkt_count += pkts;
24191 		ASSERT(!IRE_IS_LOCAL(ire));
24192 		if (ire->ire_type & IRE_BROADCAST) {
24193 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24194 		} else {
24195 			UPDATE_MIB(ill->ill_ip_mib,
24196 			    ipIfStatsHCOutForwDatagrams, pkts);
24197 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24198 		}
24199 	}
24200 	ire->ire_last_used_time = lbolt;
24201 	/* Send it down */
24202 	putnext(ire->ire_stq, md_mp);
24203 	return;
24204 
24205 pbuf_panic:
24206 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24207 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24208 	    pbuf_idx);
24209 	/* NOTREACHED */
24210 }
24211 
24212 /*
24213  * Outbound IP fragmentation routine.
24214  *
24215  * NOTE : This routine does not ire_refrele the ire that is passed in
24216  * as the argument.
24217  */
24218 static void
24219 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24220     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24221 {
24222 	int		i1;
24223 	mblk_t		*ll_hdr_mp;
24224 	int 		ll_hdr_len;
24225 	int		hdr_len;
24226 	mblk_t		*hdr_mp;
24227 	ipha_t		*ipha;
24228 	int		ip_data_end;
24229 	int		len;
24230 	mblk_t		*mp = mp_orig, *mp1;
24231 	int		offset;
24232 	queue_t		*q;
24233 	uint32_t	v_hlen_tos_len;
24234 	mblk_t		*first_mp;
24235 	boolean_t	mctl_present;
24236 	ill_t		*ill;
24237 	ill_t		*out_ill;
24238 	mblk_t		*xmit_mp;
24239 	mblk_t		*carve_mp;
24240 	ire_t		*ire1 = NULL;
24241 	ire_t		*save_ire = NULL;
24242 	mblk_t  	*next_mp = NULL;
24243 	boolean_t	last_frag = B_FALSE;
24244 	boolean_t	multirt_send = B_FALSE;
24245 	ire_t		*first_ire = NULL;
24246 	irb_t		*irb = NULL;
24247 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24248 
24249 	ill = ire_to_ill(ire);
24250 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24251 
24252 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24253 
24254 	if (max_frag == 0) {
24255 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24256 		    " -  dropping packet\n"));
24257 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24258 		freemsg(mp);
24259 		return;
24260 	}
24261 
24262 	/*
24263 	 * IPsec does not allow hw accelerated packets to be fragmented
24264 	 * This check is made in ip_wput_ipsec_out prior to coming here
24265 	 * via ip_wput_ire_fragmentit.
24266 	 *
24267 	 * If at this point we have an ire whose ARP request has not
24268 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24269 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24270 	 * This packet and all fragmentable packets for this ire will
24271 	 * continue to get dropped while ire_nce->nce_state remains in
24272 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24273 	 * ND_REACHABLE, all subsquent large packets for this ire will
24274 	 * get fragemented and sent out by this function.
24275 	 */
24276 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24277 		/* If nce_state is ND_INITIAL, trigger ARP query */
24278 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24279 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24280 		    " -  dropping packet\n"));
24281 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24282 		freemsg(mp);
24283 		return;
24284 	}
24285 
24286 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24287 	    "ip_wput_frag_start:");
24288 
24289 	if (mp->b_datap->db_type == M_CTL) {
24290 		first_mp = mp;
24291 		mp_orig = mp = mp->b_cont;
24292 		mctl_present = B_TRUE;
24293 	} else {
24294 		first_mp = mp;
24295 		mctl_present = B_FALSE;
24296 	}
24297 
24298 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24299 	ipha = (ipha_t *)mp->b_rptr;
24300 
24301 	/*
24302 	 * If the Don't Fragment flag is on, generate an ICMP destination
24303 	 * unreachable, fragmentation needed.
24304 	 */
24305 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24306 	if (offset & IPH_DF) {
24307 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24308 		if (is_system_labeled()) {
24309 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24310 			    ire->ire_max_frag - max_frag, AF_INET);
24311 		}
24312 		/*
24313 		 * Need to compute hdr checksum if called from ip_wput_ire.
24314 		 * Note that ip_rput_forward verifies the checksum before
24315 		 * calling this routine so in that case this is a noop.
24316 		 */
24317 		ipha->ipha_hdr_checksum = 0;
24318 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24319 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24320 		    ipst);
24321 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24322 		    "ip_wput_frag_end:(%S)",
24323 		    "don't fragment");
24324 		return;
24325 	}
24326 	/*
24327 	 * Labeled systems adjust max_frag if they add a label
24328 	 * to send the correct path mtu.  We need the real mtu since we
24329 	 * are fragmenting the packet after label adjustment.
24330 	 */
24331 	if (is_system_labeled())
24332 		max_frag = ire->ire_max_frag;
24333 	if (mctl_present)
24334 		freeb(first_mp);
24335 	/*
24336 	 * Establish the starting offset.  May not be zero if we are fragging
24337 	 * a fragment that is being forwarded.
24338 	 */
24339 	offset = offset & IPH_OFFSET;
24340 
24341 	/* TODO why is this test needed? */
24342 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24343 	if (((max_frag - LENGTH) & ~7) < 8) {
24344 		/* TODO: notify ulp somehow */
24345 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24346 		freemsg(mp);
24347 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24348 		    "ip_wput_frag_end:(%S)",
24349 		    "len < 8");
24350 		return;
24351 	}
24352 
24353 	hdr_len = (V_HLEN & 0xF) << 2;
24354 
24355 	ipha->ipha_hdr_checksum = 0;
24356 
24357 	/*
24358 	 * Establish the number of bytes maximum per frag, after putting
24359 	 * in the header.
24360 	 */
24361 	len = (max_frag - hdr_len) & ~7;
24362 
24363 	/* Check if we can use MDT to send out the frags. */
24364 	ASSERT(!IRE_IS_LOCAL(ire));
24365 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24366 	    ipst->ips_ip_multidata_outbound &&
24367 	    !(ire->ire_flags & RTF_MULTIRT) &&
24368 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24369 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24370 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24371 		ASSERT(ill->ill_mdt_capab != NULL);
24372 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24373 			/*
24374 			 * If MDT has been previously turned off in the past,
24375 			 * and we currently can do MDT (due to IPQoS policy
24376 			 * removal, etc.) then enable it for this interface.
24377 			 */
24378 			ill->ill_mdt_capab->ill_mdt_on = 1;
24379 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24380 			    ill->ill_name));
24381 		}
24382 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24383 		    offset);
24384 		return;
24385 	}
24386 
24387 	/* Get a copy of the header for the trailing frags */
24388 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24389 	    mp);
24390 	if (!hdr_mp) {
24391 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24392 		freemsg(mp);
24393 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24394 		    "ip_wput_frag_end:(%S)",
24395 		    "couldn't copy hdr");
24396 		return;
24397 	}
24398 
24399 	/* Store the starting offset, with the MoreFrags flag. */
24400 	i1 = offset | IPH_MF | frag_flag;
24401 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24402 
24403 	/* Establish the ending byte offset, based on the starting offset. */
24404 	offset <<= 3;
24405 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24406 
24407 	/* Store the length of the first fragment in the IP header. */
24408 	i1 = len + hdr_len;
24409 	ASSERT(i1 <= IP_MAXPACKET);
24410 	ipha->ipha_length = htons((uint16_t)i1);
24411 
24412 	/*
24413 	 * Compute the IP header checksum for the first frag.  We have to
24414 	 * watch out that we stop at the end of the header.
24415 	 */
24416 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24417 
24418 	/*
24419 	 * Now carve off the first frag.  Note that this will include the
24420 	 * original IP header.
24421 	 */
24422 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24423 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24424 		freeb(hdr_mp);
24425 		freemsg(mp_orig);
24426 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24427 		    "ip_wput_frag_end:(%S)",
24428 		    "couldn't carve first");
24429 		return;
24430 	}
24431 
24432 	/*
24433 	 * Multirouting case. Each fragment is replicated
24434 	 * via all non-condemned RTF_MULTIRT routes
24435 	 * currently resolved.
24436 	 * We ensure that first_ire is the first RTF_MULTIRT
24437 	 * ire in the bucket.
24438 	 */
24439 	if (ire->ire_flags & RTF_MULTIRT) {
24440 		irb = ire->ire_bucket;
24441 		ASSERT(irb != NULL);
24442 
24443 		multirt_send = B_TRUE;
24444 
24445 		/* Make sure we do not omit any multiroute ire. */
24446 		IRB_REFHOLD(irb);
24447 		for (first_ire = irb->irb_ire;
24448 		    first_ire != NULL;
24449 		    first_ire = first_ire->ire_next) {
24450 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24451 			    (first_ire->ire_addr == ire->ire_addr) &&
24452 			    !(first_ire->ire_marks &
24453 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24454 				break;
24455 		}
24456 
24457 		if (first_ire != NULL) {
24458 			if (first_ire != ire) {
24459 				IRE_REFHOLD(first_ire);
24460 				/*
24461 				 * Do not release the ire passed in
24462 				 * as the argument.
24463 				 */
24464 				ire = first_ire;
24465 			} else {
24466 				first_ire = NULL;
24467 			}
24468 		}
24469 		IRB_REFRELE(irb);
24470 
24471 		/*
24472 		 * Save the first ire; we will need to restore it
24473 		 * for the trailing frags.
24474 		 * We REFHOLD save_ire, as each iterated ire will be
24475 		 * REFRELEd.
24476 		 */
24477 		save_ire = ire;
24478 		IRE_REFHOLD(save_ire);
24479 	}
24480 
24481 	/*
24482 	 * First fragment emission loop.
24483 	 * In most cases, the emission loop below is entered only
24484 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24485 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24486 	 * bucket, and send the fragment through all crossed
24487 	 * RTF_MULTIRT routes.
24488 	 */
24489 	do {
24490 		if (ire->ire_flags & RTF_MULTIRT) {
24491 			/*
24492 			 * We are in a multiple send case, need to get
24493 			 * the next ire and make a copy of the packet.
24494 			 * ire1 holds here the next ire to process in the
24495 			 * bucket. If multirouting is expected,
24496 			 * any non-RTF_MULTIRT ire that has the
24497 			 * right destination address is ignored.
24498 			 *
24499 			 * We have to take into account the MTU of
24500 			 * each walked ire. max_frag is set by the
24501 			 * the caller and generally refers to
24502 			 * the primary ire entry. Here we ensure that
24503 			 * no route with a lower MTU will be used, as
24504 			 * fragments are carved once for all ires,
24505 			 * then replicated.
24506 			 */
24507 			ASSERT(irb != NULL);
24508 			IRB_REFHOLD(irb);
24509 			for (ire1 = ire->ire_next;
24510 			    ire1 != NULL;
24511 			    ire1 = ire1->ire_next) {
24512 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24513 					continue;
24514 				if (ire1->ire_addr != ire->ire_addr)
24515 					continue;
24516 				if (ire1->ire_marks &
24517 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24518 					continue;
24519 				/*
24520 				 * Ensure we do not exceed the MTU
24521 				 * of the next route.
24522 				 */
24523 				if (ire1->ire_max_frag < max_frag) {
24524 					ip_multirt_bad_mtu(ire1, max_frag);
24525 					continue;
24526 				}
24527 
24528 				/* Got one. */
24529 				IRE_REFHOLD(ire1);
24530 				break;
24531 			}
24532 			IRB_REFRELE(irb);
24533 
24534 			if (ire1 != NULL) {
24535 				next_mp = copyb(mp);
24536 				if ((next_mp == NULL) ||
24537 				    ((mp->b_cont != NULL) &&
24538 				    ((next_mp->b_cont =
24539 				    dupmsg(mp->b_cont)) == NULL))) {
24540 					freemsg(next_mp);
24541 					next_mp = NULL;
24542 					ire_refrele(ire1);
24543 					ire1 = NULL;
24544 				}
24545 			}
24546 
24547 			/* Last multiroute ire; don't loop anymore. */
24548 			if (ire1 == NULL) {
24549 				multirt_send = B_FALSE;
24550 			}
24551 		}
24552 
24553 		ll_hdr_len = 0;
24554 		LOCK_IRE_FP_MP(ire);
24555 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24556 		if (ll_hdr_mp != NULL) {
24557 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24558 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24559 		} else {
24560 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24561 		}
24562 
24563 		/* If there is a transmit header, get a copy for this frag. */
24564 		/*
24565 		 * TODO: should check db_ref before calling ip_carve_mp since
24566 		 * it might give us a dup.
24567 		 */
24568 		if (!ll_hdr_mp) {
24569 			/* No xmit header. */
24570 			xmit_mp = mp;
24571 
24572 		/* We have a link-layer header that can fit in our mblk. */
24573 		} else if (mp->b_datap->db_ref == 1 &&
24574 		    ll_hdr_len != 0 &&
24575 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24576 			/* M_DATA fastpath */
24577 			mp->b_rptr -= ll_hdr_len;
24578 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24579 			xmit_mp = mp;
24580 
24581 		/* Corner case if copyb has failed */
24582 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24583 			UNLOCK_IRE_FP_MP(ire);
24584 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24585 			freeb(hdr_mp);
24586 			freemsg(mp);
24587 			freemsg(mp_orig);
24588 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24589 			    "ip_wput_frag_end:(%S)",
24590 			    "discard");
24591 
24592 			if (multirt_send) {
24593 				ASSERT(ire1);
24594 				ASSERT(next_mp);
24595 
24596 				freemsg(next_mp);
24597 				ire_refrele(ire1);
24598 			}
24599 			if (save_ire != NULL)
24600 				IRE_REFRELE(save_ire);
24601 
24602 			if (first_ire != NULL)
24603 				ire_refrele(first_ire);
24604 			return;
24605 
24606 		/*
24607 		 * Case of res_mp OR the fastpath mp can't fit
24608 		 * in the mblk
24609 		 */
24610 		} else {
24611 			xmit_mp->b_cont = mp;
24612 
24613 			/*
24614 			 * Get priority marking, if any.
24615 			 * We propagate the CoS marking from the
24616 			 * original packet that went to QoS processing
24617 			 * in ip_wput_ire to the newly carved mp.
24618 			 */
24619 			if (DB_TYPE(xmit_mp) == M_DATA)
24620 				xmit_mp->b_band = mp->b_band;
24621 		}
24622 		UNLOCK_IRE_FP_MP(ire);
24623 
24624 		q = ire->ire_stq;
24625 		out_ill = (ill_t *)q->q_ptr;
24626 
24627 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24628 
24629 		DTRACE_PROBE4(ip4__physical__out__start,
24630 		    ill_t *, NULL, ill_t *, out_ill,
24631 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24632 
24633 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24634 		    ipst->ips_ipv4firewall_physical_out,
24635 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24636 
24637 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24638 
24639 		if (xmit_mp != NULL) {
24640 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24641 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24642 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24643 
24644 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24645 
24646 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24647 			UPDATE_MIB(out_ill->ill_ip_mib,
24648 			    ipIfStatsHCOutOctets, i1);
24649 
24650 			if (pkt_type != OB_PKT) {
24651 				/*
24652 				 * Update the packet count and MIB stats
24653 				 * of trailing RTF_MULTIRT ires.
24654 				 */
24655 				UPDATE_OB_PKT_COUNT(ire);
24656 				BUMP_MIB(out_ill->ill_ip_mib,
24657 				    ipIfStatsOutFragReqds);
24658 			}
24659 		}
24660 
24661 		if (multirt_send) {
24662 			/*
24663 			 * We are in a multiple send case; look for
24664 			 * the next ire and re-enter the loop.
24665 			 */
24666 			ASSERT(ire1);
24667 			ASSERT(next_mp);
24668 			/* REFRELE the current ire before looping */
24669 			ire_refrele(ire);
24670 			ire = ire1;
24671 			ire1 = NULL;
24672 			mp = next_mp;
24673 			next_mp = NULL;
24674 		}
24675 	} while (multirt_send);
24676 
24677 	ASSERT(ire1 == NULL);
24678 
24679 	/* Restore the original ire; we need it for the trailing frags */
24680 	if (save_ire != NULL) {
24681 		/* REFRELE the last iterated ire */
24682 		ire_refrele(ire);
24683 		/* save_ire has been REFHOLDed */
24684 		ire = save_ire;
24685 		save_ire = NULL;
24686 		q = ire->ire_stq;
24687 	}
24688 
24689 	if (pkt_type == OB_PKT) {
24690 		UPDATE_OB_PKT_COUNT(ire);
24691 	} else {
24692 		out_ill = (ill_t *)q->q_ptr;
24693 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24694 		UPDATE_IB_PKT_COUNT(ire);
24695 	}
24696 
24697 	/* Advance the offset to the second frag starting point. */
24698 	offset += len;
24699 	/*
24700 	 * Update hdr_len from the copied header - there might be less options
24701 	 * in the later fragments.
24702 	 */
24703 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24704 	/* Loop until done. */
24705 	for (;;) {
24706 		uint16_t	offset_and_flags;
24707 		uint16_t	ip_len;
24708 
24709 		if (ip_data_end - offset > len) {
24710 			/*
24711 			 * Carve off the appropriate amount from the original
24712 			 * datagram.
24713 			 */
24714 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24715 				mp = NULL;
24716 				break;
24717 			}
24718 			/*
24719 			 * More frags after this one.  Get another copy
24720 			 * of the header.
24721 			 */
24722 			if (carve_mp->b_datap->db_ref == 1 &&
24723 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24724 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24725 				/* Inline IP header */
24726 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24727 				    hdr_mp->b_rptr;
24728 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24729 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24730 				mp = carve_mp;
24731 			} else {
24732 				if (!(mp = copyb(hdr_mp))) {
24733 					freemsg(carve_mp);
24734 					break;
24735 				}
24736 				/* Get priority marking, if any. */
24737 				mp->b_band = carve_mp->b_band;
24738 				mp->b_cont = carve_mp;
24739 			}
24740 			ipha = (ipha_t *)mp->b_rptr;
24741 			offset_and_flags = IPH_MF;
24742 		} else {
24743 			/*
24744 			 * Last frag.  Consume the header. Set len to
24745 			 * the length of this last piece.
24746 			 */
24747 			len = ip_data_end - offset;
24748 
24749 			/*
24750 			 * Carve off the appropriate amount from the original
24751 			 * datagram.
24752 			 */
24753 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24754 				mp = NULL;
24755 				break;
24756 			}
24757 			if (carve_mp->b_datap->db_ref == 1 &&
24758 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24759 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24760 				/* Inline IP header */
24761 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24762 				    hdr_mp->b_rptr;
24763 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24764 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24765 				mp = carve_mp;
24766 				freeb(hdr_mp);
24767 				hdr_mp = mp;
24768 			} else {
24769 				mp = hdr_mp;
24770 				/* Get priority marking, if any. */
24771 				mp->b_band = carve_mp->b_band;
24772 				mp->b_cont = carve_mp;
24773 			}
24774 			ipha = (ipha_t *)mp->b_rptr;
24775 			/* A frag of a frag might have IPH_MF non-zero */
24776 			offset_and_flags =
24777 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24778 			    IPH_MF;
24779 		}
24780 		offset_and_flags |= (uint16_t)(offset >> 3);
24781 		offset_and_flags |= (uint16_t)frag_flag;
24782 		/* Store the offset and flags in the IP header. */
24783 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24784 
24785 		/* Store the length in the IP header. */
24786 		ip_len = (uint16_t)(len + hdr_len);
24787 		ipha->ipha_length = htons(ip_len);
24788 
24789 		/*
24790 		 * Set the IP header checksum.	Note that mp is just
24791 		 * the header, so this is easy to pass to ip_csum.
24792 		 */
24793 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24794 
24795 		/* Attach a transmit header, if any, and ship it. */
24796 		if (pkt_type == OB_PKT) {
24797 			UPDATE_OB_PKT_COUNT(ire);
24798 		} else {
24799 			out_ill = (ill_t *)q->q_ptr;
24800 			BUMP_MIB(out_ill->ill_ip_mib,
24801 			    ipIfStatsHCOutForwDatagrams);
24802 			UPDATE_IB_PKT_COUNT(ire);
24803 		}
24804 
24805 		if (ire->ire_flags & RTF_MULTIRT) {
24806 			irb = ire->ire_bucket;
24807 			ASSERT(irb != NULL);
24808 
24809 			multirt_send = B_TRUE;
24810 
24811 			/*
24812 			 * Save the original ire; we will need to restore it
24813 			 * for the tailing frags.
24814 			 */
24815 			save_ire = ire;
24816 			IRE_REFHOLD(save_ire);
24817 		}
24818 		/*
24819 		 * Emission loop for this fragment, similar
24820 		 * to what is done for the first fragment.
24821 		 */
24822 		do {
24823 			if (multirt_send) {
24824 				/*
24825 				 * We are in a multiple send case, need to get
24826 				 * the next ire and make a copy of the packet.
24827 				 */
24828 				ASSERT(irb != NULL);
24829 				IRB_REFHOLD(irb);
24830 				for (ire1 = ire->ire_next;
24831 				    ire1 != NULL;
24832 				    ire1 = ire1->ire_next) {
24833 					if (!(ire1->ire_flags & RTF_MULTIRT))
24834 						continue;
24835 					if (ire1->ire_addr != ire->ire_addr)
24836 						continue;
24837 					if (ire1->ire_marks &
24838 					    (IRE_MARK_CONDEMNED |
24839 					    IRE_MARK_TESTHIDDEN))
24840 						continue;
24841 					/*
24842 					 * Ensure we do not exceed the MTU
24843 					 * of the next route.
24844 					 */
24845 					if (ire1->ire_max_frag < max_frag) {
24846 						ip_multirt_bad_mtu(ire1,
24847 						    max_frag);
24848 						continue;
24849 					}
24850 
24851 					/* Got one. */
24852 					IRE_REFHOLD(ire1);
24853 					break;
24854 				}
24855 				IRB_REFRELE(irb);
24856 
24857 				if (ire1 != NULL) {
24858 					next_mp = copyb(mp);
24859 					if ((next_mp == NULL) ||
24860 					    ((mp->b_cont != NULL) &&
24861 					    ((next_mp->b_cont =
24862 					    dupmsg(mp->b_cont)) == NULL))) {
24863 						freemsg(next_mp);
24864 						next_mp = NULL;
24865 						ire_refrele(ire1);
24866 						ire1 = NULL;
24867 					}
24868 				}
24869 
24870 				/* Last multiroute ire; don't loop anymore. */
24871 				if (ire1 == NULL) {
24872 					multirt_send = B_FALSE;
24873 				}
24874 			}
24875 
24876 			/* Update transmit header */
24877 			ll_hdr_len = 0;
24878 			LOCK_IRE_FP_MP(ire);
24879 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24880 			if (ll_hdr_mp != NULL) {
24881 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24882 				ll_hdr_len = MBLKL(ll_hdr_mp);
24883 			} else {
24884 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24885 			}
24886 
24887 			if (!ll_hdr_mp) {
24888 				xmit_mp = mp;
24889 
24890 			/*
24891 			 * We have link-layer header that can fit in
24892 			 * our mblk.
24893 			 */
24894 			} else if (mp->b_datap->db_ref == 1 &&
24895 			    ll_hdr_len != 0 &&
24896 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24897 				/* M_DATA fastpath */
24898 				mp->b_rptr -= ll_hdr_len;
24899 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24900 				    ll_hdr_len);
24901 				xmit_mp = mp;
24902 
24903 			/*
24904 			 * Case of res_mp OR the fastpath mp can't fit
24905 			 * in the mblk
24906 			 */
24907 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24908 				xmit_mp->b_cont = mp;
24909 				/* Get priority marking, if any. */
24910 				if (DB_TYPE(xmit_mp) == M_DATA)
24911 					xmit_mp->b_band = mp->b_band;
24912 
24913 			/* Corner case if copyb failed */
24914 			} else {
24915 				/*
24916 				 * Exit both the replication and
24917 				 * fragmentation loops.
24918 				 */
24919 				UNLOCK_IRE_FP_MP(ire);
24920 				goto drop_pkt;
24921 			}
24922 			UNLOCK_IRE_FP_MP(ire);
24923 
24924 			mp1 = mp;
24925 			out_ill = (ill_t *)q->q_ptr;
24926 
24927 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24928 
24929 			DTRACE_PROBE4(ip4__physical__out__start,
24930 			    ill_t *, NULL, ill_t *, out_ill,
24931 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24932 
24933 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24934 			    ipst->ips_ipv4firewall_physical_out,
24935 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24936 
24937 			DTRACE_PROBE1(ip4__physical__out__end,
24938 			    mblk_t *, xmit_mp);
24939 
24940 			if (mp != mp1 && hdr_mp == mp1)
24941 				hdr_mp = mp;
24942 			if (mp != mp1 && mp_orig == mp1)
24943 				mp_orig = mp;
24944 
24945 			if (xmit_mp != NULL) {
24946 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24947 				    NULL, void_ip_t *, ipha,
24948 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24949 				    ipha, ip6_t *, NULL, int, 0);
24950 
24951 				ILL_SEND_TX(out_ill, ire, connp,
24952 				    xmit_mp, 0, connp);
24953 
24954 				BUMP_MIB(out_ill->ill_ip_mib,
24955 				    ipIfStatsHCOutTransmits);
24956 				UPDATE_MIB(out_ill->ill_ip_mib,
24957 				    ipIfStatsHCOutOctets, ip_len);
24958 
24959 				if (pkt_type != OB_PKT) {
24960 					/*
24961 					 * Update the packet count of trailing
24962 					 * RTF_MULTIRT ires.
24963 					 */
24964 					UPDATE_OB_PKT_COUNT(ire);
24965 				}
24966 			}
24967 
24968 			/* All done if we just consumed the hdr_mp. */
24969 			if (mp == hdr_mp) {
24970 				last_frag = B_TRUE;
24971 				BUMP_MIB(out_ill->ill_ip_mib,
24972 				    ipIfStatsOutFragOKs);
24973 			}
24974 
24975 			if (multirt_send) {
24976 				/*
24977 				 * We are in a multiple send case; look for
24978 				 * the next ire and re-enter the loop.
24979 				 */
24980 				ASSERT(ire1);
24981 				ASSERT(next_mp);
24982 				/* REFRELE the current ire before looping */
24983 				ire_refrele(ire);
24984 				ire = ire1;
24985 				ire1 = NULL;
24986 				q = ire->ire_stq;
24987 				mp = next_mp;
24988 				next_mp = NULL;
24989 			}
24990 		} while (multirt_send);
24991 		/*
24992 		 * Restore the original ire; we need it for the
24993 		 * trailing frags
24994 		 */
24995 		if (save_ire != NULL) {
24996 			ASSERT(ire1 == NULL);
24997 			/* REFRELE the last iterated ire */
24998 			ire_refrele(ire);
24999 			/* save_ire has been REFHOLDed */
25000 			ire = save_ire;
25001 			q = ire->ire_stq;
25002 			save_ire = NULL;
25003 		}
25004 
25005 		if (last_frag) {
25006 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25007 			    "ip_wput_frag_end:(%S)",
25008 			    "consumed hdr_mp");
25009 
25010 			if (first_ire != NULL)
25011 				ire_refrele(first_ire);
25012 			return;
25013 		}
25014 		/* Otherwise, advance and loop. */
25015 		offset += len;
25016 	}
25017 
25018 drop_pkt:
25019 	/* Clean up following allocation failure. */
25020 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25021 	freemsg(mp);
25022 	if (mp != hdr_mp)
25023 		freeb(hdr_mp);
25024 	if (mp != mp_orig)
25025 		freemsg(mp_orig);
25026 
25027 	if (save_ire != NULL)
25028 		IRE_REFRELE(save_ire);
25029 	if (first_ire != NULL)
25030 		ire_refrele(first_ire);
25031 
25032 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25033 	    "ip_wput_frag_end:(%S)",
25034 	    "end--alloc failure");
25035 }
25036 
25037 /*
25038  * Copy the header plus those options which have the copy bit set
25039  * src is the template to make sure we preserve the cred for TX purposes.
25040  */
25041 static mblk_t *
25042 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
25043     mblk_t *src)
25044 {
25045 	mblk_t	*mp;
25046 	uchar_t	*up;
25047 
25048 	/*
25049 	 * Quick check if we need to look for options without the copy bit
25050 	 * set
25051 	 */
25052 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
25053 	if (!mp)
25054 		return (mp);
25055 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25056 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25057 		bcopy(rptr, mp->b_rptr, hdr_len);
25058 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25059 		return (mp);
25060 	}
25061 	up  = mp->b_rptr;
25062 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25063 	up += IP_SIMPLE_HDR_LENGTH;
25064 	rptr += IP_SIMPLE_HDR_LENGTH;
25065 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25066 	while (hdr_len > 0) {
25067 		uint32_t optval;
25068 		uint32_t optlen;
25069 
25070 		optval = *rptr;
25071 		if (optval == IPOPT_EOL)
25072 			break;
25073 		if (optval == IPOPT_NOP)
25074 			optlen = 1;
25075 		else
25076 			optlen = rptr[1];
25077 		if (optval & IPOPT_COPY) {
25078 			bcopy(rptr, up, optlen);
25079 			up += optlen;
25080 		}
25081 		rptr += optlen;
25082 		hdr_len -= optlen;
25083 	}
25084 	/*
25085 	 * Make sure that we drop an even number of words by filling
25086 	 * with EOL to the next word boundary.
25087 	 */
25088 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25089 	    hdr_len & 0x3; hdr_len++)
25090 		*up++ = IPOPT_EOL;
25091 	mp->b_wptr = up;
25092 	/* Update header length */
25093 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25094 	return (mp);
25095 }
25096 
25097 /*
25098  * Delivery to local recipients including fanout to multiple recipients.
25099  * Does not do checksumming of UDP/TCP.
25100  * Note: q should be the read side queue for either the ill or conn.
25101  * Note: rq should be the read side q for the lower (ill) stream.
25102  * We don't send packets to IPPF processing, thus the last argument
25103  * to all the fanout calls are B_FALSE.
25104  */
25105 void
25106 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25107     int fanout_flags, zoneid_t zoneid)
25108 {
25109 	uint32_t	protocol;
25110 	mblk_t		*first_mp;
25111 	boolean_t	mctl_present;
25112 	int		ire_type;
25113 #define	rptr	((uchar_t *)ipha)
25114 	ip_stack_t	*ipst = ill->ill_ipst;
25115 
25116 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25117 	    "ip_wput_local_start: q %p", q);
25118 
25119 	if (ire != NULL) {
25120 		ire_type = ire->ire_type;
25121 	} else {
25122 		/*
25123 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25124 		 * packet is not multicast, we can't tell the ire type.
25125 		 */
25126 		ASSERT(CLASSD(ipha->ipha_dst));
25127 		ire_type = IRE_BROADCAST;
25128 	}
25129 
25130 	first_mp = mp;
25131 	if (first_mp->b_datap->db_type == M_CTL) {
25132 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25133 		if (!io->ipsec_out_secure) {
25134 			/*
25135 			 * This ipsec_out_t was allocated in ip_wput
25136 			 * for multicast packets to store the ill_index.
25137 			 * As this is being delivered locally, we don't
25138 			 * need this anymore.
25139 			 */
25140 			mp = first_mp->b_cont;
25141 			freeb(first_mp);
25142 			first_mp = mp;
25143 			mctl_present = B_FALSE;
25144 		} else {
25145 			/*
25146 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25147 			 * security properties for the looped-back packet.
25148 			 */
25149 			mctl_present = B_TRUE;
25150 			mp = first_mp->b_cont;
25151 			ASSERT(mp != NULL);
25152 			ipsec_out_to_in(first_mp);
25153 		}
25154 	} else {
25155 		mctl_present = B_FALSE;
25156 	}
25157 
25158 	DTRACE_PROBE4(ip4__loopback__in__start,
25159 	    ill_t *, ill, ill_t *, NULL,
25160 	    ipha_t *, ipha, mblk_t *, first_mp);
25161 
25162 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25163 	    ipst->ips_ipv4firewall_loopback_in,
25164 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25165 
25166 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25167 
25168 	if (first_mp == NULL)
25169 		return;
25170 
25171 	if (ipst->ips_ipobs_enabled) {
25172 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25173 		zoneid_t stackzoneid = netstackid_to_zoneid(
25174 		    ipst->ips_netstack->netstack_stackid);
25175 
25176 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25177 		/*
25178 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25179 		 * address.  Restrict the lookup below to the destination zone.
25180 		 */
25181 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25182 			lookup_zoneid = zoneid;
25183 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25184 		    lookup_zoneid);
25185 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25186 		    IPV4_VERSION, 0, ipst);
25187 	}
25188 
25189 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25190 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25191 	    int, 1);
25192 
25193 	ipst->ips_loopback_packets++;
25194 
25195 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25196 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25197 	if (!IS_SIMPLE_IPH(ipha)) {
25198 		ip_wput_local_options(ipha, ipst);
25199 	}
25200 
25201 	protocol = ipha->ipha_protocol;
25202 	switch (protocol) {
25203 	case IPPROTO_ICMP: {
25204 		ire_t		*ire_zone;
25205 		ilm_t		*ilm;
25206 		mblk_t		*mp1;
25207 		zoneid_t	last_zoneid;
25208 		ilm_walker_t	ilw;
25209 
25210 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25211 			ASSERT(ire_type == IRE_BROADCAST);
25212 			/*
25213 			 * In the multicast case, applications may have joined
25214 			 * the group from different zones, so we need to deliver
25215 			 * the packet to each of them. Loop through the
25216 			 * multicast memberships structures (ilm) on the receive
25217 			 * ill and send a copy of the packet up each matching
25218 			 * one. However, we don't do this for multicasts sent on
25219 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25220 			 * they must stay in the sender's zone.
25221 			 *
25222 			 * ilm_add_v6() ensures that ilms in the same zone are
25223 			 * contiguous in the ill_ilm list. We use this property
25224 			 * to avoid sending duplicates needed when two
25225 			 * applications in the same zone join the same group on
25226 			 * different logical interfaces: we ignore the ilm if
25227 			 * it's zoneid is the same as the last matching one.
25228 			 * In addition, the sending of the packet for
25229 			 * ire_zoneid is delayed until all of the other ilms
25230 			 * have been exhausted.
25231 			 */
25232 			last_zoneid = -1;
25233 			ilm = ilm_walker_start(&ilw, ill);
25234 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25235 				if (ipha->ipha_dst != ilm->ilm_addr ||
25236 				    ilm->ilm_zoneid == last_zoneid ||
25237 				    ilm->ilm_zoneid == zoneid ||
25238 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25239 					continue;
25240 				mp1 = ip_copymsg(first_mp);
25241 				if (mp1 == NULL)
25242 					continue;
25243 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25244 				    0, 0, mctl_present, B_FALSE, ill,
25245 				    ilm->ilm_zoneid);
25246 				last_zoneid = ilm->ilm_zoneid;
25247 			}
25248 			ilm_walker_finish(&ilw);
25249 			/*
25250 			 * Loopback case: the sending endpoint has
25251 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25252 			 * dispatch the multicast packet to the sending zone.
25253 			 */
25254 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25255 				freemsg(first_mp);
25256 				return;
25257 			}
25258 		} else if (ire_type == IRE_BROADCAST) {
25259 			/*
25260 			 * In the broadcast case, there may be many zones
25261 			 * which need a copy of the packet delivered to them.
25262 			 * There is one IRE_BROADCAST per broadcast address
25263 			 * and per zone; we walk those using a helper function.
25264 			 * In addition, the sending of the packet for zoneid is
25265 			 * delayed until all of the other ires have been
25266 			 * processed.
25267 			 */
25268 			IRB_REFHOLD(ire->ire_bucket);
25269 			ire_zone = NULL;
25270 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25271 			    ire)) != NULL) {
25272 				mp1 = ip_copymsg(first_mp);
25273 				if (mp1 == NULL)
25274 					continue;
25275 
25276 				UPDATE_IB_PKT_COUNT(ire_zone);
25277 				ire_zone->ire_last_used_time = lbolt;
25278 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25279 				    mctl_present, B_FALSE, ill,
25280 				    ire_zone->ire_zoneid);
25281 			}
25282 			IRB_REFRELE(ire->ire_bucket);
25283 		}
25284 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25285 		    0, mctl_present, B_FALSE, ill, zoneid);
25286 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25287 		    "ip_wput_local_end: q %p (%S)",
25288 		    q, "icmp");
25289 		return;
25290 	}
25291 	case IPPROTO_IGMP:
25292 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25293 			/* Bad packet - discarded by igmp_input */
25294 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25295 			    "ip_wput_local_end: q %p (%S)",
25296 			    q, "igmp_input--bad packet");
25297 			if (mctl_present)
25298 				freeb(first_mp);
25299 			return;
25300 		}
25301 		/*
25302 		 * igmp_input() may have returned the pulled up message.
25303 		 * So first_mp and ipha need to be reinitialized.
25304 		 */
25305 		ipha = (ipha_t *)mp->b_rptr;
25306 		if (mctl_present)
25307 			first_mp->b_cont = mp;
25308 		else
25309 			first_mp = mp;
25310 		/* deliver to local raw users */
25311 		break;
25312 	case IPPROTO_ENCAP:
25313 		/*
25314 		 * This case is covered by either ip_fanout_proto, or by
25315 		 * the above security processing for self-tunneled packets.
25316 		 */
25317 		break;
25318 	case IPPROTO_UDP: {
25319 		uint16_t	*up;
25320 		uint32_t	ports;
25321 
25322 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25323 		    UDP_PORTS_OFFSET);
25324 		/* Force a 'valid' checksum. */
25325 		up[3] = 0;
25326 
25327 		ports = *(uint32_t *)up;
25328 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25329 		    (ire_type == IRE_BROADCAST),
25330 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25331 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25332 		    ill, zoneid);
25333 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25334 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25335 		return;
25336 	}
25337 	case IPPROTO_TCP: {
25338 
25339 		/*
25340 		 * For TCP, discard broadcast packets.
25341 		 */
25342 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25343 			freemsg(first_mp);
25344 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25345 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25346 			return;
25347 		}
25348 
25349 		if (mp->b_datap->db_type == M_DATA) {
25350 			/*
25351 			 * M_DATA mblk, so init mblk (chain) for no struio().
25352 			 */
25353 			mblk_t	*mp1 = mp;
25354 
25355 			do {
25356 				mp1->b_datap->db_struioflag = 0;
25357 			} while ((mp1 = mp1->b_cont) != NULL);
25358 		}
25359 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25360 		    <= mp->b_wptr);
25361 		ip_fanout_tcp(q, first_mp, ill, ipha,
25362 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25363 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25364 		    mctl_present, B_FALSE, zoneid);
25365 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25366 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25367 		return;
25368 	}
25369 	case IPPROTO_SCTP:
25370 	{
25371 		uint32_t	ports;
25372 
25373 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25374 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25375 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25376 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25377 		return;
25378 	}
25379 
25380 	default:
25381 		break;
25382 	}
25383 	/*
25384 	 * Find a client for some other protocol.  We give
25385 	 * copies to multiple clients, if more than one is
25386 	 * bound.
25387 	 */
25388 	ip_fanout_proto(q, first_mp, ill, ipha,
25389 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25390 	    mctl_present, B_FALSE, ill, zoneid);
25391 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25392 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25393 #undef	rptr
25394 }
25395 
25396 /*
25397  * Update any source route, record route, or timestamp options.
25398  * Check that we are at end of strict source route.
25399  * The options have been sanity checked by ip_wput_options().
25400  */
25401 static void
25402 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25403 {
25404 	ipoptp_t	opts;
25405 	uchar_t		*opt;
25406 	uint8_t		optval;
25407 	uint8_t		optlen;
25408 	ipaddr_t	dst;
25409 	uint32_t	ts;
25410 	ire_t		*ire;
25411 	timestruc_t	now;
25412 
25413 	ip2dbg(("ip_wput_local_options\n"));
25414 	for (optval = ipoptp_first(&opts, ipha);
25415 	    optval != IPOPT_EOL;
25416 	    optval = ipoptp_next(&opts)) {
25417 		opt = opts.ipoptp_cur;
25418 		optlen = opts.ipoptp_len;
25419 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25420 		switch (optval) {
25421 			uint32_t off;
25422 		case IPOPT_SSRR:
25423 		case IPOPT_LSRR:
25424 			off = opt[IPOPT_OFFSET];
25425 			off--;
25426 			if (optlen < IP_ADDR_LEN ||
25427 			    off > optlen - IP_ADDR_LEN) {
25428 				/* End of source route */
25429 				break;
25430 			}
25431 			/*
25432 			 * This will only happen if two consecutive entries
25433 			 * in the source route contains our address or if
25434 			 * it is a packet with a loose source route which
25435 			 * reaches us before consuming the whole source route
25436 			 */
25437 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25438 			if (optval == IPOPT_SSRR) {
25439 				return;
25440 			}
25441 			/*
25442 			 * Hack: instead of dropping the packet truncate the
25443 			 * source route to what has been used by filling the
25444 			 * rest with IPOPT_NOP.
25445 			 */
25446 			opt[IPOPT_OLEN] = (uint8_t)off;
25447 			while (off < optlen) {
25448 				opt[off++] = IPOPT_NOP;
25449 			}
25450 			break;
25451 		case IPOPT_RR:
25452 			off = opt[IPOPT_OFFSET];
25453 			off--;
25454 			if (optlen < IP_ADDR_LEN ||
25455 			    off > optlen - IP_ADDR_LEN) {
25456 				/* No more room - ignore */
25457 				ip1dbg((
25458 				    "ip_wput_forward_options: end of RR\n"));
25459 				break;
25460 			}
25461 			dst = htonl(INADDR_LOOPBACK);
25462 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25463 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25464 			break;
25465 		case IPOPT_TS:
25466 			/* Insert timestamp if there is romm */
25467 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25468 			case IPOPT_TS_TSONLY:
25469 				off = IPOPT_TS_TIMELEN;
25470 				break;
25471 			case IPOPT_TS_PRESPEC:
25472 			case IPOPT_TS_PRESPEC_RFC791:
25473 				/* Verify that the address matched */
25474 				off = opt[IPOPT_OFFSET] - 1;
25475 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25476 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25477 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25478 				    ipst);
25479 				if (ire == NULL) {
25480 					/* Not for us */
25481 					break;
25482 				}
25483 				ire_refrele(ire);
25484 				/* FALLTHRU */
25485 			case IPOPT_TS_TSANDADDR:
25486 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25487 				break;
25488 			default:
25489 				/*
25490 				 * ip_*put_options should have already
25491 				 * dropped this packet.
25492 				 */
25493 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25494 				    "unknown IT - bug in ip_wput_options?\n");
25495 				return;	/* Keep "lint" happy */
25496 			}
25497 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25498 				/* Increase overflow counter */
25499 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25500 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25501 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25502 				    (off << 4);
25503 				break;
25504 			}
25505 			off = opt[IPOPT_OFFSET] - 1;
25506 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25507 			case IPOPT_TS_PRESPEC:
25508 			case IPOPT_TS_PRESPEC_RFC791:
25509 			case IPOPT_TS_TSANDADDR:
25510 				dst = htonl(INADDR_LOOPBACK);
25511 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25512 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25513 				/* FALLTHRU */
25514 			case IPOPT_TS_TSONLY:
25515 				off = opt[IPOPT_OFFSET] - 1;
25516 				/* Compute # of milliseconds since midnight */
25517 				gethrestime(&now);
25518 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25519 				    now.tv_nsec / (NANOSEC / MILLISEC);
25520 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25521 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25522 				break;
25523 			}
25524 			break;
25525 		}
25526 	}
25527 }
25528 
25529 /*
25530  * Send out a multicast packet on interface ipif.
25531  * The sender does not have an conn.
25532  * Caller verifies that this isn't a PHYI_LOOPBACK.
25533  */
25534 void
25535 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25536 {
25537 	ipha_t	*ipha;
25538 	ire_t	*ire;
25539 	ipaddr_t	dst;
25540 	mblk_t		*first_mp;
25541 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25542 
25543 	/* igmp_sendpkt always allocates a ipsec_out_t */
25544 	ASSERT(mp->b_datap->db_type == M_CTL);
25545 	ASSERT(!ipif->ipif_isv6);
25546 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25547 
25548 	first_mp = mp;
25549 	mp = first_mp->b_cont;
25550 	ASSERT(mp->b_datap->db_type == M_DATA);
25551 	ipha = (ipha_t *)mp->b_rptr;
25552 
25553 	/*
25554 	 * Find an IRE which matches the destination and the outgoing
25555 	 * queue (i.e. the outgoing interface.)
25556 	 */
25557 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25558 		dst = ipif->ipif_pp_dst_addr;
25559 	else
25560 		dst = ipha->ipha_dst;
25561 	/*
25562 	 * The source address has already been initialized by the
25563 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25564 	 * be sufficient rather than MATCH_IRE_IPIF.
25565 	 *
25566 	 * This function is used for sending IGMP packets.  For IPMP,
25567 	 * we sidestep IGMP snooping issues by sending all multicast
25568 	 * traffic on a single interface in the IPMP group.
25569 	 */
25570 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25571 	    MATCH_IRE_ILL, ipst);
25572 	if (!ire) {
25573 		/*
25574 		 * Mark this packet to make it be delivered to
25575 		 * ip_wput_ire after the new ire has been
25576 		 * created.
25577 		 */
25578 		mp->b_prev = NULL;
25579 		mp->b_next = NULL;
25580 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25581 		    zoneid, &zero_info);
25582 		return;
25583 	}
25584 
25585 	/*
25586 	 * Honor the RTF_SETSRC flag; this is the only case
25587 	 * where we force this addr whatever the current src addr is,
25588 	 * because this address is set by igmp_sendpkt(), and
25589 	 * cannot be specified by any user.
25590 	 */
25591 	if (ire->ire_flags & RTF_SETSRC) {
25592 		ipha->ipha_src = ire->ire_src_addr;
25593 	}
25594 
25595 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25596 }
25597 
25598 /*
25599  * NOTE : This function does not ire_refrele the ire argument passed in.
25600  *
25601  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25602  * failure. The nce_fp_mp can vanish any time in the case of
25603  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25604  * the ire_lock to access the nce_fp_mp in this case.
25605  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25606  * prepending a fastpath message IPQoS processing must precede it, we also set
25607  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25608  * (IPQoS might have set the b_band for CoS marking).
25609  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25610  * must follow it so that IPQoS can mark the dl_priority field for CoS
25611  * marking, if needed.
25612  */
25613 static mblk_t *
25614 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25615     uint32_t ill_index, ipha_t **iphap)
25616 {
25617 	uint_t	hlen;
25618 	ipha_t *ipha;
25619 	mblk_t *mp1;
25620 	boolean_t qos_done = B_FALSE;
25621 	uchar_t	*ll_hdr;
25622 	ip_stack_t	*ipst = ire->ire_ipst;
25623 
25624 #define	rptr	((uchar_t *)ipha)
25625 
25626 	ipha = (ipha_t *)mp->b_rptr;
25627 	hlen = 0;
25628 	LOCK_IRE_FP_MP(ire);
25629 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25630 		ASSERT(DB_TYPE(mp1) == M_DATA);
25631 		/* Initiate IPPF processing */
25632 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25633 			UNLOCK_IRE_FP_MP(ire);
25634 			ip_process(proc, &mp, ill_index);
25635 			if (mp == NULL)
25636 				return (NULL);
25637 
25638 			ipha = (ipha_t *)mp->b_rptr;
25639 			LOCK_IRE_FP_MP(ire);
25640 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25641 				qos_done = B_TRUE;
25642 				goto no_fp_mp;
25643 			}
25644 			ASSERT(DB_TYPE(mp1) == M_DATA);
25645 		}
25646 		hlen = MBLKL(mp1);
25647 		/*
25648 		 * Check if we have enough room to prepend fastpath
25649 		 * header
25650 		 */
25651 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25652 			ll_hdr = rptr - hlen;
25653 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25654 			/*
25655 			 * Set the b_rptr to the start of the link layer
25656 			 * header
25657 			 */
25658 			mp->b_rptr = ll_hdr;
25659 			mp1 = mp;
25660 		} else {
25661 			mp1 = copyb(mp1);
25662 			if (mp1 == NULL)
25663 				goto unlock_err;
25664 			mp1->b_band = mp->b_band;
25665 			mp1->b_cont = mp;
25666 			/*
25667 			 * XXX disable ICK_VALID and compute checksum
25668 			 * here; can happen if nce_fp_mp changes and
25669 			 * it can't be copied now due to insufficient
25670 			 * space. (unlikely, fp mp can change, but it
25671 			 * does not increase in length)
25672 			 */
25673 		}
25674 		UNLOCK_IRE_FP_MP(ire);
25675 	} else {
25676 no_fp_mp:
25677 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25678 		if (mp1 == NULL) {
25679 unlock_err:
25680 			UNLOCK_IRE_FP_MP(ire);
25681 			freemsg(mp);
25682 			return (NULL);
25683 		}
25684 		UNLOCK_IRE_FP_MP(ire);
25685 		mp1->b_cont = mp;
25686 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25687 			ip_process(proc, &mp1, ill_index);
25688 			if (mp1 == NULL)
25689 				return (NULL);
25690 
25691 			if (mp1->b_cont == NULL)
25692 				ipha = NULL;
25693 			else
25694 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25695 		}
25696 	}
25697 
25698 	*iphap = ipha;
25699 	return (mp1);
25700 #undef rptr
25701 }
25702 
25703 /*
25704  * Finish the outbound IPsec processing for an IPv6 packet. This function
25705  * is called from ipsec_out_process() if the IPsec packet was processed
25706  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25707  * asynchronously.
25708  */
25709 void
25710 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25711     ire_t *ire_arg)
25712 {
25713 	in6_addr_t *v6dstp;
25714 	ire_t *ire;
25715 	mblk_t *mp;
25716 	ip6_t *ip6h1;
25717 	uint_t	ill_index;
25718 	ipsec_out_t *io;
25719 	boolean_t hwaccel;
25720 	uint32_t flags = IP6_NO_IPPOLICY;
25721 	int match_flags;
25722 	zoneid_t zoneid;
25723 	boolean_t ill_need_rele = B_FALSE;
25724 	boolean_t ire_need_rele = B_FALSE;
25725 	ip_stack_t	*ipst;
25726 
25727 	mp = ipsec_mp->b_cont;
25728 	ip6h1 = (ip6_t *)mp->b_rptr;
25729 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25730 	ASSERT(io->ipsec_out_ns != NULL);
25731 	ipst = io->ipsec_out_ns->netstack_ip;
25732 	ill_index = io->ipsec_out_ill_index;
25733 	if (io->ipsec_out_reachable) {
25734 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25735 	}
25736 	hwaccel = io->ipsec_out_accelerated;
25737 	zoneid = io->ipsec_out_zoneid;
25738 	ASSERT(zoneid != ALL_ZONES);
25739 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25740 	/* Multicast addresses should have non-zero ill_index. */
25741 	v6dstp = &ip6h->ip6_dst;
25742 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25743 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25744 
25745 	if (ill == NULL && ill_index != 0) {
25746 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25747 		/* Failure case frees things for us. */
25748 		if (ill == NULL)
25749 			return;
25750 
25751 		ill_need_rele = B_TRUE;
25752 	}
25753 	ASSERT(mp != NULL);
25754 
25755 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25756 		boolean_t unspec_src;
25757 		ipif_t	*ipif;
25758 
25759 		/*
25760 		 * Use the ill_index to get the right ill.
25761 		 */
25762 		unspec_src = io->ipsec_out_unspec_src;
25763 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25764 		if (ipif == NULL) {
25765 			if (ill_need_rele)
25766 				ill_refrele(ill);
25767 			freemsg(ipsec_mp);
25768 			return;
25769 		}
25770 
25771 		if (ire_arg != NULL) {
25772 			ire = ire_arg;
25773 		} else {
25774 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25775 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25776 			ire_need_rele = B_TRUE;
25777 		}
25778 		if (ire != NULL) {
25779 			ipif_refrele(ipif);
25780 			/*
25781 			 * XXX Do the multicast forwarding now, as the IPsec
25782 			 * processing has been done.
25783 			 */
25784 			goto send;
25785 		}
25786 
25787 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25788 		mp->b_prev = NULL;
25789 		mp->b_next = NULL;
25790 
25791 		/*
25792 		 * If the IPsec packet was processed asynchronously,
25793 		 * drop it now.
25794 		 */
25795 		if (q == NULL) {
25796 			if (ill_need_rele)
25797 				ill_refrele(ill);
25798 			freemsg(ipsec_mp);
25799 			return;
25800 		}
25801 
25802 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25803 		    unspec_src, zoneid);
25804 		ipif_refrele(ipif);
25805 	} else {
25806 		if (ire_arg != NULL) {
25807 			ire = ire_arg;
25808 		} else {
25809 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25810 			ire_need_rele = B_TRUE;
25811 		}
25812 		if (ire != NULL)
25813 			goto send;
25814 		/*
25815 		 * ire disappeared underneath.
25816 		 *
25817 		 * What we need to do here is the ip_newroute
25818 		 * logic to get the ire without doing the IPsec
25819 		 * processing. Follow the same old path. But this
25820 		 * time, ip_wput or ire_add_then_send will call us
25821 		 * directly as all the IPsec operations are done.
25822 		 */
25823 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25824 		mp->b_prev = NULL;
25825 		mp->b_next = NULL;
25826 
25827 		/*
25828 		 * If the IPsec packet was processed asynchronously,
25829 		 * drop it now.
25830 		 */
25831 		if (q == NULL) {
25832 			if (ill_need_rele)
25833 				ill_refrele(ill);
25834 			freemsg(ipsec_mp);
25835 			return;
25836 		}
25837 
25838 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25839 		    zoneid, ipst);
25840 	}
25841 	if (ill != NULL && ill_need_rele)
25842 		ill_refrele(ill);
25843 	return;
25844 send:
25845 	if (ill != NULL && ill_need_rele)
25846 		ill_refrele(ill);
25847 
25848 	/* Local delivery */
25849 	if (ire->ire_stq == NULL) {
25850 		ill_t	*out_ill;
25851 		ASSERT(q != NULL);
25852 
25853 		/* PFHooks: LOOPBACK_OUT */
25854 		out_ill = ire_to_ill(ire);
25855 
25856 		/*
25857 		 * DTrace this as ip:::send.  A blocked packet will fire the
25858 		 * send probe, but not the receive probe.
25859 		 */
25860 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25861 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25862 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25863 
25864 		DTRACE_PROBE4(ip6__loopback__out__start,
25865 		    ill_t *, NULL, ill_t *, out_ill,
25866 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25867 
25868 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25869 		    ipst->ips_ipv6firewall_loopback_out,
25870 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25871 
25872 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25873 
25874 		if (ipsec_mp != NULL) {
25875 			ip_wput_local_v6(RD(q), out_ill,
25876 			    ip6h, ipsec_mp, ire, 0, zoneid);
25877 		}
25878 		if (ire_need_rele)
25879 			ire_refrele(ire);
25880 		return;
25881 	}
25882 	/*
25883 	 * Everything is done. Send it out on the wire.
25884 	 * We force the insertion of a fragment header using the
25885 	 * IPH_FRAG_HDR flag in two cases:
25886 	 * - after reception of an ICMPv6 "packet too big" message
25887 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25888 	 * - for multirouted IPv6 packets, so that the receiver can
25889 	 *   discard duplicates according to their fragment identifier
25890 	 */
25891 	/* XXX fix flow control problems. */
25892 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25893 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25894 		if (hwaccel) {
25895 			/*
25896 			 * hardware acceleration does not handle these
25897 			 * "slow path" cases.
25898 			 */
25899 			/* IPsec KSTATS: should bump bean counter here. */
25900 			if (ire_need_rele)
25901 				ire_refrele(ire);
25902 			freemsg(ipsec_mp);
25903 			return;
25904 		}
25905 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25906 		    (mp->b_cont ? msgdsize(mp) :
25907 		    mp->b_wptr - (uchar_t *)ip6h)) {
25908 			/* IPsec KSTATS: should bump bean counter here. */
25909 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25910 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25911 			    msgdsize(mp)));
25912 			if (ire_need_rele)
25913 				ire_refrele(ire);
25914 			freemsg(ipsec_mp);
25915 			return;
25916 		}
25917 		ASSERT(mp->b_prev == NULL);
25918 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25919 		    ntohs(ip6h->ip6_plen) +
25920 		    IPV6_HDR_LEN, ire->ire_max_frag));
25921 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25922 		    ire->ire_max_frag);
25923 	} else {
25924 		UPDATE_OB_PKT_COUNT(ire);
25925 		ire->ire_last_used_time = lbolt;
25926 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25927 	}
25928 	if (ire_need_rele)
25929 		ire_refrele(ire);
25930 	freeb(ipsec_mp);
25931 }
25932 
25933 void
25934 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25935 {
25936 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25937 	da_ipsec_t *hada;	/* data attributes */
25938 	ill_t *ill = (ill_t *)q->q_ptr;
25939 
25940 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25941 
25942 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25943 		/* IPsec KSTATS: Bump lose counter here! */
25944 		freemsg(mp);
25945 		return;
25946 	}
25947 
25948 	/*
25949 	 * It's an IPsec packet that must be
25950 	 * accelerated by the Provider, and the
25951 	 * outbound ill is IPsec acceleration capable.
25952 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25953 	 * to the ill.
25954 	 * IPsec KSTATS: should bump packet counter here.
25955 	 */
25956 
25957 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25958 	if (hada_mp == NULL) {
25959 		/* IPsec KSTATS: should bump packet counter here. */
25960 		freemsg(mp);
25961 		return;
25962 	}
25963 
25964 	hada_mp->b_datap->db_type = M_CTL;
25965 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25966 	hada_mp->b_cont = mp;
25967 
25968 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25969 	bzero(hada, sizeof (da_ipsec_t));
25970 	hada->da_type = IPHADA_M_CTL;
25971 
25972 	putnext(q, hada_mp);
25973 }
25974 
25975 /*
25976  * Finish the outbound IPsec processing. This function is called from
25977  * ipsec_out_process() if the IPsec packet was processed
25978  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25979  * asynchronously.
25980  */
25981 void
25982 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25983     ire_t *ire_arg)
25984 {
25985 	uint32_t v_hlen_tos_len;
25986 	ipaddr_t	dst;
25987 	ipif_t	*ipif = NULL;
25988 	ire_t *ire;
25989 	ire_t *ire1 = NULL;
25990 	mblk_t *next_mp = NULL;
25991 	uint32_t max_frag;
25992 	boolean_t multirt_send = B_FALSE;
25993 	mblk_t *mp;
25994 	ipha_t *ipha1;
25995 	uint_t	ill_index;
25996 	ipsec_out_t *io;
25997 	int match_flags;
25998 	irb_t *irb = NULL;
25999 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26000 	zoneid_t zoneid;
26001 	ipxmit_state_t	pktxmit_state;
26002 	ip_stack_t	*ipst;
26003 
26004 #ifdef	_BIG_ENDIAN
26005 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26006 #else
26007 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26008 #endif
26009 
26010 	mp = ipsec_mp->b_cont;
26011 	ipha1 = (ipha_t *)mp->b_rptr;
26012 	ASSERT(mp != NULL);
26013 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26014 	dst = ipha->ipha_dst;
26015 
26016 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26017 	ill_index = io->ipsec_out_ill_index;
26018 	zoneid = io->ipsec_out_zoneid;
26019 	ASSERT(zoneid != ALL_ZONES);
26020 	ipst = io->ipsec_out_ns->netstack_ip;
26021 	ASSERT(io->ipsec_out_ns != NULL);
26022 
26023 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26024 	if (ill == NULL && ill_index != 0) {
26025 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
26026 		/* Failure case frees things for us. */
26027 		if (ill == NULL)
26028 			return;
26029 
26030 		ill_need_rele = B_TRUE;
26031 	}
26032 
26033 	if (CLASSD(dst)) {
26034 		boolean_t conn_dontroute;
26035 		/*
26036 		 * Use the ill_index to get the right ipif.
26037 		 */
26038 		conn_dontroute = io->ipsec_out_dontroute;
26039 		if (ill_index == 0)
26040 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26041 		else
26042 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26043 		if (ipif == NULL) {
26044 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26045 			    " multicast\n"));
26046 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26047 			freemsg(ipsec_mp);
26048 			goto done;
26049 		}
26050 		/*
26051 		 * ipha_src has already been intialized with the
26052 		 * value of the ipif in ip_wput. All we need now is
26053 		 * an ire to send this downstream.
26054 		 */
26055 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26056 		    msg_getlabel(mp), match_flags, ipst);
26057 		if (ire != NULL) {
26058 			ill_t *ill1;
26059 			/*
26060 			 * Do the multicast forwarding now, as the IPsec
26061 			 * processing has been done.
26062 			 */
26063 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26064 			    (ill1 = ire_to_ill(ire))) {
26065 				if (ip_mforward(ill1, ipha, mp)) {
26066 					freemsg(ipsec_mp);
26067 					ip1dbg(("ip_wput_ipsec_out: mforward "
26068 					    "failed\n"));
26069 					ire_refrele(ire);
26070 					goto done;
26071 				}
26072 			}
26073 			goto send;
26074 		}
26075 
26076 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26077 		mp->b_prev = NULL;
26078 		mp->b_next = NULL;
26079 
26080 		/*
26081 		 * If the IPsec packet was processed asynchronously,
26082 		 * drop it now.
26083 		 */
26084 		if (q == NULL) {
26085 			freemsg(ipsec_mp);
26086 			goto done;
26087 		}
26088 
26089 		/*
26090 		 * We may be using a wrong ipif to create the ire.
26091 		 * But it is okay as the source address is assigned
26092 		 * for the packet already. Next outbound packet would
26093 		 * create the IRE with the right IPIF in ip_wput.
26094 		 *
26095 		 * Also handle RTF_MULTIRT routes.
26096 		 */
26097 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26098 		    zoneid, &zero_info);
26099 	} else {
26100 		if (ire_arg != NULL) {
26101 			ire = ire_arg;
26102 			ire_need_rele = B_FALSE;
26103 		} else {
26104 			ire = ire_cache_lookup(dst, zoneid,
26105 			    msg_getlabel(mp), ipst);
26106 		}
26107 		if (ire != NULL) {
26108 			goto send;
26109 		}
26110 
26111 		/*
26112 		 * ire disappeared underneath.
26113 		 *
26114 		 * What we need to do here is the ip_newroute
26115 		 * logic to get the ire without doing the IPsec
26116 		 * processing. Follow the same old path. But this
26117 		 * time, ip_wput or ire_add_then_put will call us
26118 		 * directly as all the IPsec operations are done.
26119 		 */
26120 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26121 		mp->b_prev = NULL;
26122 		mp->b_next = NULL;
26123 
26124 		/*
26125 		 * If the IPsec packet was processed asynchronously,
26126 		 * drop it now.
26127 		 */
26128 		if (q == NULL) {
26129 			freemsg(ipsec_mp);
26130 			goto done;
26131 		}
26132 
26133 		/*
26134 		 * Since we're going through ip_newroute() again, we
26135 		 * need to make sure we don't:
26136 		 *
26137 		 *	1.) Trigger the ASSERT() with the ipha_ident
26138 		 *	    overloading.
26139 		 *	2.) Redo transport-layer checksumming, since we've
26140 		 *	    already done all that to get this far.
26141 		 *
26142 		 * The easiest way not do either of the above is to set
26143 		 * the ipha_ident field to IP_HDR_INCLUDED.
26144 		 */
26145 		ipha->ipha_ident = IP_HDR_INCLUDED;
26146 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26147 		    zoneid, ipst);
26148 	}
26149 	goto done;
26150 send:
26151 	if (ire->ire_stq == NULL) {
26152 		ill_t	*out_ill;
26153 		/*
26154 		 * Loopbacks go through ip_wput_local except for one case.
26155 		 * We come here if we generate a icmp_frag_needed message
26156 		 * after IPsec processing is over. When this function calls
26157 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26158 		 * icmp_frag_needed. The message generated comes back here
26159 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26160 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26161 		 * source address as it is usually set in ip_wput_ire. As
26162 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26163 		 * and we end up here. We can't enter ip_wput_ire once the
26164 		 * IPsec processing is over and hence we need to do it here.
26165 		 */
26166 		ASSERT(q != NULL);
26167 		UPDATE_OB_PKT_COUNT(ire);
26168 		ire->ire_last_used_time = lbolt;
26169 		if (ipha->ipha_src == 0)
26170 			ipha->ipha_src = ire->ire_src_addr;
26171 
26172 		/* PFHooks: LOOPBACK_OUT */
26173 		out_ill = ire_to_ill(ire);
26174 
26175 		/*
26176 		 * DTrace this as ip:::send.  A blocked packet will fire the
26177 		 * send probe, but not the receive probe.
26178 		 */
26179 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26180 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26181 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26182 
26183 		DTRACE_PROBE4(ip4__loopback__out__start,
26184 		    ill_t *, NULL, ill_t *, out_ill,
26185 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26186 
26187 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26188 		    ipst->ips_ipv4firewall_loopback_out,
26189 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26190 
26191 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26192 
26193 		if (ipsec_mp != NULL)
26194 			ip_wput_local(RD(q), out_ill,
26195 			    ipha, ipsec_mp, ire, 0, zoneid);
26196 		if (ire_need_rele)
26197 			ire_refrele(ire);
26198 		goto done;
26199 	}
26200 
26201 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26202 		/*
26203 		 * We are through with IPsec processing.
26204 		 * Fragment this and send it on the wire.
26205 		 */
26206 		if (io->ipsec_out_accelerated) {
26207 			/*
26208 			 * The packet has been accelerated but must
26209 			 * be fragmented. This should not happen
26210 			 * since AH and ESP must not accelerate
26211 			 * packets that need fragmentation, however
26212 			 * the configuration could have changed
26213 			 * since the AH or ESP processing.
26214 			 * Drop packet.
26215 			 * IPsec KSTATS: bump bean counter here.
26216 			 */
26217 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26218 			    "fragmented accelerated packet!\n"));
26219 			freemsg(ipsec_mp);
26220 		} else {
26221 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26222 			    zoneid, ipst, NULL);
26223 		}
26224 		if (ire_need_rele)
26225 			ire_refrele(ire);
26226 		goto done;
26227 	}
26228 
26229 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26230 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26231 	    (void *)ire->ire_ipif, (void *)ipif));
26232 
26233 	/*
26234 	 * Multiroute the secured packet.
26235 	 */
26236 	if (ire->ire_flags & RTF_MULTIRT) {
26237 		ire_t *first_ire;
26238 		irb = ire->ire_bucket;
26239 		ASSERT(irb != NULL);
26240 		/*
26241 		 * This ire has been looked up as the one that
26242 		 * goes through the given ipif;
26243 		 * make sure we do not omit any other multiroute ire
26244 		 * that may be present in the bucket before this one.
26245 		 */
26246 		IRB_REFHOLD(irb);
26247 		for (first_ire = irb->irb_ire;
26248 		    first_ire != NULL;
26249 		    first_ire = first_ire->ire_next) {
26250 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26251 			    (first_ire->ire_addr == ire->ire_addr) &&
26252 			    !(first_ire->ire_marks &
26253 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26254 				break;
26255 		}
26256 
26257 		if ((first_ire != NULL) && (first_ire != ire)) {
26258 			/*
26259 			 * Don't change the ire if the packet must
26260 			 * be fragmented if sent via this new one.
26261 			 */
26262 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26263 				IRE_REFHOLD(first_ire);
26264 				if (ire_need_rele)
26265 					ire_refrele(ire);
26266 				else
26267 					ire_need_rele = B_TRUE;
26268 				ire = first_ire;
26269 			}
26270 		}
26271 		IRB_REFRELE(irb);
26272 
26273 		multirt_send = B_TRUE;
26274 		max_frag = ire->ire_max_frag;
26275 	}
26276 
26277 	/*
26278 	 * In most cases, the emission loop below is entered only once.
26279 	 * Only in the case where the ire holds the RTF_MULTIRT
26280 	 * flag, we loop to process all RTF_MULTIRT ires in the
26281 	 * bucket, and send the packet through all crossed
26282 	 * RTF_MULTIRT routes.
26283 	 */
26284 	do {
26285 		if (multirt_send) {
26286 			/*
26287 			 * ire1 holds here the next ire to process in the
26288 			 * bucket. If multirouting is expected,
26289 			 * any non-RTF_MULTIRT ire that has the
26290 			 * right destination address is ignored.
26291 			 */
26292 			ASSERT(irb != NULL);
26293 			IRB_REFHOLD(irb);
26294 			for (ire1 = ire->ire_next;
26295 			    ire1 != NULL;
26296 			    ire1 = ire1->ire_next) {
26297 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26298 					continue;
26299 				if (ire1->ire_addr != ire->ire_addr)
26300 					continue;
26301 				if (ire1->ire_marks &
26302 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26303 					continue;
26304 				/* No loopback here */
26305 				if (ire1->ire_stq == NULL)
26306 					continue;
26307 				/*
26308 				 * Ensure we do not exceed the MTU
26309 				 * of the next route.
26310 				 */
26311 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26312 					ip_multirt_bad_mtu(ire1, max_frag);
26313 					continue;
26314 				}
26315 
26316 				IRE_REFHOLD(ire1);
26317 				break;
26318 			}
26319 			IRB_REFRELE(irb);
26320 			if (ire1 != NULL) {
26321 				/*
26322 				 * We are in a multiple send case, need to
26323 				 * make a copy of the packet.
26324 				 */
26325 				next_mp = copymsg(ipsec_mp);
26326 				if (next_mp == NULL) {
26327 					ire_refrele(ire1);
26328 					ire1 = NULL;
26329 				}
26330 			}
26331 		}
26332 		/*
26333 		 * Everything is done. Send it out on the wire
26334 		 *
26335 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26336 		 * either send it on the wire or, in the case of
26337 		 * HW acceleration, call ipsec_hw_putnext.
26338 		 */
26339 		if (ire->ire_nce &&
26340 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26341 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26342 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26343 			/*
26344 			 * If ire's link-layer is unresolved (this
26345 			 * would only happen if the incomplete ire
26346 			 * was added to cachetable via forwarding path)
26347 			 * don't bother going to ip_xmit_v4. Just drop the
26348 			 * packet.
26349 			 * There is a slight risk here, in that, if we
26350 			 * have the forwarding path create an incomplete
26351 			 * IRE, then until the IRE is completed, any
26352 			 * transmitted IPsec packets will be dropped
26353 			 * instead of being queued waiting for resolution.
26354 			 *
26355 			 * But the likelihood of a forwarding packet and a wput
26356 			 * packet sending to the same dst at the same time
26357 			 * and there not yet be an ARP entry for it is small.
26358 			 * Furthermore, if this actually happens, it might
26359 			 * be likely that wput would generate multiple
26360 			 * packets (and forwarding would also have a train
26361 			 * of packets) for that destination. If this is
26362 			 * the case, some of them would have been dropped
26363 			 * anyway, since ARP only queues a few packets while
26364 			 * waiting for resolution
26365 			 *
26366 			 * NOTE: We should really call ip_xmit_v4,
26367 			 * and let it queue the packet and send the
26368 			 * ARP query and have ARP come back thus:
26369 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26370 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26371 			 * hw accel work. But it's too complex to get
26372 			 * the IPsec hw  acceleration approach to fit
26373 			 * well with ip_xmit_v4 doing ARP without
26374 			 * doing IPsec simplification. For now, we just
26375 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26376 			 * that we can continue with the send on the next
26377 			 * attempt.
26378 			 *
26379 			 * XXX THis should be revisited, when
26380 			 * the IPsec/IP interaction is cleaned up
26381 			 */
26382 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26383 			    " - dropping packet\n"));
26384 			freemsg(ipsec_mp);
26385 			/*
26386 			 * Call ip_xmit_v4() to trigger ARP query
26387 			 * in case the nce_state is ND_INITIAL
26388 			 */
26389 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26390 			goto drop_pkt;
26391 		}
26392 
26393 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26394 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26395 		    mblk_t *, ipsec_mp);
26396 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26397 		    ipst->ips_ipv4firewall_physical_out, NULL,
26398 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26399 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26400 		if (ipsec_mp == NULL)
26401 			goto drop_pkt;
26402 
26403 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26404 		pktxmit_state = ip_xmit_v4(mp, ire,
26405 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26406 
26407 		if ((pktxmit_state ==  SEND_FAILED) ||
26408 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26409 
26410 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26411 drop_pkt:
26412 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26413 			    ipIfStatsOutDiscards);
26414 			if (ire_need_rele)
26415 				ire_refrele(ire);
26416 			if (ire1 != NULL) {
26417 				ire_refrele(ire1);
26418 				freemsg(next_mp);
26419 			}
26420 			goto done;
26421 		}
26422 
26423 		freeb(ipsec_mp);
26424 		if (ire_need_rele)
26425 			ire_refrele(ire);
26426 
26427 		if (ire1 != NULL) {
26428 			ire = ire1;
26429 			ire_need_rele = B_TRUE;
26430 			ASSERT(next_mp);
26431 			ipsec_mp = next_mp;
26432 			mp = ipsec_mp->b_cont;
26433 			ire1 = NULL;
26434 			next_mp = NULL;
26435 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26436 		} else {
26437 			multirt_send = B_FALSE;
26438 		}
26439 	} while (multirt_send);
26440 done:
26441 	if (ill != NULL && ill_need_rele)
26442 		ill_refrele(ill);
26443 	if (ipif != NULL)
26444 		ipif_refrele(ipif);
26445 }
26446 
26447 /*
26448  * Get the ill corresponding to the specified ire, and compare its
26449  * capabilities with the protocol and algorithms specified by the
26450  * the SA obtained from ipsec_out. If they match, annotate the
26451  * ipsec_out structure to indicate that the packet needs acceleration.
26452  *
26453  *
26454  * A packet is eligible for outbound hardware acceleration if the
26455  * following conditions are satisfied:
26456  *
26457  * 1. the packet will not be fragmented
26458  * 2. the provider supports the algorithm
26459  * 3. there is no pending control message being exchanged
26460  * 4. snoop is not attached
26461  * 5. the destination address is not a broadcast or multicast address.
26462  *
26463  * Rationale:
26464  *	- Hardware drivers do not support fragmentation with
26465  *	  the current interface.
26466  *	- snoop, multicast, and broadcast may result in exposure of
26467  *	  a cleartext datagram.
26468  * We check all five of these conditions here.
26469  *
26470  * XXX would like to nuke "ire_t *" parameter here; problem is that
26471  * IRE is only way to figure out if a v4 address is a broadcast and
26472  * thus ineligible for acceleration...
26473  */
26474 static void
26475 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26476 {
26477 	ipsec_out_t *io;
26478 	mblk_t *data_mp;
26479 	uint_t plen, overhead;
26480 	ip_stack_t	*ipst;
26481 	phyint_t	*phyint;
26482 
26483 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26484 		return;
26485 
26486 	if (ill == NULL)
26487 		return;
26488 	ipst = ill->ill_ipst;
26489 	phyint = ill->ill_phyint;
26490 
26491 	/*
26492 	 * Destination address is a broadcast or multicast.  Punt.
26493 	 */
26494 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26495 	    IRE_LOCAL)))
26496 		return;
26497 
26498 	data_mp = ipsec_mp->b_cont;
26499 
26500 	if (ill->ill_isv6) {
26501 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26502 
26503 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26504 			return;
26505 
26506 		plen = ip6h->ip6_plen;
26507 	} else {
26508 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26509 
26510 		if (CLASSD(ipha->ipha_dst))
26511 			return;
26512 
26513 		plen = ipha->ipha_length;
26514 	}
26515 	/*
26516 	 * Is there a pending DLPI control message being exchanged
26517 	 * between IP/IPsec and the DLS Provider? If there is, it
26518 	 * could be a SADB update, and the state of the DLS Provider
26519 	 * SADB might not be in sync with the SADB maintained by
26520 	 * IPsec. To avoid dropping packets or using the wrong keying
26521 	 * material, we do not accelerate this packet.
26522 	 */
26523 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26524 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26525 		    "ill_dlpi_pending! don't accelerate packet\n"));
26526 		return;
26527 	}
26528 
26529 	/*
26530 	 * Is the Provider in promiscous mode? If it does, we don't
26531 	 * accelerate the packet since it will bounce back up to the
26532 	 * listeners in the clear.
26533 	 */
26534 	if (phyint->phyint_flags & PHYI_PROMISC) {
26535 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26536 		    "ill in promiscous mode, don't accelerate packet\n"));
26537 		return;
26538 	}
26539 
26540 	/*
26541 	 * Will the packet require fragmentation?
26542 	 */
26543 
26544 	/*
26545 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26546 	 * as is used elsewhere.
26547 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26548 	 *	+ 2-byte trailer
26549 	 */
26550 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26551 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26552 
26553 	if ((plen + overhead) > ill->ill_max_mtu)
26554 		return;
26555 
26556 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26557 
26558 	/*
26559 	 * Can the ill accelerate this IPsec protocol and algorithm
26560 	 * specified by the SA?
26561 	 */
26562 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26563 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26564 		return;
26565 	}
26566 
26567 	/*
26568 	 * Tell AH or ESP that the outbound ill is capable of
26569 	 * accelerating this packet.
26570 	 */
26571 	io->ipsec_out_is_capab_ill = B_TRUE;
26572 }
26573 
26574 /*
26575  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26576  *
26577  * If this function returns B_TRUE, the requested SA's have been filled
26578  * into the ipsec_out_*_sa pointers.
26579  *
26580  * If the function returns B_FALSE, the packet has been "consumed", most
26581  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26582  *
26583  * The SA references created by the protocol-specific "select"
26584  * function will be released when the ipsec_mp is freed, thanks to the
26585  * ipsec_out_free destructor -- see spd.c.
26586  */
26587 static boolean_t
26588 ipsec_out_select_sa(mblk_t *ipsec_mp)
26589 {
26590 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26591 	ipsec_out_t *io;
26592 	ipsec_policy_t *pp;
26593 	ipsec_action_t *ap;
26594 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26595 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26596 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26597 
26598 	if (!io->ipsec_out_secure) {
26599 		/*
26600 		 * We came here by mistake.
26601 		 * Don't bother with ipsec processing
26602 		 * We should "discourage" this path in the future.
26603 		 */
26604 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26605 		return (B_FALSE);
26606 	}
26607 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26608 	ASSERT((io->ipsec_out_policy != NULL) ||
26609 	    (io->ipsec_out_act != NULL));
26610 
26611 	ASSERT(io->ipsec_out_failed == B_FALSE);
26612 
26613 	/*
26614 	 * IPsec processing has started.
26615 	 */
26616 	io->ipsec_out_proc_begin = B_TRUE;
26617 	ap = io->ipsec_out_act;
26618 	if (ap == NULL) {
26619 		pp = io->ipsec_out_policy;
26620 		ASSERT(pp != NULL);
26621 		ap = pp->ipsp_act;
26622 		ASSERT(ap != NULL);
26623 	}
26624 
26625 	/*
26626 	 * We have an action.  now, let's select SA's.
26627 	 * (In the future, we can cache this in the conn_t..)
26628 	 */
26629 	if (ap->ipa_want_esp) {
26630 		if (io->ipsec_out_esp_sa == NULL) {
26631 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26632 			    IPPROTO_ESP);
26633 		}
26634 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26635 	}
26636 
26637 	if (ap->ipa_want_ah) {
26638 		if (io->ipsec_out_ah_sa == NULL) {
26639 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26640 			    IPPROTO_AH);
26641 		}
26642 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26643 		/*
26644 		 * The ESP and AH processing order needs to be preserved
26645 		 * when both protocols are required (ESP should be applied
26646 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26647 		 * when both ESP and AH are required, and an AH ACQUIRE
26648 		 * is needed.
26649 		 */
26650 		if (ap->ipa_want_esp && need_ah_acquire)
26651 			need_esp_acquire = B_TRUE;
26652 	}
26653 
26654 	/*
26655 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26656 	 * Release SAs that got referenced, but will not be used until we
26657 	 * acquire _all_ of the SAs we need.
26658 	 */
26659 	if (need_ah_acquire || need_esp_acquire) {
26660 		if (io->ipsec_out_ah_sa != NULL) {
26661 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26662 			io->ipsec_out_ah_sa = NULL;
26663 		}
26664 		if (io->ipsec_out_esp_sa != NULL) {
26665 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26666 			io->ipsec_out_esp_sa = NULL;
26667 		}
26668 
26669 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26670 		return (B_FALSE);
26671 	}
26672 
26673 	return (B_TRUE);
26674 }
26675 
26676 /*
26677  * Process an IPSEC_OUT message and see what you can
26678  * do with it.
26679  * IPQoS Notes:
26680  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26681  * IPsec.
26682  * XXX would like to nuke ire_t.
26683  * XXX ill_index better be "real"
26684  */
26685 void
26686 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26687 {
26688 	ipsec_out_t *io;
26689 	ipsec_policy_t *pp;
26690 	ipsec_action_t *ap;
26691 	ipha_t *ipha;
26692 	ip6_t *ip6h;
26693 	mblk_t *mp;
26694 	ill_t *ill;
26695 	zoneid_t zoneid;
26696 	ipsec_status_t ipsec_rc;
26697 	boolean_t ill_need_rele = B_FALSE;
26698 	ip_stack_t	*ipst;
26699 	ipsec_stack_t	*ipss;
26700 
26701 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26702 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26703 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26704 	ipst = io->ipsec_out_ns->netstack_ip;
26705 	mp = ipsec_mp->b_cont;
26706 
26707 	/*
26708 	 * Initiate IPPF processing. We do it here to account for packets
26709 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26710 	 * We can check for ipsec_out_proc_begin even for such packets, as
26711 	 * they will always be false (asserted below).
26712 	 */
26713 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26714 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26715 		    io->ipsec_out_ill_index : ill_index);
26716 		if (mp == NULL) {
26717 			ip2dbg(("ipsec_out_process: packet dropped "\
26718 			    "during IPPF processing\n"));
26719 			freeb(ipsec_mp);
26720 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26721 			return;
26722 		}
26723 	}
26724 
26725 	if (!io->ipsec_out_secure) {
26726 		/*
26727 		 * We came here by mistake.
26728 		 * Don't bother with ipsec processing
26729 		 * Should "discourage" this path in the future.
26730 		 */
26731 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26732 		goto done;
26733 	}
26734 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26735 	ASSERT((io->ipsec_out_policy != NULL) ||
26736 	    (io->ipsec_out_act != NULL));
26737 	ASSERT(io->ipsec_out_failed == B_FALSE);
26738 
26739 	ipss = ipst->ips_netstack->netstack_ipsec;
26740 	if (!ipsec_loaded(ipss)) {
26741 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26742 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26743 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26744 		} else {
26745 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26746 		}
26747 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26748 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26749 		    &ipss->ipsec_dropper);
26750 		return;
26751 	}
26752 
26753 	/*
26754 	 * IPsec processing has started.
26755 	 */
26756 	io->ipsec_out_proc_begin = B_TRUE;
26757 	ap = io->ipsec_out_act;
26758 	if (ap == NULL) {
26759 		pp = io->ipsec_out_policy;
26760 		ASSERT(pp != NULL);
26761 		ap = pp->ipsp_act;
26762 		ASSERT(ap != NULL);
26763 	}
26764 
26765 	/*
26766 	 * Save the outbound ill index. When the packet comes back
26767 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26768 	 * before sending it the accelerated packet.
26769 	 */
26770 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26771 		ill = ire_to_ill(ire);
26772 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26773 	}
26774 
26775 	/*
26776 	 * The order of processing is first insert a IP header if needed.
26777 	 * Then insert the ESP header and then the AH header.
26778 	 */
26779 	if ((io->ipsec_out_se_done == B_FALSE) &&
26780 	    (ap->ipa_want_se)) {
26781 		/*
26782 		 * First get the outer IP header before sending
26783 		 * it to ESP.
26784 		 */
26785 		ipha_t *oipha, *iipha;
26786 		mblk_t *outer_mp, *inner_mp;
26787 
26788 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26789 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26790 			    "ipsec_out_process: "
26791 			    "Self-Encapsulation failed: Out of memory\n");
26792 			freemsg(ipsec_mp);
26793 			if (ill != NULL) {
26794 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26795 			} else {
26796 				BUMP_MIB(&ipst->ips_ip_mib,
26797 				    ipIfStatsOutDiscards);
26798 			}
26799 			return;
26800 		}
26801 		inner_mp = ipsec_mp->b_cont;
26802 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26803 		oipha = (ipha_t *)outer_mp->b_rptr;
26804 		iipha = (ipha_t *)inner_mp->b_rptr;
26805 		*oipha = *iipha;
26806 		outer_mp->b_wptr += sizeof (ipha_t);
26807 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26808 		    sizeof (ipha_t));
26809 		oipha->ipha_protocol = IPPROTO_ENCAP;
26810 		oipha->ipha_version_and_hdr_length =
26811 		    IP_SIMPLE_HDR_VERSION;
26812 		oipha->ipha_hdr_checksum = 0;
26813 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26814 		outer_mp->b_cont = inner_mp;
26815 		ipsec_mp->b_cont = outer_mp;
26816 
26817 		io->ipsec_out_se_done = B_TRUE;
26818 		io->ipsec_out_tunnel = B_TRUE;
26819 	}
26820 
26821 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26822 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26823 	    !ipsec_out_select_sa(ipsec_mp))
26824 		return;
26825 
26826 	/*
26827 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26828 	 * to do the heavy lifting.
26829 	 */
26830 	zoneid = io->ipsec_out_zoneid;
26831 	ASSERT(zoneid != ALL_ZONES);
26832 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26833 		ASSERT(io->ipsec_out_esp_sa != NULL);
26834 		io->ipsec_out_esp_done = B_TRUE;
26835 		/*
26836 		 * Note that since hw accel can only apply one transform,
26837 		 * not two, we skip hw accel for ESP if we also have AH
26838 		 * This is an design limitation of the interface
26839 		 * which should be revisited.
26840 		 */
26841 		ASSERT(ire != NULL);
26842 		if (io->ipsec_out_ah_sa == NULL) {
26843 			ill = (ill_t *)ire->ire_stq->q_ptr;
26844 			ipsec_out_is_accelerated(ipsec_mp,
26845 			    io->ipsec_out_esp_sa, ill, ire);
26846 		}
26847 
26848 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26849 		switch (ipsec_rc) {
26850 		case IPSEC_STATUS_SUCCESS:
26851 			break;
26852 		case IPSEC_STATUS_FAILED:
26853 			if (ill != NULL) {
26854 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26855 			} else {
26856 				BUMP_MIB(&ipst->ips_ip_mib,
26857 				    ipIfStatsOutDiscards);
26858 			}
26859 			/* FALLTHRU */
26860 		case IPSEC_STATUS_PENDING:
26861 			return;
26862 		}
26863 	}
26864 
26865 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26866 		ASSERT(io->ipsec_out_ah_sa != NULL);
26867 		io->ipsec_out_ah_done = B_TRUE;
26868 		if (ire == NULL) {
26869 			int idx = io->ipsec_out_capab_ill_index;
26870 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26871 			    NULL, NULL, NULL, NULL, ipst);
26872 			ill_need_rele = B_TRUE;
26873 		} else {
26874 			ill = (ill_t *)ire->ire_stq->q_ptr;
26875 		}
26876 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26877 		    ire);
26878 
26879 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26880 		switch (ipsec_rc) {
26881 		case IPSEC_STATUS_SUCCESS:
26882 			break;
26883 		case IPSEC_STATUS_FAILED:
26884 			if (ill != NULL) {
26885 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26886 			} else {
26887 				BUMP_MIB(&ipst->ips_ip_mib,
26888 				    ipIfStatsOutDiscards);
26889 			}
26890 			/* FALLTHRU */
26891 		case IPSEC_STATUS_PENDING:
26892 			if (ill != NULL && ill_need_rele)
26893 				ill_refrele(ill);
26894 			return;
26895 		}
26896 	}
26897 	/*
26898 	 * We are done with IPsec processing. Send it over the wire.
26899 	 */
26900 done:
26901 	mp = ipsec_mp->b_cont;
26902 	ipha = (ipha_t *)mp->b_rptr;
26903 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26904 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26905 		    ire);
26906 	} else {
26907 		ip6h = (ip6_t *)ipha;
26908 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26909 		    ire);
26910 	}
26911 	if (ill != NULL && ill_need_rele)
26912 		ill_refrele(ill);
26913 }
26914 
26915 /* ARGSUSED */
26916 void
26917 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26918 {
26919 	opt_restart_t	*or;
26920 	int	err;
26921 	conn_t	*connp;
26922 	cred_t	*cr;
26923 
26924 	ASSERT(CONN_Q(q));
26925 	connp = Q_TO_CONN(q);
26926 
26927 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26928 	or = (opt_restart_t *)first_mp->b_rptr;
26929 	/*
26930 	 * We checked for a db_credp the first time svr4_optcom_req
26931 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26932 	 */
26933 	cr = msg_getcred(first_mp, NULL);
26934 	ASSERT(cr != NULL);
26935 
26936 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26937 		err = svr4_optcom_req(q, first_mp, cr,
26938 		    &ip_opt_obj, B_FALSE);
26939 	} else {
26940 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26941 		err = tpi_optcom_req(q, first_mp, cr,
26942 		    &ip_opt_obj, B_FALSE);
26943 	}
26944 	if (err != EINPROGRESS) {
26945 		/* operation is done */
26946 		CONN_OPER_PENDING_DONE(connp);
26947 	}
26948 }
26949 
26950 /*
26951  * ioctls that go through a down/up sequence may need to wait for the down
26952  * to complete. This involves waiting for the ire and ipif refcnts to go down
26953  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26954  */
26955 /* ARGSUSED */
26956 void
26957 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26958 {
26959 	struct iocblk *iocp;
26960 	mblk_t *mp1;
26961 	ip_ioctl_cmd_t *ipip;
26962 	int err;
26963 	sin_t	*sin;
26964 	struct lifreq *lifr;
26965 	struct ifreq *ifr;
26966 
26967 	iocp = (struct iocblk *)mp->b_rptr;
26968 	ASSERT(ipsq != NULL);
26969 	/* Existence of mp1 verified in ip_wput_nondata */
26970 	mp1 = mp->b_cont->b_cont;
26971 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26972 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26973 		/*
26974 		 * Special case where ipx_current_ipif is not set:
26975 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26976 		 * We are here as were not able to complete the operation in
26977 		 * ipif_set_values because we could not become exclusive on
26978 		 * the new ipsq.
26979 		 */
26980 		ill_t *ill = q->q_ptr;
26981 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26982 	}
26983 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26984 
26985 	if (ipip->ipi_cmd_type == IF_CMD) {
26986 		/* This a old style SIOC[GS]IF* command */
26987 		ifr = (struct ifreq *)mp1->b_rptr;
26988 		sin = (sin_t *)&ifr->ifr_addr;
26989 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26990 		/* This a new style SIOC[GS]LIF* command */
26991 		lifr = (struct lifreq *)mp1->b_rptr;
26992 		sin = (sin_t *)&lifr->lifr_addr;
26993 	} else {
26994 		sin = NULL;
26995 	}
26996 
26997 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26998 	    q, mp, ipip, mp1->b_rptr);
26999 
27000 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27001 }
27002 
27003 /*
27004  * ioctl processing
27005  *
27006  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
27007  * the ioctl command in the ioctl tables, determines the copyin data size
27008  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
27009  *
27010  * ioctl processing then continues when the M_IOCDATA makes its way down to
27011  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
27012  * associated 'conn' is refheld till the end of the ioctl and the general
27013  * ioctl processing function ip_process_ioctl() is called to extract the
27014  * arguments and process the ioctl.  To simplify extraction, ioctl commands
27015  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
27016  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
27017  * is used to extract the ioctl's arguments.
27018  *
27019  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27020  * so goes thru the serialization primitive ipsq_try_enter. Then the
27021  * appropriate function to handle the ioctl is called based on the entry in
27022  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27023  * which also refreleases the 'conn' that was refheld at the start of the
27024  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27025  *
27026  * Many exclusive ioctls go thru an internal down up sequence as part of
27027  * the operation. For example an attempt to change the IP address of an
27028  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27029  * does all the cleanup such as deleting all ires that use this address.
27030  * Then we need to wait till all references to the interface go away.
27031  */
27032 void
27033 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27034 {
27035 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27036 	ip_ioctl_cmd_t *ipip = arg;
27037 	ip_extract_func_t *extract_funcp;
27038 	cmd_info_t ci;
27039 	int err;
27040 	boolean_t entered_ipsq = B_FALSE;
27041 
27042 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27043 
27044 	if (ipip == NULL)
27045 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27046 
27047 	/*
27048 	 * SIOCLIFADDIF needs to go thru a special path since the
27049 	 * ill may not exist yet. This happens in the case of lo0
27050 	 * which is created using this ioctl.
27051 	 */
27052 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27053 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27054 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27055 		return;
27056 	}
27057 
27058 	ci.ci_ipif = NULL;
27059 	if (ipip->ipi_cmd_type == MISC_CMD) {
27060 		/*
27061 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27062 		 */
27063 		if (ipip->ipi_cmd == IF_UNITSEL) {
27064 			/* ioctl comes down the ill */
27065 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27066 			ipif_refhold(ci.ci_ipif);
27067 		}
27068 		err = 0;
27069 		ci.ci_sin = NULL;
27070 		ci.ci_sin6 = NULL;
27071 		ci.ci_lifr = NULL;
27072 	} else {
27073 		switch (ipip->ipi_cmd_type) {
27074 		case IF_CMD:
27075 		case LIF_CMD:
27076 			extract_funcp = ip_extract_lifreq;
27077 			break;
27078 
27079 		case ARP_CMD:
27080 		case XARP_CMD:
27081 			extract_funcp = ip_extract_arpreq;
27082 			break;
27083 
27084 		case TUN_CMD:
27085 			extract_funcp = ip_extract_tunreq;
27086 			break;
27087 
27088 		case MSFILT_CMD:
27089 			extract_funcp = ip_extract_msfilter;
27090 			break;
27091 
27092 		default:
27093 			ASSERT(0);
27094 		}
27095 
27096 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27097 		if (err != 0) {
27098 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27099 			return;
27100 		}
27101 
27102 		/*
27103 		 * All of the extraction functions return a refheld ipif.
27104 		 */
27105 		ASSERT(ci.ci_ipif != NULL);
27106 	}
27107 
27108 	if (!(ipip->ipi_flags & IPI_WR)) {
27109 		/*
27110 		 * A return value of EINPROGRESS means the ioctl is
27111 		 * either queued and waiting for some reason or has
27112 		 * already completed.
27113 		 */
27114 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27115 		    ci.ci_lifr);
27116 		if (ci.ci_ipif != NULL)
27117 			ipif_refrele(ci.ci_ipif);
27118 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27119 		return;
27120 	}
27121 
27122 	ASSERT(ci.ci_ipif != NULL);
27123 
27124 	/*
27125 	 * If ipsq is non-NULL, we are already being called exclusively.
27126 	 */
27127 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27128 	if (ipsq == NULL) {
27129 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27130 		    NEW_OP, B_TRUE);
27131 		if (ipsq == NULL) {
27132 			ipif_refrele(ci.ci_ipif);
27133 			return;
27134 		}
27135 		entered_ipsq = B_TRUE;
27136 	}
27137 
27138 	/*
27139 	 * Release the ipif so that ipif_down and friends that wait for
27140 	 * references to go away are not misled about the current ipif_refcnt
27141 	 * values. We are writer so we can access the ipif even after releasing
27142 	 * the ipif.
27143 	 */
27144 	ipif_refrele(ci.ci_ipif);
27145 
27146 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27147 
27148 	/*
27149 	 * A return value of EINPROGRESS means the ioctl is
27150 	 * either queued and waiting for some reason or has
27151 	 * already completed.
27152 	 */
27153 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27154 
27155 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27156 
27157 	if (entered_ipsq)
27158 		ipsq_exit(ipsq);
27159 }
27160 
27161 /*
27162  * Complete the ioctl. Typically ioctls use the mi package and need to
27163  * do mi_copyout/mi_copy_done.
27164  */
27165 void
27166 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27167 {
27168 	conn_t	*connp = NULL;
27169 
27170 	if (err == EINPROGRESS)
27171 		return;
27172 
27173 	if (CONN_Q(q)) {
27174 		connp = Q_TO_CONN(q);
27175 		ASSERT(connp->conn_ref >= 2);
27176 	}
27177 
27178 	switch (mode) {
27179 	case COPYOUT:
27180 		if (err == 0)
27181 			mi_copyout(q, mp);
27182 		else
27183 			mi_copy_done(q, mp, err);
27184 		break;
27185 
27186 	case NO_COPYOUT:
27187 		mi_copy_done(q, mp, err);
27188 		break;
27189 
27190 	default:
27191 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27192 		break;
27193 	}
27194 
27195 	/*
27196 	 * The refhold placed at the start of the ioctl is released here.
27197 	 */
27198 	if (connp != NULL)
27199 		CONN_OPER_PENDING_DONE(connp);
27200 
27201 	if (ipsq != NULL)
27202 		ipsq_current_finish(ipsq);
27203 }
27204 
27205 /* Called from ip_wput for all non data messages */
27206 /* ARGSUSED */
27207 void
27208 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27209 {
27210 	mblk_t		*mp1;
27211 	ire_t		*ire, *fake_ire;
27212 	ill_t		*ill;
27213 	struct iocblk	*iocp;
27214 	ip_ioctl_cmd_t	*ipip;
27215 	cred_t		*cr;
27216 	conn_t		*connp;
27217 	int		err;
27218 	nce_t		*nce;
27219 	ipif_t		*ipif;
27220 	ip_stack_t	*ipst;
27221 	char		*proto_str;
27222 
27223 	if (CONN_Q(q)) {
27224 		connp = Q_TO_CONN(q);
27225 		ipst = connp->conn_netstack->netstack_ip;
27226 	} else {
27227 		connp = NULL;
27228 		ipst = ILLQ_TO_IPST(q);
27229 	}
27230 
27231 	switch (DB_TYPE(mp)) {
27232 	case M_IOCTL:
27233 		/*
27234 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27235 		 * will arrange to copy in associated control structures.
27236 		 */
27237 		ip_sioctl_copyin_setup(q, mp);
27238 		return;
27239 	case M_IOCDATA:
27240 		/*
27241 		 * Ensure that this is associated with one of our trans-
27242 		 * parent ioctls.  If it's not ours, discard it if we're
27243 		 * running as a driver, or pass it on if we're a module.
27244 		 */
27245 		iocp = (struct iocblk *)mp->b_rptr;
27246 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27247 		if (ipip == NULL) {
27248 			if (q->q_next == NULL) {
27249 				goto nak;
27250 			} else {
27251 				putnext(q, mp);
27252 			}
27253 			return;
27254 		}
27255 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27256 			/*
27257 			 * the ioctl is one we recognise, but is not
27258 			 * consumed by IP as a module, pass M_IOCDATA
27259 			 * for processing downstream, but only for
27260 			 * common Streams ioctls.
27261 			 */
27262 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27263 				putnext(q, mp);
27264 				return;
27265 			} else {
27266 				goto nak;
27267 			}
27268 		}
27269 
27270 		/* IOCTL continuation following copyin or copyout. */
27271 		if (mi_copy_state(q, mp, NULL) == -1) {
27272 			/*
27273 			 * The copy operation failed.  mi_copy_state already
27274 			 * cleaned up, so we're out of here.
27275 			 */
27276 			return;
27277 		}
27278 		/*
27279 		 * If we just completed a copy in, we become writer and
27280 		 * continue processing in ip_sioctl_copyin_done.  If it
27281 		 * was a copy out, we call mi_copyout again.  If there is
27282 		 * nothing more to copy out, it will complete the IOCTL.
27283 		 */
27284 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27285 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27286 				mi_copy_done(q, mp, EPROTO);
27287 				return;
27288 			}
27289 			/*
27290 			 * Check for cases that need more copying.  A return
27291 			 * value of 0 means a second copyin has been started,
27292 			 * so we return; a return value of 1 means no more
27293 			 * copying is needed, so we continue.
27294 			 */
27295 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27296 			    MI_COPY_COUNT(mp) == 1) {
27297 				if (ip_copyin_msfilter(q, mp) == 0)
27298 					return;
27299 			}
27300 			/*
27301 			 * Refhold the conn, till the ioctl completes. This is
27302 			 * needed in case the ioctl ends up in the pending mp
27303 			 * list. Every mp in the ill_pending_mp list and
27304 			 * the ipx_pending_mp must have a refhold on the conn
27305 			 * to resume processing. The refhold is released when
27306 			 * the ioctl completes. (normally or abnormally)
27307 			 * In all cases ip_ioctl_finish is called to finish
27308 			 * the ioctl.
27309 			 */
27310 			if (connp != NULL) {
27311 				/* This is not a reentry */
27312 				ASSERT(ipsq == NULL);
27313 				CONN_INC_REF(connp);
27314 			} else {
27315 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27316 					mi_copy_done(q, mp, EINVAL);
27317 					return;
27318 				}
27319 			}
27320 
27321 			ip_process_ioctl(ipsq, q, mp, ipip);
27322 
27323 		} else {
27324 			mi_copyout(q, mp);
27325 		}
27326 		return;
27327 nak:
27328 		iocp->ioc_error = EINVAL;
27329 		mp->b_datap->db_type = M_IOCNAK;
27330 		iocp->ioc_count = 0;
27331 		qreply(q, mp);
27332 		return;
27333 
27334 	case M_IOCNAK:
27335 		/*
27336 		 * The only way we could get here is if a resolver didn't like
27337 		 * an IOCTL we sent it.	 This shouldn't happen.
27338 		 */
27339 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27340 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27341 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27342 		freemsg(mp);
27343 		return;
27344 	case M_IOCACK:
27345 		/* /dev/ip shouldn't see this */
27346 		if (CONN_Q(q))
27347 			goto nak;
27348 
27349 		/*
27350 		 * Finish socket ioctls passed through to ARP.  We use the
27351 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27352 		 * we need to become writer before calling ip_sioctl_iocack().
27353 		 * Note that qwriter_ip() will release the refhold, and that a
27354 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27355 		 * ill stream.
27356 		 */
27357 		iocp = (struct iocblk *)mp->b_rptr;
27358 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27359 			ip_sioctl_iocack(NULL, q, mp, NULL);
27360 			return;
27361 		}
27362 
27363 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27364 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27365 		ill = q->q_ptr;
27366 		ill_refhold(ill);
27367 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27368 		return;
27369 	case M_FLUSH:
27370 		if (*mp->b_rptr & FLUSHW)
27371 			flushq(q, FLUSHALL);
27372 		if (q->q_next) {
27373 			putnext(q, mp);
27374 			return;
27375 		}
27376 		if (*mp->b_rptr & FLUSHR) {
27377 			*mp->b_rptr &= ~FLUSHW;
27378 			qreply(q, mp);
27379 			return;
27380 		}
27381 		freemsg(mp);
27382 		return;
27383 	case IRE_DB_REQ_TYPE:
27384 		if (connp == NULL) {
27385 			proto_str = "IRE_DB_REQ_TYPE";
27386 			goto protonak;
27387 		}
27388 		/* An Upper Level Protocol wants a copy of an IRE. */
27389 		ip_ire_req(q, mp);
27390 		return;
27391 	case M_CTL:
27392 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27393 			break;
27394 
27395 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27396 		    TUN_HELLO) {
27397 			ASSERT(connp != NULL);
27398 			connp->conn_flags |= IPCL_IPTUN;
27399 			freeb(mp);
27400 			return;
27401 		}
27402 
27403 		/* M_CTL messages are used by ARP to tell us things. */
27404 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27405 			break;
27406 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27407 		case AR_ENTRY_SQUERY:
27408 			putnext(q, mp);
27409 			return;
27410 		case AR_CLIENT_NOTIFY:
27411 			ip_arp_news(q, mp);
27412 			return;
27413 		case AR_DLPIOP_DONE:
27414 			ASSERT(q->q_next != NULL);
27415 			ill = (ill_t *)q->q_ptr;
27416 			/* qwriter_ip releases the refhold */
27417 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27418 			ill_refhold(ill);
27419 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27420 			return;
27421 		case AR_ARP_CLOSING:
27422 			/*
27423 			 * ARP (above us) is closing. If no ARP bringup is
27424 			 * currently pending, ack the message so that ARP
27425 			 * can complete its close. Also mark ill_arp_closing
27426 			 * so that new ARP bringups will fail. If any
27427 			 * ARP bringup is currently in progress, we will
27428 			 * ack this when the current ARP bringup completes.
27429 			 */
27430 			ASSERT(q->q_next != NULL);
27431 			ill = (ill_t *)q->q_ptr;
27432 			mutex_enter(&ill->ill_lock);
27433 			ill->ill_arp_closing = 1;
27434 			if (!ill->ill_arp_bringup_pending) {
27435 				mutex_exit(&ill->ill_lock);
27436 				qreply(q, mp);
27437 			} else {
27438 				mutex_exit(&ill->ill_lock);
27439 				freemsg(mp);
27440 			}
27441 			return;
27442 		case AR_ARP_EXTEND:
27443 			/*
27444 			 * The ARP module above us is capable of duplicate
27445 			 * address detection.  Old ATM drivers will not send
27446 			 * this message.
27447 			 */
27448 			ASSERT(q->q_next != NULL);
27449 			ill = (ill_t *)q->q_ptr;
27450 			ill->ill_arp_extend = B_TRUE;
27451 			freemsg(mp);
27452 			return;
27453 		default:
27454 			break;
27455 		}
27456 		break;
27457 	case M_PROTO:
27458 	case M_PCPROTO:
27459 		/*
27460 		 * The only PROTO messages we expect are copies of option
27461 		 * negotiation acknowledgements, AH and ESP bind requests
27462 		 * are also expected.
27463 		 */
27464 		switch (((union T_primitives *)mp->b_rptr)->type) {
27465 		case O_T_BIND_REQ:
27466 		case T_BIND_REQ: {
27467 			/* Request can get queued in bind */
27468 			if (connp == NULL) {
27469 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27470 				goto protonak;
27471 			}
27472 			/*
27473 			 * The transports except SCTP call ip_bind_{v4,v6}()
27474 			 * directly instead of a a putnext. SCTP doesn't
27475 			 * generate any T_BIND_REQ since it has its own
27476 			 * fanout data structures. However, ESP and AH
27477 			 * come in for regular binds; all other cases are
27478 			 * bind retries.
27479 			 */
27480 			ASSERT(!IPCL_IS_SCTP(connp));
27481 
27482 			/* Don't increment refcnt if this is a re-entry */
27483 			if (ipsq == NULL)
27484 				CONN_INC_REF(connp);
27485 
27486 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27487 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27488 			ASSERT(mp != NULL);
27489 
27490 			ASSERT(!IPCL_IS_TCP(connp));
27491 			ASSERT(!IPCL_IS_UDP(connp));
27492 			ASSERT(!IPCL_IS_RAWIP(connp));
27493 
27494 			/* The case of AH and ESP */
27495 			qreply(q, mp);
27496 			CONN_OPER_PENDING_DONE(connp);
27497 			return;
27498 		}
27499 		case T_SVR4_OPTMGMT_REQ:
27500 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27501 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27502 
27503 			if (connp == NULL) {
27504 				proto_str = "T_SVR4_OPTMGMT_REQ";
27505 				goto protonak;
27506 			}
27507 
27508 			/*
27509 			 * All Solaris components should pass a db_credp
27510 			 * for this TPI message, hence we ASSERT.
27511 			 * But in case there is some other M_PROTO that looks
27512 			 * like a TPI message sent by some other kernel
27513 			 * component, we check and return an error.
27514 			 */
27515 			cr = msg_getcred(mp, NULL);
27516 			ASSERT(cr != NULL);
27517 			if (cr == NULL) {
27518 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27519 				if (mp != NULL)
27520 					qreply(q, mp);
27521 				return;
27522 			}
27523 
27524 			if (!snmpcom_req(q, mp, ip_snmp_set,
27525 			    ip_snmp_get, cr)) {
27526 				/*
27527 				 * Call svr4_optcom_req so that it can
27528 				 * generate the ack. We don't come here
27529 				 * if this operation is being restarted.
27530 				 * ip_restart_optmgmt will drop the conn ref.
27531 				 * In the case of ipsec option after the ipsec
27532 				 * load is complete conn_restart_ipsec_waiter
27533 				 * drops the conn ref.
27534 				 */
27535 				ASSERT(ipsq == NULL);
27536 				CONN_INC_REF(connp);
27537 				if (ip_check_for_ipsec_opt(q, mp))
27538 					return;
27539 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27540 				    B_FALSE);
27541 				if (err != EINPROGRESS) {
27542 					/* Operation is done */
27543 					CONN_OPER_PENDING_DONE(connp);
27544 				}
27545 			}
27546 			return;
27547 		case T_OPTMGMT_REQ:
27548 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27549 			/*
27550 			 * Note: No snmpcom_req support through new
27551 			 * T_OPTMGMT_REQ.
27552 			 * Call tpi_optcom_req so that it can
27553 			 * generate the ack.
27554 			 */
27555 			if (connp == NULL) {
27556 				proto_str = "T_OPTMGMT_REQ";
27557 				goto protonak;
27558 			}
27559 
27560 			/*
27561 			 * All Solaris components should pass a db_credp
27562 			 * for this TPI message, hence we ASSERT.
27563 			 * But in case there is some other M_PROTO that looks
27564 			 * like a TPI message sent by some other kernel
27565 			 * component, we check and return an error.
27566 			 */
27567 			cr = msg_getcred(mp, NULL);
27568 			ASSERT(cr != NULL);
27569 			if (cr == NULL) {
27570 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27571 				if (mp != NULL)
27572 					qreply(q, mp);
27573 				return;
27574 			}
27575 			ASSERT(ipsq == NULL);
27576 			/*
27577 			 * We don't come here for restart. ip_restart_optmgmt
27578 			 * will drop the conn ref. In the case of ipsec option
27579 			 * after the ipsec load is complete
27580 			 * conn_restart_ipsec_waiter drops the conn ref.
27581 			 */
27582 			CONN_INC_REF(connp);
27583 			if (ip_check_for_ipsec_opt(q, mp))
27584 				return;
27585 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27586 			if (err != EINPROGRESS) {
27587 				/* Operation is done */
27588 				CONN_OPER_PENDING_DONE(connp);
27589 			}
27590 			return;
27591 		case T_UNBIND_REQ:
27592 			if (connp == NULL) {
27593 				proto_str = "T_UNBIND_REQ";
27594 				goto protonak;
27595 			}
27596 			ip_unbind(Q_TO_CONN(q));
27597 			mp = mi_tpi_ok_ack_alloc(mp);
27598 			qreply(q, mp);
27599 			return;
27600 		default:
27601 			/*
27602 			 * Have to drop any DLPI messages coming down from
27603 			 * arp (such as an info_req which would cause ip
27604 			 * to receive an extra info_ack if it was passed
27605 			 * through.
27606 			 */
27607 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27608 			    (int)*(uint_t *)mp->b_rptr));
27609 			freemsg(mp);
27610 			return;
27611 		}
27612 		/* NOTREACHED */
27613 	case IRE_DB_TYPE: {
27614 		nce_t		*nce;
27615 		ill_t		*ill;
27616 		in6_addr_t	gw_addr_v6;
27617 
27618 		/*
27619 		 * This is a response back from a resolver.  It
27620 		 * consists of a message chain containing:
27621 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27622 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27623 		 * The LL_HDR_MBLK is the DLPI header to use to get
27624 		 * the attached packet, and subsequent ones for the
27625 		 * same destination, transmitted.
27626 		 */
27627 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27628 			break;
27629 		/*
27630 		 * First, check to make sure the resolution succeeded.
27631 		 * If it failed, the second mblk will be empty.
27632 		 * If it is, free the chain, dropping the packet.
27633 		 * (We must ire_delete the ire; that frees the ire mblk)
27634 		 * We're doing this now to support PVCs for ATM; it's
27635 		 * a partial xresolv implementation. When we fully implement
27636 		 * xresolv interfaces, instead of freeing everything here
27637 		 * we'll initiate neighbor discovery.
27638 		 *
27639 		 * For v4 (ARP and other external resolvers) the resolver
27640 		 * frees the message, so no check is needed. This check
27641 		 * is required, though, for a full xresolve implementation.
27642 		 * Including this code here now both shows how external
27643 		 * resolvers can NACK a resolution request using an
27644 		 * existing design that has no specific provisions for NACKs,
27645 		 * and also takes into account that the current non-ARP
27646 		 * external resolver has been coded to use this method of
27647 		 * NACKing for all IPv6 (xresolv) cases,
27648 		 * whether our xresolv implementation is complete or not.
27649 		 *
27650 		 */
27651 		ire = (ire_t *)mp->b_rptr;
27652 		ill = ire_to_ill(ire);
27653 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27654 		if (mp1->b_rptr == mp1->b_wptr) {
27655 			if (ire->ire_ipversion == IPV6_VERSION) {
27656 				/*
27657 				 * XRESOLV interface.
27658 				 */
27659 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27660 				mutex_enter(&ire->ire_lock);
27661 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27662 				mutex_exit(&ire->ire_lock);
27663 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27664 					nce = ndp_lookup_v6(ill, B_FALSE,
27665 					    &ire->ire_addr_v6, B_FALSE);
27666 				} else {
27667 					nce = ndp_lookup_v6(ill, B_FALSE,
27668 					    &gw_addr_v6, B_FALSE);
27669 				}
27670 				if (nce != NULL) {
27671 					nce_resolv_failed(nce);
27672 					ndp_delete(nce);
27673 					NCE_REFRELE(nce);
27674 				}
27675 			}
27676 			mp->b_cont = NULL;
27677 			freemsg(mp1);		/* frees the pkt as well */
27678 			ASSERT(ire->ire_nce == NULL);
27679 			ire_delete((ire_t *)mp->b_rptr);
27680 			return;
27681 		}
27682 
27683 		/*
27684 		 * Split them into IRE_MBLK and pkt and feed it into
27685 		 * ire_add_then_send. Then in ire_add_then_send
27686 		 * the IRE will be added, and then the packet will be
27687 		 * run back through ip_wput. This time it will make
27688 		 * it to the wire.
27689 		 */
27690 		mp->b_cont = NULL;
27691 		mp = mp1->b_cont;		/* now, mp points to pkt */
27692 		mp1->b_cont = NULL;
27693 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27694 		if (ire->ire_ipversion == IPV6_VERSION) {
27695 			/*
27696 			 * XRESOLV interface. Find the nce and put a copy
27697 			 * of the dl_unitdata_req in nce_res_mp
27698 			 */
27699 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27700 			mutex_enter(&ire->ire_lock);
27701 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27702 			mutex_exit(&ire->ire_lock);
27703 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27704 				nce = ndp_lookup_v6(ill, B_FALSE,
27705 				    &ire->ire_addr_v6, B_FALSE);
27706 			} else {
27707 				nce = ndp_lookup_v6(ill, B_FALSE,
27708 				    &gw_addr_v6, B_FALSE);
27709 			}
27710 			if (nce != NULL) {
27711 				/*
27712 				 * We have to protect nce_res_mp here
27713 				 * from being accessed by other threads
27714 				 * while we change the mblk pointer.
27715 				 * Other functions will also lock the nce when
27716 				 * accessing nce_res_mp.
27717 				 *
27718 				 * The reason we change the mblk pointer
27719 				 * here rather than copying the resolved address
27720 				 * into the template is that, unlike with
27721 				 * ethernet, we have no guarantee that the
27722 				 * resolved address length will be
27723 				 * smaller than or equal to the lla length
27724 				 * with which the template was allocated,
27725 				 * (for ethernet, they're equal)
27726 				 * so we have to use the actual resolved
27727 				 * address mblk - which holds the real
27728 				 * dl_unitdata_req with the resolved address.
27729 				 *
27730 				 * Doing this is the same behavior as was
27731 				 * previously used in the v4 ARP case.
27732 				 */
27733 				mutex_enter(&nce->nce_lock);
27734 				if (nce->nce_res_mp != NULL)
27735 					freemsg(nce->nce_res_mp);
27736 				nce->nce_res_mp = mp1;
27737 				mutex_exit(&nce->nce_lock);
27738 				/*
27739 				 * We do a fastpath probe here because
27740 				 * we have resolved the address without
27741 				 * using Neighbor Discovery.
27742 				 * In the non-XRESOLV v6 case, the fastpath
27743 				 * probe is done right after neighbor
27744 				 * discovery completes.
27745 				 */
27746 				if (nce->nce_res_mp != NULL) {
27747 					int res;
27748 					nce_fastpath_list_add(nce);
27749 					res = ill_fastpath_probe(ill,
27750 					    nce->nce_res_mp);
27751 					if (res != 0 && res != EAGAIN)
27752 						nce_fastpath_list_delete(nce);
27753 				}
27754 
27755 				ire_add_then_send(q, ire, mp);
27756 				/*
27757 				 * Now we have to clean out any packets
27758 				 * that may have been queued on the nce
27759 				 * while it was waiting for address resolution
27760 				 * to complete.
27761 				 */
27762 				mutex_enter(&nce->nce_lock);
27763 				mp1 = nce->nce_qd_mp;
27764 				nce->nce_qd_mp = NULL;
27765 				mutex_exit(&nce->nce_lock);
27766 				while (mp1 != NULL) {
27767 					mblk_t *nxt_mp;
27768 					queue_t *fwdq = NULL;
27769 					ill_t   *inbound_ill;
27770 					uint_t ifindex;
27771 
27772 					nxt_mp = mp1->b_next;
27773 					mp1->b_next = NULL;
27774 					/*
27775 					 * Retrieve ifindex stored in
27776 					 * ip_rput_data_v6()
27777 					 */
27778 					ifindex =
27779 					    (uint_t)(uintptr_t)mp1->b_prev;
27780 					inbound_ill =
27781 					    ill_lookup_on_ifindex(ifindex,
27782 					    B_TRUE, NULL, NULL, NULL,
27783 					    NULL, ipst);
27784 					mp1->b_prev = NULL;
27785 					if (inbound_ill != NULL)
27786 						fwdq = inbound_ill->ill_rq;
27787 
27788 					if (fwdq != NULL) {
27789 						put(fwdq, mp1);
27790 						ill_refrele(inbound_ill);
27791 					} else
27792 						put(WR(ill->ill_rq), mp1);
27793 					mp1 = nxt_mp;
27794 				}
27795 				NCE_REFRELE(nce);
27796 			} else {	/* nce is NULL; clean up */
27797 				ire_delete(ire);
27798 				freemsg(mp);
27799 				freemsg(mp1);
27800 				return;
27801 			}
27802 		} else {
27803 			nce_t *arpce;
27804 			/*
27805 			 * Link layer resolution succeeded. Recompute the
27806 			 * ire_nce.
27807 			 */
27808 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27809 			if ((arpce = ndp_lookup_v4(ill,
27810 			    (ire->ire_gateway_addr != INADDR_ANY ?
27811 			    &ire->ire_gateway_addr : &ire->ire_addr),
27812 			    B_FALSE)) == NULL) {
27813 				freeb(ire->ire_mp);
27814 				freeb(mp1);
27815 				freemsg(mp);
27816 				return;
27817 			}
27818 			mutex_enter(&arpce->nce_lock);
27819 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27820 			if (arpce->nce_state == ND_REACHABLE) {
27821 				/*
27822 				 * Someone resolved this before us;
27823 				 * cleanup the res_mp. Since ire has
27824 				 * not been added yet, the call to ire_add_v4
27825 				 * from ire_add_then_send (when a dup is
27826 				 * detected) will clean up the ire.
27827 				 */
27828 				freeb(mp1);
27829 			} else {
27830 				ASSERT(arpce->nce_res_mp == NULL);
27831 				arpce->nce_res_mp = mp1;
27832 				arpce->nce_state = ND_REACHABLE;
27833 			}
27834 			mutex_exit(&arpce->nce_lock);
27835 			if (ire->ire_marks & IRE_MARK_NOADD) {
27836 				/*
27837 				 * this ire will not be added to the ire
27838 				 * cache table, so we can set the ire_nce
27839 				 * here, as there are no atomicity constraints.
27840 				 */
27841 				ire->ire_nce = arpce;
27842 				/*
27843 				 * We are associating this nce with the ire
27844 				 * so change the nce ref taken in
27845 				 * ndp_lookup_v4() from
27846 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27847 				 */
27848 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27849 			} else {
27850 				NCE_REFRELE(arpce);
27851 			}
27852 			ire_add_then_send(q, ire, mp);
27853 		}
27854 		return;	/* All is well, the packet has been sent. */
27855 	}
27856 	case IRE_ARPRESOLVE_TYPE: {
27857 
27858 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27859 			break;
27860 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27861 		mp->b_cont = NULL;
27862 		/*
27863 		 * First, check to make sure the resolution succeeded.
27864 		 * If it failed, the second mblk will be empty.
27865 		 */
27866 		if (mp1->b_rptr == mp1->b_wptr) {
27867 			/* cleanup  the incomplete ire, free queued packets */
27868 			freemsg(mp); /* fake ire */
27869 			freeb(mp1);  /* dl_unitdata response */
27870 			return;
27871 		}
27872 
27873 		/*
27874 		 * Update any incomplete nce_t found. We search the ctable
27875 		 * and find the nce from the ire->ire_nce because we need
27876 		 * to pass the ire to ip_xmit_v4 later, and can find both
27877 		 * ire and nce in one lookup.
27878 		 */
27879 		fake_ire = (ire_t *)mp->b_rptr;
27880 
27881 		/*
27882 		 * By the time we come back here from ARP the logical outgoing
27883 		 * interface of the incomplete ire we added in ire_forward()
27884 		 * could have disappeared, causing the incomplete ire to also
27885 		 * disappear.  So we need to retreive the proper ipif for the
27886 		 * ire before looking in ctable.  In the case of IPMP, the
27887 		 * ipif may be on the IPMP ill, so look it up based on the
27888 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27889 		 * Then, we can verify that ire_ipif_seqid still exists.
27890 		 */
27891 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27892 		    NULL, NULL, NULL, NULL, ipst);
27893 		if (ill == NULL) {
27894 			ip1dbg(("ill for incomplete ire vanished\n"));
27895 			freemsg(mp); /* fake ire */
27896 			freeb(mp1);  /* dl_unitdata response */
27897 			return;
27898 		}
27899 
27900 		/* Get the outgoing ipif */
27901 		mutex_enter(&ill->ill_lock);
27902 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27903 		if (ipif == NULL) {
27904 			mutex_exit(&ill->ill_lock);
27905 			ill_refrele(ill);
27906 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27907 			freemsg(mp); /* fake_ire */
27908 			freeb(mp1);  /* dl_unitdata response */
27909 			return;
27910 		}
27911 
27912 		ipif_refhold_locked(ipif);
27913 		mutex_exit(&ill->ill_lock);
27914 		ill_refrele(ill);
27915 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27916 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27917 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27918 		ipif_refrele(ipif);
27919 		if (ire == NULL) {
27920 			/*
27921 			 * no ire was found; check if there is an nce
27922 			 * for this lookup; if it has no ire's pointing at it
27923 			 * cleanup.
27924 			 */
27925 			if ((nce = ndp_lookup_v4(q->q_ptr,
27926 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27927 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27928 			    B_FALSE)) != NULL) {
27929 				/*
27930 				 * cleanup:
27931 				 * We check for refcnt 2 (one for the nce
27932 				 * hash list + 1 for the ref taken by
27933 				 * ndp_lookup_v4) to check that there are
27934 				 * no ire's pointing at the nce.
27935 				 */
27936 				if (nce->nce_refcnt == 2)
27937 					ndp_delete(nce);
27938 				NCE_REFRELE(nce);
27939 			}
27940 			freeb(mp1);  /* dl_unitdata response */
27941 			freemsg(mp); /* fake ire */
27942 			return;
27943 		}
27944 
27945 		nce = ire->ire_nce;
27946 		DTRACE_PROBE2(ire__arpresolve__type,
27947 		    ire_t *, ire, nce_t *, nce);
27948 		mutex_enter(&nce->nce_lock);
27949 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27950 		if (nce->nce_state == ND_REACHABLE) {
27951 			/*
27952 			 * Someone resolved this before us;
27953 			 * our response is not needed any more.
27954 			 */
27955 			mutex_exit(&nce->nce_lock);
27956 			freeb(mp1);  /* dl_unitdata response */
27957 		} else {
27958 			ASSERT(nce->nce_res_mp == NULL);
27959 			nce->nce_res_mp = mp1;
27960 			nce->nce_state = ND_REACHABLE;
27961 			mutex_exit(&nce->nce_lock);
27962 			nce_fastpath(nce);
27963 		}
27964 		/*
27965 		 * The cached nce_t has been updated to be reachable;
27966 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27967 		 */
27968 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27969 		freemsg(mp);
27970 		/*
27971 		 * send out queued packets.
27972 		 */
27973 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27974 
27975 		IRE_REFRELE(ire);
27976 		return;
27977 	}
27978 	default:
27979 		break;
27980 	}
27981 	if (q->q_next) {
27982 		putnext(q, mp);
27983 	} else
27984 		freemsg(mp);
27985 	return;
27986 
27987 protonak:
27988 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27989 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27990 		qreply(q, mp);
27991 }
27992 
27993 /*
27994  * Process IP options in an outbound packet.  Modify the destination if there
27995  * is a source route option.
27996  * Returns non-zero if something fails in which case an ICMP error has been
27997  * sent and mp freed.
27998  */
27999 static int
28000 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28001     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28002 {
28003 	ipoptp_t	opts;
28004 	uchar_t		*opt;
28005 	uint8_t		optval;
28006 	uint8_t		optlen;
28007 	ipaddr_t	dst;
28008 	intptr_t	code = 0;
28009 	mblk_t		*mp;
28010 	ire_t		*ire = NULL;
28011 
28012 	ip2dbg(("ip_wput_options\n"));
28013 	mp = ipsec_mp;
28014 	if (mctl_present) {
28015 		mp = ipsec_mp->b_cont;
28016 	}
28017 
28018 	dst = ipha->ipha_dst;
28019 	for (optval = ipoptp_first(&opts, ipha);
28020 	    optval != IPOPT_EOL;
28021 	    optval = ipoptp_next(&opts)) {
28022 		opt = opts.ipoptp_cur;
28023 		optlen = opts.ipoptp_len;
28024 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28025 		    optval, optlen));
28026 		switch (optval) {
28027 			uint32_t off;
28028 		case IPOPT_SSRR:
28029 		case IPOPT_LSRR:
28030 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28031 				ip1dbg((
28032 				    "ip_wput_options: bad option offset\n"));
28033 				code = (char *)&opt[IPOPT_OLEN] -
28034 				    (char *)ipha;
28035 				goto param_prob;
28036 			}
28037 			off = opt[IPOPT_OFFSET];
28038 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28039 			    ntohl(dst)));
28040 			/*
28041 			 * For strict: verify that dst is directly
28042 			 * reachable.
28043 			 */
28044 			if (optval == IPOPT_SSRR) {
28045 				ire = ire_ftable_lookup(dst, 0, 0,
28046 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28047 				    msg_getlabel(mp),
28048 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28049 				if (ire == NULL) {
28050 					ip1dbg(("ip_wput_options: SSRR not"
28051 					    " directly reachable: 0x%x\n",
28052 					    ntohl(dst)));
28053 					goto bad_src_route;
28054 				}
28055 				ire_refrele(ire);
28056 			}
28057 			break;
28058 		case IPOPT_RR:
28059 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28060 				ip1dbg((
28061 				    "ip_wput_options: bad option offset\n"));
28062 				code = (char *)&opt[IPOPT_OLEN] -
28063 				    (char *)ipha;
28064 				goto param_prob;
28065 			}
28066 			break;
28067 		case IPOPT_TS:
28068 			/*
28069 			 * Verify that length >=5 and that there is either
28070 			 * room for another timestamp or that the overflow
28071 			 * counter is not maxed out.
28072 			 */
28073 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28074 			if (optlen < IPOPT_MINLEN_IT) {
28075 				goto param_prob;
28076 			}
28077 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28078 				ip1dbg((
28079 				    "ip_wput_options: bad option offset\n"));
28080 				code = (char *)&opt[IPOPT_OFFSET] -
28081 				    (char *)ipha;
28082 				goto param_prob;
28083 			}
28084 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28085 			case IPOPT_TS_TSONLY:
28086 				off = IPOPT_TS_TIMELEN;
28087 				break;
28088 			case IPOPT_TS_TSANDADDR:
28089 			case IPOPT_TS_PRESPEC:
28090 			case IPOPT_TS_PRESPEC_RFC791:
28091 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28092 				break;
28093 			default:
28094 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28095 				    (char *)ipha;
28096 				goto param_prob;
28097 			}
28098 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28099 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28100 				/*
28101 				 * No room and the overflow counter is 15
28102 				 * already.
28103 				 */
28104 				goto param_prob;
28105 			}
28106 			break;
28107 		}
28108 	}
28109 
28110 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28111 		return (0);
28112 
28113 	ip1dbg(("ip_wput_options: error processing IP options."));
28114 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28115 
28116 param_prob:
28117 	/*
28118 	 * Since ip_wput() isn't close to finished, we fill
28119 	 * in enough of the header for credible error reporting.
28120 	 */
28121 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28122 		/* Failed */
28123 		freemsg(ipsec_mp);
28124 		return (-1);
28125 	}
28126 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28127 	return (-1);
28128 
28129 bad_src_route:
28130 	/*
28131 	 * Since ip_wput() isn't close to finished, we fill
28132 	 * in enough of the header for credible error reporting.
28133 	 */
28134 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28135 		/* Failed */
28136 		freemsg(ipsec_mp);
28137 		return (-1);
28138 	}
28139 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28140 	return (-1);
28141 }
28142 
28143 /*
28144  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28145  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28146  * thru /etc/system.
28147  */
28148 #define	CONN_MAXDRAINCNT	64
28149 
28150 static void
28151 conn_drain_init(ip_stack_t *ipst)
28152 {
28153 	int i, j;
28154 	idl_tx_list_t *itl_tx;
28155 
28156 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28157 
28158 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28159 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28160 		/*
28161 		 * Default value of the number of drainers is the
28162 		 * number of cpus, subject to maximum of 8 drainers.
28163 		 */
28164 		if (boot_max_ncpus != -1)
28165 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28166 		else
28167 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28168 	}
28169 
28170 	ipst->ips_idl_tx_list =
28171 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
28172 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28173 		itl_tx =  &ipst->ips_idl_tx_list[i];
28174 		itl_tx->txl_drain_list =
28175 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28176 		    sizeof (idl_t), KM_SLEEP);
28177 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
28178 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
28179 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
28180 			    MUTEX_DEFAULT, NULL);
28181 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
28182 		}
28183 	}
28184 }
28185 
28186 static void
28187 conn_drain_fini(ip_stack_t *ipst)
28188 {
28189 	int i;
28190 	idl_tx_list_t *itl_tx;
28191 
28192 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28193 		itl_tx =  &ipst->ips_idl_tx_list[i];
28194 		kmem_free(itl_tx->txl_drain_list,
28195 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28196 	}
28197 	kmem_free(ipst->ips_idl_tx_list,
28198 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28199 	ipst->ips_idl_tx_list = NULL;
28200 }
28201 
28202 /*
28203  * Note: For an overview of how flowcontrol is handled in IP please see the
28204  * IP Flowcontrol notes at the top of this file.
28205  *
28206  * Flow control has blocked us from proceeding. Insert the given conn in one
28207  * of the conn drain lists. These conn wq's will be qenabled later on when
28208  * STREAMS flow control does a backenable. conn_walk_drain will enable
28209  * the first conn in each of these drain lists. Each of these qenabled conns
28210  * in turn enables the next in the list, after it runs, or when it closes,
28211  * thus sustaining the drain process.
28212  */
28213 void
28214 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28215 {
28216 	idl_t	*idl = tx_list->txl_drain_list;
28217 	uint_t	index;
28218 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28219 
28220 	mutex_enter(&connp->conn_lock);
28221 	if (connp->conn_state_flags & CONN_CLOSING) {
28222 		/*
28223 		 * The conn is closing as a result of which CONN_CLOSING
28224 		 * is set. Return.
28225 		 */
28226 		mutex_exit(&connp->conn_lock);
28227 		return;
28228 	} else if (connp->conn_idl == NULL) {
28229 		/*
28230 		 * Assign the next drain list round robin. We dont' use
28231 		 * a lock, and thus it may not be strictly round robin.
28232 		 * Atomicity of load/stores is enough to make sure that
28233 		 * conn_drain_list_index is always within bounds.
28234 		 */
28235 		index = tx_list->txl_drain_index;
28236 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28237 		connp->conn_idl = &tx_list->txl_drain_list[index];
28238 		index++;
28239 		if (index == ipst->ips_conn_drain_list_cnt)
28240 			index = 0;
28241 		tx_list->txl_drain_index = index;
28242 	}
28243 	mutex_exit(&connp->conn_lock);
28244 
28245 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28246 	if ((connp->conn_drain_prev != NULL) ||
28247 	    (connp->conn_state_flags & CONN_CLOSING)) {
28248 		/*
28249 		 * The conn is already in the drain list, OR
28250 		 * the conn is closing. We need to check again for
28251 		 * the closing case again since close can happen
28252 		 * after we drop the conn_lock, and before we
28253 		 * acquire the CONN_DRAIN_LIST_LOCK.
28254 		 */
28255 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28256 		return;
28257 	} else {
28258 		idl = connp->conn_idl;
28259 	}
28260 
28261 	/*
28262 	 * The conn is not in the drain list. Insert it at the
28263 	 * tail of the drain list. The drain list is circular
28264 	 * and doubly linked. idl_conn points to the 1st element
28265 	 * in the list.
28266 	 */
28267 	if (idl->idl_conn == NULL) {
28268 		idl->idl_conn = connp;
28269 		connp->conn_drain_next = connp;
28270 		connp->conn_drain_prev = connp;
28271 	} else {
28272 		conn_t *head = idl->idl_conn;
28273 
28274 		connp->conn_drain_next = head;
28275 		connp->conn_drain_prev = head->conn_drain_prev;
28276 		head->conn_drain_prev->conn_drain_next = connp;
28277 		head->conn_drain_prev = connp;
28278 	}
28279 	/*
28280 	 * For non streams based sockets assert flow control.
28281 	 */
28282 	if (IPCL_IS_NONSTR(connp)) {
28283 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28284 		(*connp->conn_upcalls->su_txq_full)
28285 		    (connp->conn_upper_handle, B_TRUE);
28286 	} else {
28287 		conn_setqfull(connp);
28288 		noenable(connp->conn_wq);
28289 	}
28290 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28291 }
28292 
28293 /*
28294  * This conn is closing, and we are called from ip_close. OR
28295  * This conn has been serviced by ip_wsrv, and we need to do the tail
28296  * processing.
28297  * If this conn is part of the drain list, we may need to sustain the drain
28298  * process by qenabling the next conn in the drain list. We may also need to
28299  * remove this conn from the list, if it is done.
28300  */
28301 static void
28302 conn_drain_tail(conn_t *connp, boolean_t closing)
28303 {
28304 	idl_t *idl;
28305 
28306 	/*
28307 	 * connp->conn_idl is stable at this point, and no lock is needed
28308 	 * to check it. If we are called from ip_close, close has already
28309 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28310 	 * called us only because conn_idl is non-null. If we are called thru
28311 	 * service, conn_idl could be null, but it cannot change because
28312 	 * service is single-threaded per queue, and there cannot be another
28313 	 * instance of service trying to call conn_drain_insert on this conn
28314 	 * now.
28315 	 */
28316 	ASSERT(!closing || (connp->conn_idl != NULL));
28317 
28318 	/*
28319 	 * If connp->conn_idl is null, the conn has not been inserted into any
28320 	 * drain list even once since creation of the conn. Just return.
28321 	 */
28322 	if (connp->conn_idl == NULL)
28323 		return;
28324 
28325 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28326 
28327 	if (connp->conn_drain_prev == NULL) {
28328 		/* This conn is currently not in the drain list.  */
28329 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28330 		return;
28331 	}
28332 	idl = connp->conn_idl;
28333 	if (idl->idl_conn_draining == connp) {
28334 		/*
28335 		 * This conn is the current drainer. If this is the last conn
28336 		 * in the drain list, we need to do more checks, in the 'if'
28337 		 * below. Otherwwise we need to just qenable the next conn,
28338 		 * to sustain the draining, and is handled in the 'else'
28339 		 * below.
28340 		 */
28341 		if (connp->conn_drain_next == idl->idl_conn) {
28342 			/*
28343 			 * This conn is the last in this list. This round
28344 			 * of draining is complete. If idl_repeat is set,
28345 			 * it means another flow enabling has happened from
28346 			 * the driver/streams and we need to another round
28347 			 * of draining.
28348 			 * If there are more than 2 conns in the drain list,
28349 			 * do a left rotate by 1, so that all conns except the
28350 			 * conn at the head move towards the head by 1, and the
28351 			 * the conn at the head goes to the tail. This attempts
28352 			 * a more even share for all queues that are being
28353 			 * drained.
28354 			 */
28355 			if ((connp->conn_drain_next != connp) &&
28356 			    (idl->idl_conn->conn_drain_next != connp)) {
28357 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28358 			}
28359 			if (idl->idl_repeat) {
28360 				qenable(idl->idl_conn->conn_wq);
28361 				idl->idl_conn_draining = idl->idl_conn;
28362 				idl->idl_repeat = 0;
28363 			} else {
28364 				idl->idl_conn_draining = NULL;
28365 			}
28366 		} else {
28367 			/*
28368 			 * If the next queue that we are now qenable'ing,
28369 			 * is closing, it will remove itself from this list
28370 			 * and qenable the subsequent queue in ip_close().
28371 			 * Serialization is acheived thru idl_lock.
28372 			 */
28373 			qenable(connp->conn_drain_next->conn_wq);
28374 			idl->idl_conn_draining = connp->conn_drain_next;
28375 		}
28376 	}
28377 	if (!connp->conn_did_putbq || closing) {
28378 		/*
28379 		 * Remove ourself from the drain list, if we did not do
28380 		 * a putbq, or if the conn is closing.
28381 		 * Note: It is possible that q->q_first is non-null. It means
28382 		 * that these messages landed after we did a enableok() in
28383 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28384 		 * service them.
28385 		 */
28386 		if (connp->conn_drain_next == connp) {
28387 			/* Singleton in the list */
28388 			ASSERT(connp->conn_drain_prev == connp);
28389 			idl->idl_conn = NULL;
28390 			idl->idl_conn_draining = NULL;
28391 		} else {
28392 			connp->conn_drain_prev->conn_drain_next =
28393 			    connp->conn_drain_next;
28394 			connp->conn_drain_next->conn_drain_prev =
28395 			    connp->conn_drain_prev;
28396 			if (idl->idl_conn == connp)
28397 				idl->idl_conn = connp->conn_drain_next;
28398 			ASSERT(idl->idl_conn_draining != connp);
28399 
28400 		}
28401 		connp->conn_drain_next = NULL;
28402 		connp->conn_drain_prev = NULL;
28403 
28404 		/*
28405 		 * For non streams based sockets open up flow control.
28406 		 */
28407 		if (IPCL_IS_NONSTR(connp)) {
28408 			(*connp->conn_upcalls->su_txq_full)
28409 			    (connp->conn_upper_handle, B_FALSE);
28410 		} else {
28411 			conn_clrqfull(connp);
28412 			enableok(connp->conn_wq);
28413 		}
28414 	}
28415 
28416 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28417 }
28418 
28419 /*
28420  * Write service routine. Shared perimeter entry point.
28421  * ip_wsrv can be called in any of the following ways.
28422  * 1. The device queue's messages has fallen below the low water mark
28423  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28424  *    the drain lists and backenable the first conn in each list.
28425  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28426  *    qenabled non-tcp upper layers. We start dequeing messages and call
28427  *    ip_wput for each message.
28428  */
28429 
28430 void
28431 ip_wsrv(queue_t *q)
28432 {
28433 	conn_t	*connp;
28434 	ill_t	*ill;
28435 	mblk_t	*mp;
28436 
28437 	if (q->q_next) {
28438 		ill = (ill_t *)q->q_ptr;
28439 		if (ill->ill_state_flags == 0) {
28440 			ip_stack_t *ipst = ill->ill_ipst;
28441 
28442 			/*
28443 			 * The device flow control has opened up.
28444 			 * Walk through conn drain lists and qenable the
28445 			 * first conn in each list. This makes sense only
28446 			 * if the stream is fully plumbed and setup.
28447 			 * Hence the if check above.
28448 			 */
28449 			ip1dbg(("ip_wsrv: walking\n"));
28450 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28451 		}
28452 		return;
28453 	}
28454 
28455 	connp = Q_TO_CONN(q);
28456 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28457 
28458 	/*
28459 	 * 1. Set conn_draining flag to signal that service is active.
28460 	 *
28461 	 * 2. ip_output determines whether it has been called from service,
28462 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28463 	 *    has been called from service.
28464 	 *
28465 	 * 3. Message ordering is preserved by the following logic.
28466 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28467 	 *    the message at the tail, if conn_draining is set (i.e. service
28468 	 *    is running) or if q->q_first is non-null.
28469 	 *
28470 	 *    ii. If ip_output is called from service, and if ip_output cannot
28471 	 *    putnext due to flow control, it does a putbq.
28472 	 *
28473 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28474 	 *    (causing an infinite loop).
28475 	 */
28476 	ASSERT(!connp->conn_did_putbq);
28477 
28478 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28479 		connp->conn_draining = 1;
28480 		noenable(q);
28481 		while ((mp = getq(q)) != NULL) {
28482 			ASSERT(CONN_Q(q));
28483 
28484 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28485 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28486 			if (connp->conn_did_putbq) {
28487 				/* ip_wput did a putbq */
28488 				break;
28489 			}
28490 		}
28491 		/*
28492 		 * At this point, a thread coming down from top, calling
28493 		 * ip_wput, may end up queueing the message. We have not yet
28494 		 * enabled the queue, so ip_wsrv won't be called again.
28495 		 * To avoid this race, check q->q_first again (in the loop)
28496 		 * If the other thread queued the message before we call
28497 		 * enableok(), we will catch it in the q->q_first check.
28498 		 * If the other thread queues the message after we call
28499 		 * enableok(), ip_wsrv will be called again by STREAMS.
28500 		 */
28501 		connp->conn_draining = 0;
28502 		enableok(q);
28503 	}
28504 
28505 	/* Enable the next conn for draining */
28506 	conn_drain_tail(connp, B_FALSE);
28507 
28508 	/*
28509 	 * conn_direct_blocked is used to indicate blocked
28510 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28511 	 * This is the only place where it is set without
28512 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28513 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28514 	 */
28515 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28516 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28517 		connp->conn_direct_blocked = B_FALSE;
28518 	}
28519 
28520 	connp->conn_did_putbq = 0;
28521 }
28522 
28523 /*
28524  * Callback to disable flow control in IP.
28525  *
28526  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28527  * is enabled.
28528  *
28529  * When MAC_TX() is not able to send any more packets, dld sets its queue
28530  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28531  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28532  * function and wakes up corresponding mac worker threads, which in turn
28533  * calls this callback function, and disables flow control.
28534  */
28535 void
28536 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28537 {
28538 	ill_t *ill = (ill_t *)arg;
28539 	ip_stack_t *ipst = ill->ill_ipst;
28540 	idl_tx_list_t *idl_txl;
28541 
28542 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28543 	mutex_enter(&idl_txl->txl_lock);
28544 	/* add code to to set a flag to indicate idl_txl is enabled */
28545 	conn_walk_drain(ipst, idl_txl);
28546 	mutex_exit(&idl_txl->txl_lock);
28547 }
28548 
28549 /*
28550  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28551  * of conns that need to be drained, check if drain is already in progress.
28552  * If so set the idl_repeat bit, indicating that the last conn in the list
28553  * needs to reinitiate the drain once again, for the list. If drain is not
28554  * in progress for the list, initiate the draining, by qenabling the 1st
28555  * conn in the list. The drain is self-sustaining, each qenabled conn will
28556  * in turn qenable the next conn, when it is done/blocked/closing.
28557  */
28558 static void
28559 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28560 {
28561 	int i;
28562 	idl_t *idl;
28563 
28564 	IP_STAT(ipst, ip_conn_walk_drain);
28565 
28566 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28567 		idl = &tx_list->txl_drain_list[i];
28568 		mutex_enter(&idl->idl_lock);
28569 		if (idl->idl_conn == NULL) {
28570 			mutex_exit(&idl->idl_lock);
28571 			continue;
28572 		}
28573 		/*
28574 		 * If this list is not being drained currently by
28575 		 * an ip_wsrv thread, start the process.
28576 		 */
28577 		if (idl->idl_conn_draining == NULL) {
28578 			ASSERT(idl->idl_repeat == 0);
28579 			qenable(idl->idl_conn->conn_wq);
28580 			idl->idl_conn_draining = idl->idl_conn;
28581 		} else {
28582 			idl->idl_repeat = 1;
28583 		}
28584 		mutex_exit(&idl->idl_lock);
28585 	}
28586 }
28587 
28588 /*
28589  * Determine if the ill and multicast aspects of that packets
28590  * "matches" the conn.
28591  */
28592 boolean_t
28593 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28594     zoneid_t zoneid)
28595 {
28596 	ill_t *bound_ill;
28597 	boolean_t found;
28598 	ipif_t *ipif;
28599 	ire_t *ire;
28600 	ipaddr_t dst, src;
28601 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28602 
28603 	dst = ipha->ipha_dst;
28604 	src = ipha->ipha_src;
28605 
28606 	/*
28607 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28608 	 * unicast, broadcast and multicast reception to
28609 	 * conn_incoming_ill. conn_wantpacket itself is called
28610 	 * only for BROADCAST and multicast.
28611 	 */
28612 	bound_ill = connp->conn_incoming_ill;
28613 	if (bound_ill != NULL) {
28614 		if (IS_IPMP(bound_ill)) {
28615 			if (bound_ill->ill_grp != ill->ill_grp)
28616 				return (B_FALSE);
28617 		} else {
28618 			if (bound_ill != ill)
28619 				return (B_FALSE);
28620 		}
28621 	}
28622 
28623 	if (!CLASSD(dst)) {
28624 		if (IPCL_ZONE_MATCH(connp, zoneid))
28625 			return (B_TRUE);
28626 		/*
28627 		 * The conn is in a different zone; we need to check that this
28628 		 * broadcast address is configured in the application's zone.
28629 		 */
28630 		ipif = ipif_get_next_ipif(NULL, ill);
28631 		if (ipif == NULL)
28632 			return (B_FALSE);
28633 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28634 		    connp->conn_zoneid, NULL,
28635 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28636 		ipif_refrele(ipif);
28637 		if (ire != NULL) {
28638 			ire_refrele(ire);
28639 			return (B_TRUE);
28640 		} else {
28641 			return (B_FALSE);
28642 		}
28643 	}
28644 
28645 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28646 	    connp->conn_zoneid == zoneid) {
28647 		/*
28648 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28649 		 * disabled, therefore we don't dispatch the multicast packet to
28650 		 * the sending zone.
28651 		 */
28652 		return (B_FALSE);
28653 	}
28654 
28655 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28656 		/*
28657 		 * Multicast packet on the loopback interface: we only match
28658 		 * conns who joined the group in the specified zone.
28659 		 */
28660 		return (B_FALSE);
28661 	}
28662 
28663 	if (connp->conn_multi_router) {
28664 		/* multicast packet and multicast router socket: send up */
28665 		return (B_TRUE);
28666 	}
28667 
28668 	mutex_enter(&connp->conn_lock);
28669 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28670 	mutex_exit(&connp->conn_lock);
28671 	return (found);
28672 }
28673 
28674 static void
28675 conn_setqfull(conn_t *connp)
28676 {
28677 	queue_t *q = connp->conn_wq;
28678 
28679 	if (!(q->q_flag & QFULL)) {
28680 		mutex_enter(QLOCK(q));
28681 		if (!(q->q_flag & QFULL)) {
28682 			/* still need to set QFULL */
28683 			q->q_flag |= QFULL;
28684 			mutex_exit(QLOCK(q));
28685 		} else {
28686 			mutex_exit(QLOCK(q));
28687 		}
28688 	}
28689 }
28690 
28691 static void
28692 conn_clrqfull(conn_t *connp)
28693 {
28694 	queue_t *q = connp->conn_wq;
28695 
28696 	if (q->q_flag & QFULL) {
28697 		mutex_enter(QLOCK(q));
28698 		if (q->q_flag & QFULL) {
28699 			q->q_flag &= ~QFULL;
28700 			mutex_exit(QLOCK(q));
28701 			if (q->q_flag & QWANTW)
28702 				qbackenable(q, 0);
28703 		} else {
28704 			mutex_exit(QLOCK(q));
28705 		}
28706 	}
28707 }
28708 
28709 /*
28710  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28711  */
28712 /* ARGSUSED */
28713 static void
28714 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28715 {
28716 	ill_t *ill = (ill_t *)q->q_ptr;
28717 	mblk_t	*mp1, *mp2;
28718 	ipif_t  *ipif;
28719 	int err = 0;
28720 	conn_t *connp = NULL;
28721 	ipsq_t	*ipsq;
28722 	arc_t	*arc;
28723 
28724 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28725 
28726 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28727 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28728 
28729 	ASSERT(IAM_WRITER_ILL(ill));
28730 	mp2 = mp->b_cont;
28731 	mp->b_cont = NULL;
28732 
28733 	/*
28734 	 * We have now received the arp bringup completion message
28735 	 * from ARP. Mark the arp bringup as done. Also if the arp
28736 	 * stream has already started closing, send up the AR_ARP_CLOSING
28737 	 * ack now since ARP is waiting in close for this ack.
28738 	 */
28739 	mutex_enter(&ill->ill_lock);
28740 	ill->ill_arp_bringup_pending = 0;
28741 	if (ill->ill_arp_closing) {
28742 		mutex_exit(&ill->ill_lock);
28743 		/* Let's reuse the mp for sending the ack */
28744 		arc = (arc_t *)mp->b_rptr;
28745 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28746 		arc->arc_cmd = AR_ARP_CLOSING;
28747 		qreply(q, mp);
28748 	} else {
28749 		mutex_exit(&ill->ill_lock);
28750 		freeb(mp);
28751 	}
28752 
28753 	ipsq = ill->ill_phyint->phyint_ipsq;
28754 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28755 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28756 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28757 	if (mp1 == NULL) {
28758 		/* bringup was aborted by the user */
28759 		freemsg(mp2);
28760 		return;
28761 	}
28762 
28763 	/*
28764 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28765 	 * must have an associated conn_t.  Otherwise, we're bringing this
28766 	 * interface back up as part of handling an asynchronous event (e.g.,
28767 	 * physical address change).
28768 	 */
28769 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28770 		ASSERT(connp != NULL);
28771 		q = CONNP_TO_WQ(connp);
28772 	} else {
28773 		ASSERT(connp == NULL);
28774 		q = ill->ill_rq;
28775 	}
28776 
28777 	/*
28778 	 * If the DL_BIND_REQ fails, it is noted
28779 	 * in arc_name_offset.
28780 	 */
28781 	err = *((int *)mp2->b_rptr);
28782 	if (err == 0) {
28783 		if (ipif->ipif_isv6) {
28784 			if ((err = ipif_up_done_v6(ipif)) != 0)
28785 				ip0dbg(("ip_arp_done: init failed\n"));
28786 		} else {
28787 			if ((err = ipif_up_done(ipif)) != 0)
28788 				ip0dbg(("ip_arp_done: init failed\n"));
28789 		}
28790 	} else {
28791 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28792 	}
28793 
28794 	freemsg(mp2);
28795 
28796 	if ((err == 0) && (ill->ill_up_ipifs)) {
28797 		err = ill_up_ipifs(ill, q, mp1);
28798 		if (err == EINPROGRESS)
28799 			return;
28800 	}
28801 
28802 	/*
28803 	 * If we have a moved ipif to bring up, and everything has succeeded
28804 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28805 	 * down -- the admin can try to bring it up by hand if need be.
28806 	 */
28807 	if (ill->ill_move_ipif != NULL) {
28808 		ipif = ill->ill_move_ipif;
28809 		ill->ill_move_ipif = NULL;
28810 		if (err == 0) {
28811 			err = ipif_up(ipif, q, mp1);
28812 			if (err == EINPROGRESS)
28813 				return;
28814 		}
28815 	}
28816 
28817 	/*
28818 	 * The operation must complete without EINPROGRESS since
28819 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28820 	 * operation will be stuck forever in the ipsq.
28821 	 */
28822 	ASSERT(err != EINPROGRESS);
28823 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28824 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28825 	else
28826 		ipsq_current_finish(ipsq);
28827 }
28828 
28829 /* Allocate the private structure */
28830 static int
28831 ip_priv_alloc(void **bufp)
28832 {
28833 	void	*buf;
28834 
28835 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28836 		return (ENOMEM);
28837 
28838 	*bufp = buf;
28839 	return (0);
28840 }
28841 
28842 /* Function to delete the private structure */
28843 void
28844 ip_priv_free(void *buf)
28845 {
28846 	ASSERT(buf != NULL);
28847 	kmem_free(buf, sizeof (ip_priv_t));
28848 }
28849 
28850 /*
28851  * The entry point for IPPF processing.
28852  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28853  * routine just returns.
28854  *
28855  * When called, ip_process generates an ipp_packet_t structure
28856  * which holds the state information for this packet and invokes the
28857  * the classifier (via ipp_packet_process). The classification, depending on
28858  * configured filters, results in a list of actions for this packet. Invoking
28859  * an action may cause the packet to be dropped, in which case the resulting
28860  * mblk (*mpp) is NULL. proc indicates the callout position for
28861  * this packet and ill_index is the interface this packet on or will leave
28862  * on (inbound and outbound resp.).
28863  */
28864 void
28865 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28866 {
28867 	mblk_t		*mp;
28868 	ip_priv_t	*priv;
28869 	ipp_action_id_t	aid;
28870 	int		rc = 0;
28871 	ipp_packet_t	*pp;
28872 #define	IP_CLASS	"ip"
28873 
28874 	/* If the classifier is not loaded, return  */
28875 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28876 		return;
28877 	}
28878 
28879 	mp = *mpp;
28880 	ASSERT(mp != NULL);
28881 
28882 	/* Allocate the packet structure */
28883 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28884 	if (rc != 0) {
28885 		*mpp = NULL;
28886 		freemsg(mp);
28887 		return;
28888 	}
28889 
28890 	/* Allocate the private structure */
28891 	rc = ip_priv_alloc((void **)&priv);
28892 	if (rc != 0) {
28893 		*mpp = NULL;
28894 		freemsg(mp);
28895 		ipp_packet_free(pp);
28896 		return;
28897 	}
28898 	priv->proc = proc;
28899 	priv->ill_index = ill_index;
28900 	ipp_packet_set_private(pp, priv, ip_priv_free);
28901 	ipp_packet_set_data(pp, mp);
28902 
28903 	/* Invoke the classifier */
28904 	rc = ipp_packet_process(&pp);
28905 	if (pp != NULL) {
28906 		mp = ipp_packet_get_data(pp);
28907 		ipp_packet_free(pp);
28908 		if (rc != 0) {
28909 			freemsg(mp);
28910 			*mpp = NULL;
28911 		}
28912 	} else {
28913 		*mpp = NULL;
28914 	}
28915 #undef	IP_CLASS
28916 }
28917 
28918 /*
28919  * Propagate a multicast group membership operation (add/drop) on
28920  * all the interfaces crossed by the related multirt routes.
28921  * The call is considered successful if the operation succeeds
28922  * on at least one interface.
28923  */
28924 static int
28925 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28926     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28927     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28928     mblk_t *first_mp)
28929 {
28930 	ire_t		*ire_gw;
28931 	irb_t		*irb;
28932 	int		error = 0;
28933 	opt_restart_t	*or;
28934 	ip_stack_t	*ipst = ire->ire_ipst;
28935 
28936 	irb = ire->ire_bucket;
28937 	ASSERT(irb != NULL);
28938 
28939 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28940 
28941 	or = (opt_restart_t *)first_mp->b_rptr;
28942 	IRB_REFHOLD(irb);
28943 	for (; ire != NULL; ire = ire->ire_next) {
28944 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28945 			continue;
28946 		if (ire->ire_addr != group)
28947 			continue;
28948 
28949 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28950 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28951 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28952 		/* No resolver exists for the gateway; skip this ire. */
28953 		if (ire_gw == NULL)
28954 			continue;
28955 
28956 		/*
28957 		 * This function can return EINPROGRESS. If so the operation
28958 		 * will be restarted from ip_restart_optmgmt which will
28959 		 * call ip_opt_set and option processing will restart for
28960 		 * this option. So we may end up calling 'fn' more than once.
28961 		 * This requires that 'fn' is idempotent except for the
28962 		 * return value. The operation is considered a success if
28963 		 * it succeeds at least once on any one interface.
28964 		 */
28965 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28966 		    NULL, fmode, src, first_mp);
28967 		if (error == 0)
28968 			or->or_private = CGTP_MCAST_SUCCESS;
28969 
28970 		if (ip_debug > 0) {
28971 			ulong_t	off;
28972 			char	*ksym;
28973 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28974 			ip2dbg(("ip_multirt_apply_membership: "
28975 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28976 			    "error %d [success %u]\n",
28977 			    ksym ? ksym : "?",
28978 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28979 			    error, or->or_private));
28980 		}
28981 
28982 		ire_refrele(ire_gw);
28983 		if (error == EINPROGRESS) {
28984 			IRB_REFRELE(irb);
28985 			return (error);
28986 		}
28987 	}
28988 	IRB_REFRELE(irb);
28989 	/*
28990 	 * Consider the call as successful if we succeeded on at least
28991 	 * one interface. Otherwise, return the last encountered error.
28992 	 */
28993 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28994 }
28995 
28996 /*
28997  * Issue a warning regarding a route crossing an interface with an
28998  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28999  * amount of time is logged.
29000  */
29001 static void
29002 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29003 {
29004 	hrtime_t	current = gethrtime();
29005 	char		buf[INET_ADDRSTRLEN];
29006 	ip_stack_t	*ipst = ire->ire_ipst;
29007 
29008 	/* Convert interval in ms to hrtime in ns */
29009 	if (ipst->ips_multirt_bad_mtu_last_time +
29010 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29011 	    current) {
29012 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29013 		    "to %s, incorrect MTU %u (expected %u)\n",
29014 		    ip_dot_addr(ire->ire_addr, buf),
29015 		    ire->ire_max_frag, max_frag);
29016 
29017 		ipst->ips_multirt_bad_mtu_last_time = current;
29018 	}
29019 }
29020 
29021 /*
29022  * Get the CGTP (multirouting) filtering status.
29023  * If 0, the CGTP hooks are transparent.
29024  */
29025 /* ARGSUSED */
29026 static int
29027 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29028 {
29029 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29030 
29031 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29032 	return (0);
29033 }
29034 
29035 /*
29036  * Set the CGTP (multirouting) filtering status.
29037  * If the status is changed from active to transparent
29038  * or from transparent to active, forward the new status
29039  * to the filtering module (if loaded).
29040  */
29041 /* ARGSUSED */
29042 static int
29043 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29044     cred_t *ioc_cr)
29045 {
29046 	long		new_value;
29047 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29048 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29049 
29050 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29051 		return (EPERM);
29052 
29053 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29054 	    new_value < 0 || new_value > 1) {
29055 		return (EINVAL);
29056 	}
29057 
29058 	if ((!*ip_cgtp_filter_value) && new_value) {
29059 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29060 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29061 		    " (module not loaded)" : "");
29062 	}
29063 	if (*ip_cgtp_filter_value && (!new_value)) {
29064 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29065 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29066 		    " (module not loaded)" : "");
29067 	}
29068 
29069 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29070 		int	res;
29071 		netstackid_t stackid;
29072 
29073 		stackid = ipst->ips_netstack->netstack_stackid;
29074 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29075 		    new_value);
29076 		if (res)
29077 			return (res);
29078 	}
29079 
29080 	*ip_cgtp_filter_value = (boolean_t)new_value;
29081 
29082 	return (0);
29083 }
29084 
29085 /*
29086  * Return the expected CGTP hooks version number.
29087  */
29088 int
29089 ip_cgtp_filter_supported(void)
29090 {
29091 	return (ip_cgtp_filter_rev);
29092 }
29093 
29094 /*
29095  * CGTP hooks can be registered by invoking this function.
29096  * Checks that the version number matches.
29097  */
29098 int
29099 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29100 {
29101 	netstack_t *ns;
29102 	ip_stack_t *ipst;
29103 
29104 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29105 		return (ENOTSUP);
29106 
29107 	ns = netstack_find_by_stackid(stackid);
29108 	if (ns == NULL)
29109 		return (EINVAL);
29110 	ipst = ns->netstack_ip;
29111 	ASSERT(ipst != NULL);
29112 
29113 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29114 		netstack_rele(ns);
29115 		return (EALREADY);
29116 	}
29117 
29118 	ipst->ips_ip_cgtp_filter_ops = ops;
29119 	netstack_rele(ns);
29120 	return (0);
29121 }
29122 
29123 /*
29124  * CGTP hooks can be unregistered by invoking this function.
29125  * Returns ENXIO if there was no registration.
29126  * Returns EBUSY if the ndd variable has not been turned off.
29127  */
29128 int
29129 ip_cgtp_filter_unregister(netstackid_t stackid)
29130 {
29131 	netstack_t *ns;
29132 	ip_stack_t *ipst;
29133 
29134 	ns = netstack_find_by_stackid(stackid);
29135 	if (ns == NULL)
29136 		return (EINVAL);
29137 	ipst = ns->netstack_ip;
29138 	ASSERT(ipst != NULL);
29139 
29140 	if (ipst->ips_ip_cgtp_filter) {
29141 		netstack_rele(ns);
29142 		return (EBUSY);
29143 	}
29144 
29145 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29146 		netstack_rele(ns);
29147 		return (ENXIO);
29148 	}
29149 	ipst->ips_ip_cgtp_filter_ops = NULL;
29150 	netstack_rele(ns);
29151 	return (0);
29152 }
29153 
29154 /*
29155  * Check whether there is a CGTP filter registration.
29156  * Returns non-zero if there is a registration, otherwise returns zero.
29157  * Note: returns zero if bad stackid.
29158  */
29159 int
29160 ip_cgtp_filter_is_registered(netstackid_t stackid)
29161 {
29162 	netstack_t *ns;
29163 	ip_stack_t *ipst;
29164 	int ret;
29165 
29166 	ns = netstack_find_by_stackid(stackid);
29167 	if (ns == NULL)
29168 		return (0);
29169 	ipst = ns->netstack_ip;
29170 	ASSERT(ipst != NULL);
29171 
29172 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29173 		ret = 1;
29174 	else
29175 		ret = 0;
29176 
29177 	netstack_rele(ns);
29178 	return (ret);
29179 }
29180 
29181 static int
29182 ip_squeue_switch(int val)
29183 {
29184 	int rval = SQ_FILL;
29185 
29186 	switch (val) {
29187 	case IP_SQUEUE_ENTER_NODRAIN:
29188 		rval = SQ_NODRAIN;
29189 		break;
29190 	case IP_SQUEUE_ENTER:
29191 		rval = SQ_PROCESS;
29192 		break;
29193 	default:
29194 		break;
29195 	}
29196 	return (rval);
29197 }
29198 
29199 /* ARGSUSED */
29200 static int
29201 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29202     caddr_t addr, cred_t *cr)
29203 {
29204 	int *v = (int *)addr;
29205 	long new_value;
29206 
29207 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29208 		return (EPERM);
29209 
29210 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29211 		return (EINVAL);
29212 
29213 	ip_squeue_flag = ip_squeue_switch(new_value);
29214 	*v = new_value;
29215 	return (0);
29216 }
29217 
29218 /*
29219  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29220  * ip_debug.
29221  */
29222 /* ARGSUSED */
29223 static int
29224 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29225     caddr_t addr, cred_t *cr)
29226 {
29227 	int *v = (int *)addr;
29228 	long new_value;
29229 
29230 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29231 		return (EPERM);
29232 
29233 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29234 		return (EINVAL);
29235 
29236 	*v = new_value;
29237 	return (0);
29238 }
29239 
29240 static void *
29241 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29242 {
29243 	kstat_t *ksp;
29244 
29245 	ip_stat_t template = {
29246 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29247 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29248 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29249 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29250 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29251 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29252 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29253 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29254 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29255 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29256 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29257 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29258 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29259 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29260 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29261 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29262 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29263 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29264 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29265 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29266 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29267 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29268 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29269 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29270 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29271 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29272 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29273 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29274 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29275 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29276 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29277 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29278 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29279 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29280 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29281 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29282 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29283 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29284 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29285 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29286 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29287 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29288 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29289 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29290 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29291 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29292 	};
29293 
29294 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29295 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29296 	    KSTAT_FLAG_VIRTUAL, stackid);
29297 
29298 	if (ksp == NULL)
29299 		return (NULL);
29300 
29301 	bcopy(&template, ip_statisticsp, sizeof (template));
29302 	ksp->ks_data = (void *)ip_statisticsp;
29303 	ksp->ks_private = (void *)(uintptr_t)stackid;
29304 
29305 	kstat_install(ksp);
29306 	return (ksp);
29307 }
29308 
29309 static void
29310 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29311 {
29312 	if (ksp != NULL) {
29313 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29314 		kstat_delete_netstack(ksp, stackid);
29315 	}
29316 }
29317 
29318 static void *
29319 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29320 {
29321 	kstat_t	*ksp;
29322 
29323 	ip_named_kstat_t template = {
29324 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29325 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29326 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29327 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29328 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29329 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29330 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29331 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29332 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29333 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29334 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29335 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29336 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29337 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29338 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29339 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29340 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29341 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29342 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29343 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29344 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29345 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29346 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29347 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29348 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29349 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29350 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29351 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29352 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29353 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29354 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29355 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29356 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29357 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29358 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29359 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29360 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29361 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29362 	};
29363 
29364 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29365 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29366 	if (ksp == NULL || ksp->ks_data == NULL)
29367 		return (NULL);
29368 
29369 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29370 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29371 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29372 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29373 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29374 
29375 	template.netToMediaEntrySize.value.i32 =
29376 	    sizeof (mib2_ipNetToMediaEntry_t);
29377 
29378 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29379 
29380 	bcopy(&template, ksp->ks_data, sizeof (template));
29381 	ksp->ks_update = ip_kstat_update;
29382 	ksp->ks_private = (void *)(uintptr_t)stackid;
29383 
29384 	kstat_install(ksp);
29385 	return (ksp);
29386 }
29387 
29388 static void
29389 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29390 {
29391 	if (ksp != NULL) {
29392 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29393 		kstat_delete_netstack(ksp, stackid);
29394 	}
29395 }
29396 
29397 static int
29398 ip_kstat_update(kstat_t *kp, int rw)
29399 {
29400 	ip_named_kstat_t *ipkp;
29401 	mib2_ipIfStatsEntry_t ipmib;
29402 	ill_walk_context_t ctx;
29403 	ill_t *ill;
29404 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29405 	netstack_t	*ns;
29406 	ip_stack_t	*ipst;
29407 
29408 	if (kp == NULL || kp->ks_data == NULL)
29409 		return (EIO);
29410 
29411 	if (rw == KSTAT_WRITE)
29412 		return (EACCES);
29413 
29414 	ns = netstack_find_by_stackid(stackid);
29415 	if (ns == NULL)
29416 		return (-1);
29417 	ipst = ns->netstack_ip;
29418 	if (ipst == NULL) {
29419 		netstack_rele(ns);
29420 		return (-1);
29421 	}
29422 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29423 
29424 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29425 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29426 	ill = ILL_START_WALK_V4(&ctx, ipst);
29427 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29428 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29429 	rw_exit(&ipst->ips_ill_g_lock);
29430 
29431 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29432 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29433 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29434 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29435 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29436 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29437 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29438 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29439 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29440 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29441 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29442 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29443 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29444 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29445 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29446 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29447 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29448 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29449 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29450 
29451 	ipkp->routingDiscards.value.ui32 =	0;
29452 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29453 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29454 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29455 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29456 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29457 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29458 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29459 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29460 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29461 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29462 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29463 
29464 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29465 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29466 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29467 
29468 	netstack_rele(ns);
29469 
29470 	return (0);
29471 }
29472 
29473 static void *
29474 icmp_kstat_init(netstackid_t stackid)
29475 {
29476 	kstat_t	*ksp;
29477 
29478 	icmp_named_kstat_t template = {
29479 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29480 		{ "inErrors",		KSTAT_DATA_UINT32 },
29481 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29482 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29483 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29484 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29485 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29486 		{ "inEchos",		KSTAT_DATA_UINT32 },
29487 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29488 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29489 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29490 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29491 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29492 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29493 		{ "outErrors",		KSTAT_DATA_UINT32 },
29494 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29495 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29496 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29497 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29498 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29499 		{ "outEchos",		KSTAT_DATA_UINT32 },
29500 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29501 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29502 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29503 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29504 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29505 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29506 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29507 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29508 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29509 		{ "outDrops",		KSTAT_DATA_UINT32 },
29510 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29511 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29512 	};
29513 
29514 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29515 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29516 	if (ksp == NULL || ksp->ks_data == NULL)
29517 		return (NULL);
29518 
29519 	bcopy(&template, ksp->ks_data, sizeof (template));
29520 
29521 	ksp->ks_update = icmp_kstat_update;
29522 	ksp->ks_private = (void *)(uintptr_t)stackid;
29523 
29524 	kstat_install(ksp);
29525 	return (ksp);
29526 }
29527 
29528 static void
29529 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29530 {
29531 	if (ksp != NULL) {
29532 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29533 		kstat_delete_netstack(ksp, stackid);
29534 	}
29535 }
29536 
29537 static int
29538 icmp_kstat_update(kstat_t *kp, int rw)
29539 {
29540 	icmp_named_kstat_t *icmpkp;
29541 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29542 	netstack_t	*ns;
29543 	ip_stack_t	*ipst;
29544 
29545 	if ((kp == NULL) || (kp->ks_data == NULL))
29546 		return (EIO);
29547 
29548 	if (rw == KSTAT_WRITE)
29549 		return (EACCES);
29550 
29551 	ns = netstack_find_by_stackid(stackid);
29552 	if (ns == NULL)
29553 		return (-1);
29554 	ipst = ns->netstack_ip;
29555 	if (ipst == NULL) {
29556 		netstack_rele(ns);
29557 		return (-1);
29558 	}
29559 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29560 
29561 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29562 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29563 	icmpkp->inDestUnreachs.value.ui32 =
29564 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29565 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29566 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29567 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29568 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29569 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29570 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29571 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29572 	icmpkp->inTimestampReps.value.ui32 =
29573 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29574 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29575 	icmpkp->inAddrMaskReps.value.ui32 =
29576 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29577 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29578 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29579 	icmpkp->outDestUnreachs.value.ui32 =
29580 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29581 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29582 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29583 	icmpkp->outSrcQuenchs.value.ui32 =
29584 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29585 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29586 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29587 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29588 	icmpkp->outTimestamps.value.ui32 =
29589 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29590 	icmpkp->outTimestampReps.value.ui32 =
29591 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29592 	icmpkp->outAddrMasks.value.ui32 =
29593 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29594 	icmpkp->outAddrMaskReps.value.ui32 =
29595 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29596 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29597 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29598 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29599 	icmpkp->outFragNeeded.value.ui32 =
29600 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29601 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29602 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29603 	icmpkp->inBadRedirects.value.ui32 =
29604 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29605 
29606 	netstack_rele(ns);
29607 	return (0);
29608 }
29609 
29610 /*
29611  * This is the fanout function for raw socket opened for SCTP.  Note
29612  * that it is called after SCTP checks that there is no socket which
29613  * wants a packet.  Then before SCTP handles this out of the blue packet,
29614  * this function is called to see if there is any raw socket for SCTP.
29615  * If there is and it is bound to the correct address, the packet will
29616  * be sent to that socket.  Note that only one raw socket can be bound to
29617  * a port.  This is assured in ipcl_sctp_hash_insert();
29618  */
29619 void
29620 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29621     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29622     zoneid_t zoneid)
29623 {
29624 	conn_t		*connp;
29625 	queue_t		*rq;
29626 	mblk_t		*first_mp;
29627 	boolean_t	secure;
29628 	ip6_t		*ip6h;
29629 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29630 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29631 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29632 	boolean_t	sctp_csum_err = B_FALSE;
29633 
29634 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29635 		sctp_csum_err = B_TRUE;
29636 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29637 	}
29638 
29639 	first_mp = mp;
29640 	if (mctl_present) {
29641 		mp = first_mp->b_cont;
29642 		secure = ipsec_in_is_secure(first_mp);
29643 		ASSERT(mp != NULL);
29644 	} else {
29645 		secure = B_FALSE;
29646 	}
29647 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29648 
29649 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29650 	if (connp == NULL) {
29651 		/*
29652 		 * Although raw sctp is not summed, OOB chunks must be.
29653 		 * Drop the packet here if the sctp checksum failed.
29654 		 */
29655 		if (sctp_csum_err) {
29656 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29657 			freemsg(first_mp);
29658 			return;
29659 		}
29660 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29661 		return;
29662 	}
29663 	rq = connp->conn_rq;
29664 	if (!canputnext(rq)) {
29665 		CONN_DEC_REF(connp);
29666 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29667 		freemsg(first_mp);
29668 		return;
29669 	}
29670 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29671 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29672 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29673 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29674 		if (first_mp == NULL) {
29675 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29676 			CONN_DEC_REF(connp);
29677 			return;
29678 		}
29679 	}
29680 	/*
29681 	 * We probably should not send M_CTL message up to
29682 	 * raw socket.
29683 	 */
29684 	if (mctl_present)
29685 		freeb(first_mp);
29686 
29687 	/* Initiate IPPF processing here if needed. */
29688 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29689 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29690 		ip_process(IPP_LOCAL_IN, &mp,
29691 		    recv_ill->ill_phyint->phyint_ifindex);
29692 		if (mp == NULL) {
29693 			CONN_DEC_REF(connp);
29694 			return;
29695 		}
29696 	}
29697 
29698 	if (connp->conn_recvif || connp->conn_recvslla ||
29699 	    ((connp->conn_ip_recvpktinfo ||
29700 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29701 	    (flags & IP_FF_IPINFO))) {
29702 		int in_flags = 0;
29703 
29704 		/*
29705 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29706 		 * IPF_RECVIF.
29707 		 */
29708 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29709 			in_flags = IPF_RECVIF;
29710 		}
29711 		if (connp->conn_recvslla) {
29712 			in_flags |= IPF_RECVSLLA;
29713 		}
29714 		if (isv4) {
29715 			mp = ip_add_info(mp, recv_ill, in_flags,
29716 			    IPCL_ZONEID(connp), ipst);
29717 		} else {
29718 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29719 			if (mp == NULL) {
29720 				BUMP_MIB(recv_ill->ill_ip_mib,
29721 				    ipIfStatsInDiscards);
29722 				CONN_DEC_REF(connp);
29723 				return;
29724 			}
29725 		}
29726 	}
29727 
29728 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29729 	/*
29730 	 * We are sending the IPSEC_IN message also up. Refer
29731 	 * to comments above this function.
29732 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29733 	 */
29734 	(connp->conn_recv)(connp, mp, NULL);
29735 	CONN_DEC_REF(connp);
29736 }
29737 
29738 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29739 {									\
29740 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29741 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29742 }
29743 /*
29744  * This function should be called only if all packet processing
29745  * including fragmentation is complete. Callers of this function
29746  * must set mp->b_prev to one of these values:
29747  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29748  * prior to handing over the mp as first argument to this function.
29749  *
29750  * If the ire passed by caller is incomplete, this function
29751  * queues the packet and if necessary, sends ARP request and bails.
29752  * If the ire passed is fully resolved, we simply prepend
29753  * the link-layer header to the packet, do ipsec hw acceleration
29754  * work if necessary, and send the packet out on the wire.
29755  *
29756  * NOTE: IPsec will only call this function with fully resolved
29757  * ires if hw acceleration is involved.
29758  * TODO list :
29759  * 	a Handle M_MULTIDATA so that
29760  *	  tcp_multisend->tcp_multisend_data can
29761  *	  call ip_xmit_v4 directly
29762  *	b Handle post-ARP work for fragments so that
29763  *	  ip_wput_frag can call this function.
29764  */
29765 ipxmit_state_t
29766 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29767     boolean_t flow_ctl_enabled, conn_t *connp)
29768 {
29769 	nce_t		*arpce;
29770 	ipha_t		*ipha;
29771 	queue_t		*q;
29772 	int		ill_index;
29773 	mblk_t		*nxt_mp, *first_mp;
29774 	boolean_t	xmit_drop = B_FALSE;
29775 	ip_proc_t	proc;
29776 	ill_t		*out_ill;
29777 	int		pkt_len;
29778 
29779 	arpce = ire->ire_nce;
29780 	ASSERT(arpce != NULL);
29781 
29782 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29783 
29784 	mutex_enter(&arpce->nce_lock);
29785 	switch (arpce->nce_state) {
29786 	case ND_REACHABLE:
29787 		/* If there are other queued packets, queue this packet */
29788 		if (arpce->nce_qd_mp != NULL) {
29789 			if (mp != NULL)
29790 				nce_queue_mp_common(arpce, mp, B_FALSE);
29791 			mp = arpce->nce_qd_mp;
29792 		}
29793 		arpce->nce_qd_mp = NULL;
29794 		mutex_exit(&arpce->nce_lock);
29795 
29796 		/*
29797 		 * Flush the queue.  In the common case, where the
29798 		 * ARP is already resolved,  it will go through the
29799 		 * while loop only once.
29800 		 */
29801 		while (mp != NULL) {
29802 
29803 			nxt_mp = mp->b_next;
29804 			mp->b_next = NULL;
29805 			ASSERT(mp->b_datap->db_type != M_CTL);
29806 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29807 			/*
29808 			 * This info is needed for IPQOS to do COS marking
29809 			 * in ip_wput_attach_llhdr->ip_process.
29810 			 */
29811 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29812 			mp->b_prev = NULL;
29813 
29814 			/* set up ill index for outbound qos processing */
29815 			out_ill = ire_to_ill(ire);
29816 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29817 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29818 			    ill_index, &ipha);
29819 			if (first_mp == NULL) {
29820 				xmit_drop = B_TRUE;
29821 				BUMP_MIB(out_ill->ill_ip_mib,
29822 				    ipIfStatsOutDiscards);
29823 				goto next_mp;
29824 			}
29825 
29826 			/* non-ipsec hw accel case */
29827 			if (io == NULL || !io->ipsec_out_accelerated) {
29828 				/* send it */
29829 				q = ire->ire_stq;
29830 				if (proc == IPP_FWD_OUT) {
29831 					UPDATE_IB_PKT_COUNT(ire);
29832 				} else {
29833 					UPDATE_OB_PKT_COUNT(ire);
29834 				}
29835 				ire->ire_last_used_time = lbolt;
29836 
29837 				if (flow_ctl_enabled || canputnext(q)) {
29838 					if (proc == IPP_FWD_OUT) {
29839 
29840 					BUMP_MIB(out_ill->ill_ip_mib,
29841 					    ipIfStatsHCOutForwDatagrams);
29842 
29843 					}
29844 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29845 					    pkt_len);
29846 
29847 					DTRACE_IP7(send, mblk_t *, first_mp,
29848 					    conn_t *, NULL, void_ip_t *, ipha,
29849 					    __dtrace_ipsr_ill_t *, out_ill,
29850 					    ipha_t *, ipha, ip6_t *, NULL, int,
29851 					    0);
29852 
29853 					ILL_SEND_TX(out_ill,
29854 					    ire, connp, first_mp, 0, connp);
29855 				} else {
29856 					BUMP_MIB(out_ill->ill_ip_mib,
29857 					    ipIfStatsOutDiscards);
29858 					xmit_drop = B_TRUE;
29859 					freemsg(first_mp);
29860 				}
29861 			} else {
29862 				/*
29863 				 * Safety Pup says: make sure this
29864 				 *  is going to the right interface!
29865 				 */
29866 				ill_t *ill1 =
29867 				    (ill_t *)ire->ire_stq->q_ptr;
29868 				int ifindex =
29869 				    ill1->ill_phyint->phyint_ifindex;
29870 				if (ifindex !=
29871 				    io->ipsec_out_capab_ill_index) {
29872 					xmit_drop = B_TRUE;
29873 					freemsg(mp);
29874 				} else {
29875 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29876 					    pkt_len);
29877 
29878 					DTRACE_IP7(send, mblk_t *, first_mp,
29879 					    conn_t *, NULL, void_ip_t *, ipha,
29880 					    __dtrace_ipsr_ill_t *, ill1,
29881 					    ipha_t *, ipha, ip6_t *, NULL,
29882 					    int, 0);
29883 
29884 					ipsec_hw_putnext(ire->ire_stq, mp);
29885 				}
29886 			}
29887 next_mp:
29888 			mp = nxt_mp;
29889 		} /* while (mp != NULL) */
29890 		if (xmit_drop)
29891 			return (SEND_FAILED);
29892 		else
29893 			return (SEND_PASSED);
29894 
29895 	case ND_INITIAL:
29896 	case ND_INCOMPLETE:
29897 
29898 		/*
29899 		 * While we do send off packets to dests that
29900 		 * use fully-resolved CGTP routes, we do not
29901 		 * handle unresolved CGTP routes.
29902 		 */
29903 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29904 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29905 
29906 		if (mp != NULL) {
29907 			/* queue the packet */
29908 			nce_queue_mp_common(arpce, mp, B_FALSE);
29909 		}
29910 
29911 		if (arpce->nce_state == ND_INCOMPLETE) {
29912 			mutex_exit(&arpce->nce_lock);
29913 			DTRACE_PROBE3(ip__xmit__incomplete,
29914 			    (ire_t *), ire, (mblk_t *), mp,
29915 			    (ipsec_out_t *), io);
29916 			return (LOOKUP_IN_PROGRESS);
29917 		}
29918 
29919 		arpce->nce_state = ND_INCOMPLETE;
29920 		mutex_exit(&arpce->nce_lock);
29921 
29922 		/*
29923 		 * Note that ire_add() (called from ire_forward())
29924 		 * holds a ref on the ire until ARP is completed.
29925 		 */
29926 		ire_arpresolve(ire);
29927 		return (LOOKUP_IN_PROGRESS);
29928 	default:
29929 		ASSERT(0);
29930 		mutex_exit(&arpce->nce_lock);
29931 		return (LLHDR_RESLV_FAILED);
29932 	}
29933 }
29934 
29935 #undef	UPDATE_IP_MIB_OB_COUNTERS
29936 
29937 /*
29938  * Return B_TRUE if the buffers differ in length or content.
29939  * This is used for comparing extension header buffers.
29940  * Note that an extension header would be declared different
29941  * even if all that changed was the next header value in that header i.e.
29942  * what really changed is the next extension header.
29943  */
29944 boolean_t
29945 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29946     uint_t blen)
29947 {
29948 	if (!b_valid)
29949 		blen = 0;
29950 
29951 	if (alen != blen)
29952 		return (B_TRUE);
29953 	if (alen == 0)
29954 		return (B_FALSE);	/* Both zero length */
29955 	return (bcmp(abuf, bbuf, alen));
29956 }
29957 
29958 /*
29959  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29960  * Return B_FALSE if memory allocation fails - don't change any state!
29961  */
29962 boolean_t
29963 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29964     const void *src, uint_t srclen)
29965 {
29966 	void *dst;
29967 
29968 	if (!src_valid)
29969 		srclen = 0;
29970 
29971 	ASSERT(*dstlenp == 0);
29972 	if (src != NULL && srclen != 0) {
29973 		dst = mi_alloc(srclen, BPRI_MED);
29974 		if (dst == NULL)
29975 			return (B_FALSE);
29976 	} else {
29977 		dst = NULL;
29978 	}
29979 	if (*dstp != NULL)
29980 		mi_free(*dstp);
29981 	*dstp = dst;
29982 	*dstlenp = dst == NULL ? 0 : srclen;
29983 	return (B_TRUE);
29984 }
29985 
29986 /*
29987  * Replace what is in *dst, *dstlen with the source.
29988  * Assumes ip_allocbuf has already been called.
29989  */
29990 void
29991 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29992     const void *src, uint_t srclen)
29993 {
29994 	if (!src_valid)
29995 		srclen = 0;
29996 
29997 	ASSERT(*dstlenp == srclen);
29998 	if (src != NULL && srclen != 0)
29999 		bcopy(src, *dstp, srclen);
30000 }
30001 
30002 /*
30003  * Free the storage pointed to by the members of an ip6_pkt_t.
30004  */
30005 void
30006 ip6_pkt_free(ip6_pkt_t *ipp)
30007 {
30008 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30009 
30010 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30011 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30012 		ipp->ipp_hopopts = NULL;
30013 		ipp->ipp_hopoptslen = 0;
30014 	}
30015 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30016 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30017 		ipp->ipp_rtdstopts = NULL;
30018 		ipp->ipp_rtdstoptslen = 0;
30019 	}
30020 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30021 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30022 		ipp->ipp_dstopts = NULL;
30023 		ipp->ipp_dstoptslen = 0;
30024 	}
30025 	if (ipp->ipp_fields & IPPF_RTHDR) {
30026 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30027 		ipp->ipp_rthdr = NULL;
30028 		ipp->ipp_rthdrlen = 0;
30029 	}
30030 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30031 	    IPPF_RTHDR);
30032 }
30033 
30034 zoneid_t
30035 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
30036     zoneid_t lookup_zoneid)
30037 {
30038 	ire_t		*ire;
30039 	int		ire_flags = MATCH_IRE_TYPE;
30040 	zoneid_t	zoneid = ALL_ZONES;
30041 
30042 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30043 		return (ALL_ZONES);
30044 
30045 	if (lookup_zoneid != ALL_ZONES)
30046 		ire_flags |= MATCH_IRE_ZONEONLY;
30047 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
30048 	    lookup_zoneid, NULL, ire_flags, ipst);
30049 	if (ire != NULL) {
30050 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30051 		ire_refrele(ire);
30052 	}
30053 	return (zoneid);
30054 }
30055 
30056 zoneid_t
30057 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
30058     ip_stack_t *ipst, zoneid_t lookup_zoneid)
30059 {
30060 	ire_t		*ire;
30061 	int		ire_flags = MATCH_IRE_TYPE;
30062 	zoneid_t	zoneid = ALL_ZONES;
30063 	ipif_t		*ipif_arg = NULL;
30064 
30065 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30066 		return (ALL_ZONES);
30067 
30068 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30069 		ire_flags |= MATCH_IRE_ILL;
30070 		ipif_arg = ill->ill_ipif;
30071 	}
30072 	if (lookup_zoneid != ALL_ZONES)
30073 		ire_flags |= MATCH_IRE_ZONEONLY;
30074 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30075 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30076 	if (ire != NULL) {
30077 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30078 		ire_refrele(ire);
30079 	}
30080 	return (zoneid);
30081 }
30082 
30083 /*
30084  * IP obserability hook support functions.
30085  */
30086 
30087 static void
30088 ipobs_init(ip_stack_t *ipst)
30089 {
30090 	ipst->ips_ipobs_enabled = B_FALSE;
30091 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30092 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30093 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30094 	ipst->ips_ipobs_cb_nwalkers = 0;
30095 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30096 }
30097 
30098 static void
30099 ipobs_fini(ip_stack_t *ipst)
30100 {
30101 	ipobs_cb_t *cb;
30102 
30103 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30104 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30105 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30106 
30107 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30108 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30109 		kmem_free(cb, sizeof (*cb));
30110 	}
30111 	list_destroy(&ipst->ips_ipobs_cb_list);
30112 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30113 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30114 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30115 }
30116 
30117 void
30118 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30119     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30120 {
30121 	mblk_t *mp2;
30122 	ipobs_cb_t *ipobs_cb;
30123 	ipobs_hook_data_t *ihd;
30124 	uint64_t grifindex = 0;
30125 
30126 	ASSERT(DB_TYPE(mp) == M_DATA);
30127 
30128 	if (IS_UNDER_IPMP(ill))
30129 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
30130 
30131 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30132 	ipst->ips_ipobs_cb_nwalkers++;
30133 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30134 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30135 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30136 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
30137 		if (mp2 != NULL) {
30138 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
30139 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30140 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30141 				freemsg(mp2);
30142 				continue;
30143 			}
30144 			ihd->ihd_mp->b_rptr += hlen;
30145 			ihd->ihd_htype = htype;
30146 			ihd->ihd_ipver = ipver;
30147 			ihd->ihd_zsrc = zsrc;
30148 			ihd->ihd_zdst = zdst;
30149 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30150 			ihd->ihd_grifindex = grifindex;
30151 			ihd->ihd_stack = ipst->ips_netstack;
30152 			mp2->b_wptr += sizeof (*ihd);
30153 			ipobs_cb->ipobs_cbfunc(mp2);
30154 		}
30155 	}
30156 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30157 	ipst->ips_ipobs_cb_nwalkers--;
30158 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30159 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30160 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30161 }
30162 
30163 void
30164 ipobs_register_hook(netstack_t *ns, pfv_t func)
30165 {
30166 	ipobs_cb_t   *cb;
30167 	ip_stack_t *ipst = ns->netstack_ip;
30168 
30169 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30170 
30171 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30172 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30173 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30174 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30175 
30176 	cb->ipobs_cbfunc = func;
30177 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30178 	ipst->ips_ipobs_enabled = B_TRUE;
30179 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30180 }
30181 
30182 void
30183 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30184 {
30185 	ipobs_cb_t	*curcb;
30186 	ip_stack_t	*ipst = ns->netstack_ip;
30187 
30188 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30189 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30190 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30191 
30192 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30193 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30194 		if (func == curcb->ipobs_cbfunc) {
30195 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30196 			kmem_free(curcb, sizeof (*curcb));
30197 			break;
30198 		}
30199 	}
30200 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30201 		ipst->ips_ipobs_enabled = B_FALSE;
30202 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30203 }
30204