xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision b1593d50e783f7d66722dde093752b74ffa95176)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 #include <sys/squeue_impl.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	uint_t		ird_flags;	/* see below */
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 #define	IRD_REPORT_TESTHIDDEN	0x01	/* include IRE_MARK_TESTHIDDEN routes */
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, certain multicast operations, most set ioctls,
236  * igmp/mld timers etc.
237  *
238  * Plumbing is a long sequence of operations involving message
239  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
240  * involved in plumbing operations. A natural model is to serialize these
241  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
242  * parallel without any interference. But various set ioctls on hme0 are best
243  * serialized, along with multicast join/leave operations, igmp/mld timer
244  * operations, and processing of DLPI control messages received from drivers
245  * on a per phyint basis.  This serialization is provided by the ipsq_t and
246  * primitives operating on this. Details can be found in ip_if.c above the
247  * core primitives operating on ipsq_t.
248  *
249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
251  * In addition ipif's and ill's referenced by the ire are also indirectly
252  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
253  * the ipif's address or netmask change as long as an ipif is refheld
254  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
255  * address of an ipif has to go through the ipsq_t. This ensures that only
256  * 1 such exclusive operation proceeds at any time on the ipif. It then
257  * deletes all ires associated with this ipif, and waits for all refcnts
258  * associated with this ipif to come down to zero. The address is changed
259  * only after the ipif has been quiesced. Then the ipif is brought up again.
260  * More details are described above the comment in ip_sioctl_flags.
261  *
262  * Packet processing is based mostly on IREs and are fully multi-threaded
263  * using standard Solaris MT techniques.
264  *
265  * There are explicit locks in IP to handle:
266  * - The ip_g_head list maintained by mi_open_link() and friends.
267  *
268  * - The reassembly data structures (one lock per hash bucket)
269  *
270  * - conn_lock is meant to protect conn_t fields. The fields actually
271  *   protected by conn_lock are documented in the conn_t definition.
272  *
273  * - ire_lock to protect some of the fields of the ire, IRE tables
274  *   (one lock per hash bucket). Refer to ip_ire.c for details.
275  *
276  * - ndp_g_lock and nce_lock for protecting NCEs.
277  *
278  * - ill_lock protects fields of the ill and ipif. Details in ip.h
279  *
280  * - ill_g_lock: This is a global reader/writer lock. Protects the following
281  *	* The AVL tree based global multi list of all ills.
282  *	* The linked list of all ipifs of an ill
283  *	* The <ipsq-xop> mapping
284  *	* <ill-phyint> association
285  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
286  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
287  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
288  *   writer for the actual duration of the insertion/deletion/change.
289  *
290  * - ill_lock:  This is a per ill mutex.
291  *   It protects some members of the ill_t struct; see ip.h for details.
292  *   It also protects the <ill-phyint> assoc.
293  *   It also protects the list of ipifs hanging off the ill.
294  *
295  * - ipsq_lock: This is a per ipsq_t mutex lock.
296  *   This protects some members of the ipsq_t struct; see ip.h for details.
297  *   It also protects the <ipsq-ipxop> mapping
298  *
299  * - ipx_lock: This is a per ipxop_t mutex lock.
300  *   This protects some members of the ipxop_t struct; see ip.h for details.
301  *
302  * - phyint_lock: This is a per phyint mutex lock. Protects just the
303  *   phyint_flags
304  *
305  * - ip_g_nd_lock: This is a global reader/writer lock.
306  *   Any call to nd_load to load a new parameter to the ND table must hold the
307  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
308  *   as reader.
309  *
310  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
311  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
312  *   uniqueness check also done atomically.
313  *
314  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
315  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
316  *   as a writer when adding or deleting elements from these lists, and
317  *   as a reader when walking these lists to send a SADB update to the
318  *   IPsec capable ills.
319  *
320  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
321  *   group list linked by ill_usesrc_grp_next. It also protects the
322  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
323  *   group is being added or deleted.  This lock is taken as a reader when
324  *   walking the list/group(eg: to get the number of members in a usesrc group).
325  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
326  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
327  *   example, it is not necessary to take this lock in the initial portion
328  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
329  *   operations are executed exclusively and that ensures that the "usesrc
330  *   group state" cannot change. The "usesrc group state" change can happen
331  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
332  *
333  * Changing <ill-phyint>, <ipsq-xop> assocications:
334  *
335  * To change the <ill-phyint> association, the ill_g_lock must be held
336  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
337  * must be held.
338  *
339  * To change the <ipsq-xop> association, the ill_g_lock must be held as
340  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
341  * This is only done when ills are added or removed from IPMP groups.
342  *
343  * To add or delete an ipif from the list of ipifs hanging off the ill,
344  * ill_g_lock (writer) and ill_lock must be held and the thread must be
345  * a writer on the associated ipsq.
346  *
347  * To add or delete an ill to the system, the ill_g_lock must be held as
348  * writer and the thread must be a writer on the associated ipsq.
349  *
350  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
351  * must be a writer on the associated ipsq.
352  *
353  * Lock hierarchy
354  *
355  * Some lock hierarchy scenarios are listed below.
356  *
357  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
358  * ill_g_lock -> ill_lock(s) -> phyint_lock
359  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
360  * ill_g_lock -> ip_addr_avail_lock
361  * conn_lock -> irb_lock -> ill_lock -> ire_lock
362  * ill_g_lock -> ip_g_nd_lock
363  *
364  * When more than 1 ill lock is needed to be held, all ill lock addresses
365  * are sorted on address and locked starting from highest addressed lock
366  * downward.
367  *
368  * IPsec scenarios
369  *
370  * ipsa_lock -> ill_g_lock -> ill_lock
371  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
372  * ipsec_capab_ills_lock -> ipsa_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IPsec notes :
417  *
418  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
419  * in front of the actual packet. For outbound datagrams, the M_CTL
420  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
421  * information used by the IPsec code for applying the right level of
422  * protection. The information initialized by IP in the ipsec_out_t
423  * is determined by the per-socket policy or global policy in the system.
424  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
425  * ipsec_info.h) which starts out with nothing in it. It gets filled
426  * with the right information if it goes through the AH/ESP code, which
427  * happens if the incoming packet is secure. The information initialized
428  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
429  * the policy requirements needed by per-socket policy or global policy
430  * is met or not.
431  *
432  * If there is both per-socket policy (set using setsockopt) and there
433  * is also global policy match for the 5 tuples of the socket,
434  * ipsec_override_policy() makes the decision of which one to use.
435  *
436  * For fully connected sockets i.e dst, src [addr, port] is known,
437  * conn_policy_cached is set indicating that policy has been cached.
438  * conn_in_enforce_policy may or may not be set depending on whether
439  * there is a global policy match or per-socket policy match.
440  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
441  * Once the right policy is set on the conn_t, policy cannot change for
442  * this socket. This makes life simpler for TCP (UDP ?) where
443  * re-transmissions go out with the same policy. For symmetry, policy
444  * is cached for fully connected UDP sockets also. Thus if policy is cached,
445  * it also implies that policy is latched i.e policy cannot change
446  * on these sockets. As we have the right policy on the conn, we don't
447  * have to lookup global policy for every outbound and inbound datagram
448  * and thus serving as an optimization. Note that a global policy change
449  * does not affect fully connected sockets if they have policy. If fully
450  * connected sockets did not have any policy associated with it, global
451  * policy change may affect them.
452  *
453  * IP Flow control notes:
454  * ---------------------
455  * Non-TCP streams are flow controlled by IP. The way this is accomplished
456  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
457  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
458  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
459  * functions.
460  *
461  * Per Tx ring udp flow control:
462  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
463  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
464  *
465  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
466  * To achieve best performance, outgoing traffic need to be fanned out among
467  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
468  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
469  * the address of connp as fanout hint to mac_tx(). Under flow controlled
470  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
471  * cookie points to a specific Tx ring that is blocked. The cookie is used to
472  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
473  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
474  * connp's. The drain list is not a single list but a configurable number of
475  * lists.
476  *
477  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
478  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
479  * which is equal to 128. This array in turn contains a pointer to idl_t[],
480  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
481  * list will point to the list of connp's that are flow controlled.
482  *
483  *                      ---------------   -------   -------   -------
484  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   |  ---------------   -------   -------   -------
487  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
488  * ----------------  |  ---------------   -------   -------   -------
489  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
490  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
491  *                   |  ---------------   -------   -------   -------
492  *                   .        .              .         .         .
493  *                   |  ---------------   -------   -------   -------
494  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
495  *                      ---------------   -------   -------   -------
496  *                      ---------------   -------   -------   -------
497  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
498  *                   |  ---------------   -------   -------   -------
499  *                   |  ---------------   -------   -------   -------
500  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
501  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
502  * ----------------  |        .              .         .         .
503  *                   |  ---------------   -------   -------   -------
504  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
505  *                      ---------------   -------   -------   -------
506  *     .....
507  * ----------------
508  * |idl_tx_list[n]|-> ...
509  * ----------------
510  *
511  * When mac_tx() returns a cookie, the cookie is used to hash into a
512  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
513  * called passing idl_tx_list. The connp gets inserted in a drain list
514  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
515  * the sockets (non stream based) and sets QFULL condition for conn_wq.
516  * connp->conn_direct_blocked will be set to indicate the blocked
517  * condition.
518  *
519  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
520  * A cookie is passed in the call to ill_flow_enable() that identifies the
521  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
522  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
523  * and goes through each of the drain list (q)enabling the conn_wq of the
524  * first conn in each of the drain list. This causes ip_wsrv to run for the
525  * conn. ip_wsrv drains the queued messages, and removes the conn from the
526  * drain list, if all messages were drained. It also qenables the next conn
527  * in the drain list to continue the drain process.
528  *
529  * In reality the drain list is not a single list, but a configurable number
530  * of lists. conn_drain_walk() in the IP module, qenables the first conn in
531  * each list. If the ip_wsrv of the next qenabled conn does not run, because
532  * the stream closes, ip_close takes responsibility to qenable the next conn
533  * in the drain list. conn_drain_insert and conn_drain_tail are the only
534  * functions that manipulate this drain list. conn_drain_insert is called in
535  * ip_wput context itself (as opposed to from ip_wsrv context for STREAMS
536  * case -- see below). The synchronization between drain insertion and flow
537  * control wakeup is handled by using idl_txl->txl_lock.
538  *
539  * Flow control using STREAMS:
540  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
541  * is used. On the send side, if the packet cannot be sent down to the
542  * driver by IP, because of a canput failure, IP does a putq on the conn_wq.
543  * This will cause ip_wsrv to run on the conn_wq. ip_wsrv in turn, inserts
544  * the conn in a list of conn's that need to be drained when the flow
545  * control condition subsides. The blocked connps are put in first member
546  * of ips_idl_tx_list[] array. Ultimately STREAMS backenables the ip_wsrv
547  * on the IP module. It calls conn_walk_drain() passing ips_idl_tx_list[0].
548  * ips_idl_tx_list[0] contains the drain lists of blocked conns. The
549  * conn_wq of the first conn in the drain lists is (q)enabled to run.
550  * ip_wsrv on this conn drains the queued messages, and removes the conn
551  * from the drain list, if all messages were drained. It also qenables the
552  * next conn in the drain list to continue the drain process.
553  *
554  * If the ip_wsrv of the next qenabled conn does not run, because the
555  * stream closes, ip_close takes responsibility to qenable the next conn in
556  * the drain list. The directly called ip_wput path always does a putq, if
557  * it cannot putnext. Thus synchronization problems are handled between
558  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
559  * functions that manipulate this drain list. Furthermore conn_drain_insert
560  * is called only from ip_wsrv for the STREAMS case, and there can be only 1
561  * instance of ip_wsrv running on a queue at any time. conn_drain_tail can
562  * be simultaneously called from both ip_wsrv and ip_close.
563  *
564  * IPQOS notes:
565  *
566  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
567  * and IPQoS modules. IPPF includes hooks in IP at different control points
568  * (callout positions) which direct packets to IPQoS modules for policy
569  * processing. Policies, if present, are global.
570  *
571  * The callout positions are located in the following paths:
572  *		o local_in (packets destined for this host)
573  *		o local_out (packets orginating from this host )
574  *		o fwd_in  (packets forwarded by this m/c - inbound)
575  *		o fwd_out (packets forwarded by this m/c - outbound)
576  * Hooks at these callout points can be enabled/disabled using the ndd variable
577  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
578  * By default all the callout positions are enabled.
579  *
580  * Outbound (local_out)
581  * Hooks are placed in ip_wput_ire and ipsec_out_process.
582  *
583  * Inbound (local_in)
584  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
585  * TCP and UDP fanout routines.
586  *
587  * Forwarding (in and out)
588  * Hooks are placed in ip_rput_forward.
589  *
590  * IP Policy Framework processing (IPPF processing)
591  * Policy processing for a packet is initiated by ip_process, which ascertains
592  * that the classifier (ipgpc) is loaded and configured, failing which the
593  * packet resumes normal processing in IP. If the clasifier is present, the
594  * packet is acted upon by one or more IPQoS modules (action instances), per
595  * filters configured in ipgpc and resumes normal IP processing thereafter.
596  * An action instance can drop a packet in course of its processing.
597  *
598  * A boolean variable, ip_policy, is used in all the fanout routines that can
599  * invoke ip_process for a packet. This variable indicates if the packet should
600  * to be sent for policy processing. The variable is set to B_TRUE by default,
601  * i.e. when the routines are invoked in the normal ip procesing path for a
602  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
603  * ip_policy is set to B_FALSE for all the routines called in these two
604  * functions because, in the former case,  we don't process loopback traffic
605  * currently while in the latter, the packets have already been processed in
606  * icmp_inbound.
607  *
608  * Zones notes:
609  *
610  * The partitioning rules for networking are as follows:
611  * 1) Packets coming from a zone must have a source address belonging to that
612  * zone.
613  * 2) Packets coming from a zone can only be sent on a physical interface on
614  * which the zone has an IP address.
615  * 3) Between two zones on the same machine, packet delivery is only allowed if
616  * there's a matching route for the destination and zone in the forwarding
617  * table.
618  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
619  * different zones can bind to the same port with the wildcard address
620  * (INADDR_ANY).
621  *
622  * The granularity of interface partitioning is at the logical interface level.
623  * Therefore, every zone has its own IP addresses, and incoming packets can be
624  * attributed to a zone unambiguously. A logical interface is placed into a zone
625  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
626  * structure. Rule (1) is implemented by modifying the source address selection
627  * algorithm so that the list of eligible addresses is filtered based on the
628  * sending process zone.
629  *
630  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
631  * across all zones, depending on their type. Here is the break-up:
632  *
633  * IRE type				Shared/exclusive
634  * --------				----------------
635  * IRE_BROADCAST			Exclusive
636  * IRE_DEFAULT (default routes)		Shared (*)
637  * IRE_LOCAL				Exclusive (x)
638  * IRE_LOOPBACK				Exclusive
639  * IRE_PREFIX (net routes)		Shared (*)
640  * IRE_CACHE				Exclusive
641  * IRE_IF_NORESOLVER (interface routes)	Exclusive
642  * IRE_IF_RESOLVER (interface routes)	Exclusive
643  * IRE_HOST (host routes)		Shared (*)
644  *
645  * (*) A zone can only use a default or off-subnet route if the gateway is
646  * directly reachable from the zone, that is, if the gateway's address matches
647  * one of the zone's logical interfaces.
648  *
649  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
650  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
651  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
652  * address of the zone itself (the destination). Since IRE_LOCAL is used
653  * for communication between zones, ip_wput_ire has special logic to set
654  * the right source address when sending using an IRE_LOCAL.
655  *
656  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
657  * ire_cache_lookup restricts loopback using an IRE_LOCAL
658  * between zone to the case when L2 would have conceptually looped the packet
659  * back, i.e. the loopback which is required since neither Ethernet drivers
660  * nor Ethernet hardware loops them back. This is the case when the normal
661  * routes (ignoring IREs with different zoneids) would send out the packet on
662  * the same ill as the ill with which is IRE_LOCAL is associated.
663  *
664  * Multiple zones can share a common broadcast address; typically all zones
665  * share the 255.255.255.255 address. Incoming as well as locally originated
666  * broadcast packets must be dispatched to all the zones on the broadcast
667  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
668  * since some zones may not be on the 10.16.72/24 network. To handle this, each
669  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
670  * sent to every zone that has an IRE_BROADCAST entry for the destination
671  * address on the input ill, see conn_wantpacket().
672  *
673  * Applications in different zones can join the same multicast group address.
674  * For IPv4, group memberships are per-logical interface, so they're already
675  * inherently part of a zone. For IPv6, group memberships are per-physical
676  * interface, so we distinguish IPv6 group memberships based on group address,
677  * interface and zoneid. In both cases, received multicast packets are sent to
678  * every zone for which a group membership entry exists. On IPv6 we need to
679  * check that the target zone still has an address on the receiving physical
680  * interface; it could have been removed since the application issued the
681  * IPV6_JOIN_GROUP.
682  */
683 
684 /*
685  * Squeue Fanout flags:
686  *	0: No fanout.
687  *	1: Fanout across all squeues
688  */
689 boolean_t	ip_squeue_fanout = 0;
690 
691 /*
692  * Maximum dups allowed per packet.
693  */
694 uint_t ip_max_frag_dups = 10;
695 
696 #define	IS_SIMPLE_IPH(ipha)						\
697 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
698 
699 /* RFC 1122 Conformance */
700 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
701 
702 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
703 
704 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
705 
706 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
707 		    cred_t *credp, boolean_t isv6);
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
709 		    ipha_t **);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
712 		    ip_stack_t *);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int, ip_stack_t *);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
723 		    ip_stack_t *);
724 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
725 		    zoneid_t zoneid, ip_stack_t *);
726 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
727 static void	icmp_redirect(ill_t *, mblk_t *);
728 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
729 		    ip_stack_t *);
730 
731 static void	ip_arp_news(queue_t *, mblk_t *);
732 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
733 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
734 char		*ip_dot_addr(ipaddr_t, char *);
735 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
736 int		ip_close(queue_t *, int);
737 static char	*ip_dot_saddr(uchar_t *, char *);
738 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, ill_t *, zoneid_t);
740 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
741 		    boolean_t, boolean_t, zoneid_t);
742 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
743 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
744 static void	ip_lrput(queue_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
747 		    ip_stack_t *);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
755     ipndp_t *, size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
762     ip_stack_t *);
763 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
764 			    ire_t *, ip_stack_t *);
765 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
766 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
767 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
768     ip_stack_t *);
769 static boolean_t ip_rput_fragment(ill_t *, ill_t *, mblk_t **, ipha_t *,
770     uint32_t *, uint16_t *);
771 int		ip_snmp_get(queue_t *, mblk_t *, int);
772 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
773 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
775 		    ip_stack_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
777 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
778 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
779 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
780 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
781 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
782 		    ip_stack_t *ipst);
783 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
784 		    ip_stack_t *ipst);
785 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
786 		    ip_stack_t *ipst);
787 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
788 		    ip_stack_t *ipst);
789 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
790 		    ip_stack_t *ipst);
791 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
792 		    ip_stack_t *ipst);
793 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
794 		    ip_stack_t *ipst);
795 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
796 		    ip_stack_t *ipst);
797 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
798 		    ip_stack_t *ipst);
799 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
800 		    ip_stack_t *ipst);
801 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
802 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
803 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
804 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
805 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
806 static boolean_t	ip_source_route_included(ipha_t *);
807 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
808 
809 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
810 		    zoneid_t, ip_stack_t *, conn_t *);
811 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *,
812 		    mblk_t *);
813 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
814 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
815 		    zoneid_t, ip_stack_t *);
816 
817 static void	conn_drain_init(ip_stack_t *);
818 static void	conn_drain_fini(ip_stack_t *);
819 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
820 
821 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
822 static void	conn_setqfull(conn_t *);
823 static void	conn_clrqfull(conn_t *);
824 
825 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
826 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
827 static void	ip_stack_fini(netstackid_t stackid, void *arg);
828 
829 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
830     zoneid_t);
831 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
832     void *dummy_arg);
833 
834 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
835 
836 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
837     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
838     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
839 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
840 
841 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
842 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
843     caddr_t, cred_t *);
844 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
845     cred_t *, boolean_t);
846 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
847     caddr_t cp, cred_t *cr);
848 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
849     cred_t *);
850 static int	ip_squeue_switch(int);
851 
852 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
853 static void	ip_kstat_fini(netstackid_t, kstat_t *);
854 static int	ip_kstat_update(kstat_t *kp, int rw);
855 static void	*icmp_kstat_init(netstackid_t);
856 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
857 static int	icmp_kstat_update(kstat_t *kp, int rw);
858 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
859 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
860 
861 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
862     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
863 
864 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
865     ipha_t *, ill_t *, boolean_t, boolean_t);
866 
867 static void ipobs_init(ip_stack_t *);
868 static void ipobs_fini(ip_stack_t *);
869 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
870 
871 /* How long, in seconds, we allow frags to hang around. */
872 #define	IP_FRAG_TIMEOUT	15
873 
874 /*
875  * Threshold which determines whether MDT should be used when
876  * generating IP fragments; payload size must be greater than
877  * this threshold for MDT to take place.
878  */
879 #define	IP_WPUT_FRAG_MDT_MIN	32768
880 
881 /* Setable in /etc/system only */
882 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
883 
884 static long ip_rput_pullups;
885 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
886 
887 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
888 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
889 
890 int	ip_debug;
891 
892 #ifdef DEBUG
893 uint32_t ipsechw_debug = 0;
894 #endif
895 
896 /*
897  * Multirouting/CGTP stuff
898  */
899 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
900 
901 /*
902  * XXX following really should only be in a header. Would need more
903  * header and .c clean up first.
904  */
905 extern optdb_obj_t	ip_opt_obj;
906 
907 ulong_t ip_squeue_enter_unbound = 0;
908 
909 /*
910  * Named Dispatch Parameter Table.
911  * All of these are alterable, within the min/max values given, at run time.
912  */
913 static ipparam_t	lcl_param_arr[] = {
914 	/* min	max	value	name */
915 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
916 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
917 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
918 	{  0,	1,	0,	"ip_respond_to_timestamp"},
919 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
920 	{  0,	1,	1,	"ip_send_redirects"},
921 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
922 	{  0,	10,	0,	"ip_mrtdebug"},
923 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
924 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
925 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
926 	{  1,	255,	255,	"ip_def_ttl" },
927 	{  0,	1,	0,	"ip_forward_src_routed"},
928 	{  0,	256,	32,	"ip_wroff_extra" },
929 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
930 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
931 	{  0,	1,	1,	"ip_path_mtu_discovery" },
932 	{  0,	240,	30,	"ip_ignore_delete_time" },
933 	{  0,	1,	0,	"ip_ignore_redirect" },
934 	{  0,	1,	1,	"ip_output_queue" },
935 	{  1,	254,	1,	"ip_broadcast_ttl" },
936 	{  0,	99999,	100,	"ip_icmp_err_interval" },
937 	{  1,	99999,	10,	"ip_icmp_err_burst" },
938 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
939 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
940 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
941 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
942 	{  0,	1,	1,	"icmp_accept_clear_messages" },
943 	{  0,	1,	1,	"igmp_accept_clear_messages" },
944 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
945 				"ip_ndp_delay_first_probe_time"},
946 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
947 				"ip_ndp_max_unicast_solicit"},
948 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
949 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
950 	{  0,	1,	0,	"ip6_forward_src_routed"},
951 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
952 	{  0,	1,	1,	"ip6_send_redirects"},
953 	{  0,	1,	0,	"ip6_ignore_redirect" },
954 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
955 
956 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
957 
958 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
959 
960 	{  0,	1,	1,	"pim_accept_clear_messages" },
961 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
962 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
963 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
964 	{  0,	15,	0,	"ip_policy_mask" },
965 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
966 	{  0,	255,	1,	"ip_multirt_ttl" },
967 	{  0,	1,	1,	"ip_multidata_outbound" },
968 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
969 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
970 	{  0,	1000,	1,	"ip_max_temp_defend" },
971 	{  0,	1000,	3,	"ip_max_defend" },
972 	{  0,	999999,	30,	"ip_defend_interval" },
973 	{  0,	3600000, 300000, "ip_dup_recovery" },
974 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
975 	{  0,	1,	1,	"ip_lso_outbound" },
976 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
977 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
978 	{ 68,	65535,	576,	"ip_pmtu_min" },
979 #ifdef DEBUG
980 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
981 #else
982 	{  0,	0,	0,	"" },
983 #endif
984 };
985 
986 /*
987  * Extended NDP table
988  * The addresses for the first two are filled in to be ips_ip_g_forward
989  * and ips_ipv6_forward at init time.
990  */
991 static ipndp_t	lcl_ndp_arr[] = {
992 	/* getf			setf		data			name */
993 #define	IPNDP_IP_FORWARDING_OFFSET	0
994 	{  ip_param_generic_get,	ip_forward_set,	NULL,
995 	    "ip_forwarding" },
996 #define	IPNDP_IP6_FORWARDING_OFFSET	1
997 	{  ip_param_generic_get,	ip_forward_set,	NULL,
998 	    "ip6_forwarding" },
999 	{ ip_param_generic_get, ip_input_proc_set,
1000 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1001 	{ ip_param_generic_get, ip_int_set,
1002 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1003 #define	IPNDP_CGTP_FILTER_OFFSET	4
1004 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1005 	    "ip_cgtp_filter" },
1006 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1007 	    "ip_debug" },
1008 };
1009 
1010 /*
1011  * Table of IP ioctls encoding the various properties of the ioctl and
1012  * indexed based on the last byte of the ioctl command. Occasionally there
1013  * is a clash, and there is more than 1 ioctl with the same last byte.
1014  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1015  * ioctls are encoded in the misc table. An entry in the ndx table is
1016  * retrieved by indexing on the last byte of the ioctl command and comparing
1017  * the ioctl command with the value in the ndx table. In the event of a
1018  * mismatch the misc table is then searched sequentially for the desired
1019  * ioctl command.
1020  *
1021  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1022  */
1023 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1024 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 
1035 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1036 			MISC_CMD, ip_siocaddrt, NULL },
1037 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1038 			MISC_CMD, ip_siocdelrt, NULL },
1039 
1040 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1041 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1042 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1043 			IF_CMD, ip_sioctl_get_addr, NULL },
1044 
1045 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1046 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1047 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1048 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1049 
1050 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1051 			IPI_PRIV | IPI_WR,
1052 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1053 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1054 			IPI_MODOK | IPI_GET_CMD,
1055 			IF_CMD, ip_sioctl_get_flags, NULL },
1056 
1057 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 
1060 	/* copyin size cannot be coded for SIOCGIFCONF */
1061 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1062 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1063 
1064 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1065 			IF_CMD, ip_sioctl_mtu, NULL },
1066 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1067 			IF_CMD, ip_sioctl_get_mtu, NULL },
1068 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1069 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1070 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1071 			IF_CMD, ip_sioctl_brdaddr, NULL },
1072 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1073 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1074 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1075 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1076 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1077 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1078 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1079 			IF_CMD, ip_sioctl_metric, NULL },
1080 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 
1082 	/* See 166-168 below for extended SIOC*XARP ioctls */
1083 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1084 			ARP_CMD, ip_sioctl_arp, NULL },
1085 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1086 			ARP_CMD, ip_sioctl_arp, NULL },
1087 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1088 			ARP_CMD, ip_sioctl_arp, NULL },
1089 
1090 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1091 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 
1112 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1113 			MISC_CMD, if_unitsel, if_unitsel_restart },
1114 
1115 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 
1134 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1135 			IPI_PRIV | IPI_WR | IPI_MODOK,
1136 			IF_CMD, ip_sioctl_sifname, NULL },
1137 
1138 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 
1152 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1153 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1154 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1155 			IF_CMD, ip_sioctl_get_muxid, NULL },
1156 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1157 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1158 
1159 	/* Both if and lif variants share same func */
1160 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1161 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1162 	/* Both if and lif variants share same func */
1163 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1164 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1165 
1166 	/* copyin size cannot be coded for SIOCGIFCONF */
1167 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1168 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1169 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1170 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 
1187 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1188 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1189 			ip_sioctl_removeif_restart },
1190 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1191 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1192 			LIF_CMD, ip_sioctl_addif, NULL },
1193 #define	SIOCLIFADDR_NDX 112
1194 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1195 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1196 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1197 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1198 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1199 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1200 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1201 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1202 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1203 			IPI_PRIV | IPI_WR,
1204 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1205 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1206 			IPI_GET_CMD | IPI_MODOK,
1207 			LIF_CMD, ip_sioctl_get_flags, NULL },
1208 
1209 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1210 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 
1212 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1213 			ip_sioctl_get_lifconf, NULL },
1214 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1215 			LIF_CMD, ip_sioctl_mtu, NULL },
1216 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1217 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1218 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1219 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1220 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1221 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1222 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1223 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1224 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1225 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1226 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1227 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1228 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1229 			LIF_CMD, ip_sioctl_metric, NULL },
1230 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1231 			IPI_PRIV | IPI_WR | IPI_MODOK,
1232 			LIF_CMD, ip_sioctl_slifname,
1233 			ip_sioctl_slifname_restart },
1234 
1235 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1236 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1237 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1238 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1239 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1240 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1241 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1242 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1243 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1244 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1245 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1246 			LIF_CMD, ip_sioctl_token, NULL },
1247 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1248 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1249 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1250 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1251 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1252 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1253 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1254 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1255 
1256 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1257 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1258 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1259 			LIF_CMD, ip_siocdelndp_v6, NULL },
1260 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1261 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1262 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1263 			LIF_CMD, ip_siocsetndp_v6, NULL },
1264 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1265 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1266 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1267 			MISC_CMD, ip_sioctl_tonlink, NULL },
1268 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1269 			MISC_CMD, ip_sioctl_tmysite, NULL },
1270 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1271 			TUN_CMD, ip_sioctl_tunparam, NULL },
1272 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1273 		    IPI_PRIV | IPI_WR,
1274 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1275 
1276 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1277 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1278 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1279 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1280 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1281 
1282 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1283 
1284 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1285 			LIF_CMD, ip_sioctl_get_binding, NULL },
1286 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1287 			IPI_PRIV | IPI_WR,
1288 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1289 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1290 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1291 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1292 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1293 
1294 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1295 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1296 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1298 
1299 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1300 
1301 	/* These are handled in ip_sioctl_copyin_setup itself */
1302 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1303 			MISC_CMD, NULL, NULL },
1304 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1305 			MISC_CMD, NULL, NULL },
1306 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1307 
1308 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1309 			ip_sioctl_get_lifconf, NULL },
1310 
1311 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1312 			XARP_CMD, ip_sioctl_arp, NULL },
1313 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1314 			XARP_CMD, ip_sioctl_arp, NULL },
1315 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1316 			XARP_CMD, ip_sioctl_arp, NULL },
1317 
1318 	/* SIOCPOPSOCKFS is not handled by IP */
1319 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1320 
1321 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1322 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1323 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1324 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1325 			ip_sioctl_slifzone_restart },
1326 	/* 172-174 are SCTP ioctls and not handled by IP */
1327 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1328 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1329 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1330 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1331 			IPI_GET_CMD, LIF_CMD,
1332 			ip_sioctl_get_lifusesrc, 0 },
1333 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1334 			IPI_PRIV | IPI_WR,
1335 			LIF_CMD, ip_sioctl_slifusesrc,
1336 			NULL },
1337 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1338 			ip_sioctl_get_lifsrcof, NULL },
1339 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1340 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1341 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1342 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1343 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1344 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1345 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1346 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1347 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1348 	/* SIOCSENABLESDP is handled by SDP */
1349 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1350 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1351 };
1352 
1353 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1354 
1355 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1356 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1357 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1358 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1359 		TUN_CMD, ip_sioctl_tunparam, NULL },
1360 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1361 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1362 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1363 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1364 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1365 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1366 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1367 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1368 		MISC_CMD, mrt_ioctl},
1369 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1370 		MISC_CMD, mrt_ioctl},
1371 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1372 		MISC_CMD, mrt_ioctl}
1373 };
1374 
1375 int ip_misc_ioctl_count =
1376     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1377 
1378 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1379 					/* Settable in /etc/system */
1380 /* Defined in ip_ire.c */
1381 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1382 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1383 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1384 
1385 static nv_t	ire_nv_arr[] = {
1386 	{ IRE_BROADCAST, "BROADCAST" },
1387 	{ IRE_LOCAL, "LOCAL" },
1388 	{ IRE_LOOPBACK, "LOOPBACK" },
1389 	{ IRE_CACHE, "CACHE" },
1390 	{ IRE_DEFAULT, "DEFAULT" },
1391 	{ IRE_PREFIX, "PREFIX" },
1392 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1393 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1394 	{ IRE_HOST, "HOST" },
1395 	{ 0 }
1396 };
1397 
1398 nv_t	*ire_nv_tbl = ire_nv_arr;
1399 
1400 /* Simple ICMP IP Header Template */
1401 static ipha_t icmp_ipha = {
1402 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1403 };
1404 
1405 struct module_info ip_mod_info = {
1406 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1407 	IP_MOD_LOWAT
1408 };
1409 
1410 /*
1411  * Duplicate static symbols within a module confuses mdb; so we avoid the
1412  * problem by making the symbols here distinct from those in udp.c.
1413  */
1414 
1415 /*
1416  * Entry points for IP as a device and as a module.
1417  * FIXME: down the road we might want a separate module and driver qinit.
1418  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1419  */
1420 static struct qinit iprinitv4 = {
1421 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1422 	&ip_mod_info
1423 };
1424 
1425 struct qinit iprinitv6 = {
1426 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1427 	&ip_mod_info
1428 };
1429 
1430 static struct qinit ipwinitv4 = {
1431 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1432 	&ip_mod_info
1433 };
1434 
1435 struct qinit ipwinitv6 = {
1436 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1437 	&ip_mod_info
1438 };
1439 
1440 static struct qinit iplrinit = {
1441 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1442 	&ip_mod_info
1443 };
1444 
1445 static struct qinit iplwinit = {
1446 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1447 	&ip_mod_info
1448 };
1449 
1450 /* For AF_INET aka /dev/ip */
1451 struct streamtab ipinfov4 = {
1452 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1453 };
1454 
1455 /* For AF_INET6 aka /dev/ip6 */
1456 struct streamtab ipinfov6 = {
1457 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1458 };
1459 
1460 #ifdef	DEBUG
1461 static boolean_t skip_sctp_cksum = B_FALSE;
1462 #endif
1463 
1464 /*
1465  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1466  * ip_rput_v6(), ip_output(), etc.  If the message
1467  * block already has a M_CTL at the front of it, then simply set the zoneid
1468  * appropriately.
1469  */
1470 mblk_t *
1471 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1472 {
1473 	mblk_t		*first_mp;
1474 	ipsec_out_t	*io;
1475 
1476 	ASSERT(zoneid != ALL_ZONES);
1477 	if (mp->b_datap->db_type == M_CTL) {
1478 		io = (ipsec_out_t *)mp->b_rptr;
1479 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1480 		io->ipsec_out_zoneid = zoneid;
1481 		return (mp);
1482 	}
1483 
1484 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1485 	if (first_mp == NULL)
1486 		return (NULL);
1487 	io = (ipsec_out_t *)first_mp->b_rptr;
1488 	/* This is not a secure packet */
1489 	io->ipsec_out_secure = B_FALSE;
1490 	io->ipsec_out_zoneid = zoneid;
1491 	first_mp->b_cont = mp;
1492 	return (first_mp);
1493 }
1494 
1495 /*
1496  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1497  */
1498 mblk_t *
1499 ip_copymsg(mblk_t *mp)
1500 {
1501 	mblk_t *nmp;
1502 	ipsec_info_t *in;
1503 
1504 	if (mp->b_datap->db_type != M_CTL)
1505 		return (copymsg(mp));
1506 
1507 	in = (ipsec_info_t *)mp->b_rptr;
1508 
1509 	/*
1510 	 * Note that M_CTL is also used for delivering ICMP error messages
1511 	 * upstream to transport layers.
1512 	 */
1513 	if (in->ipsec_info_type != IPSEC_OUT &&
1514 	    in->ipsec_info_type != IPSEC_IN)
1515 		return (copymsg(mp));
1516 
1517 	nmp = copymsg(mp->b_cont);
1518 
1519 	if (in->ipsec_info_type == IPSEC_OUT) {
1520 		return (ipsec_out_tag(mp, nmp,
1521 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1522 	} else {
1523 		return (ipsec_in_tag(mp, nmp,
1524 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1525 	}
1526 }
1527 
1528 /* Generate an ICMP fragmentation needed message. */
1529 static void
1530 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1531     ip_stack_t *ipst)
1532 {
1533 	icmph_t	icmph;
1534 	mblk_t *first_mp;
1535 	boolean_t mctl_present;
1536 
1537 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1538 
1539 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1540 		if (mctl_present)
1541 			freeb(first_mp);
1542 		return;
1543 	}
1544 
1545 	bzero(&icmph, sizeof (icmph_t));
1546 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1547 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1548 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1549 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1550 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1551 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1552 	    ipst);
1553 }
1554 
1555 /*
1556  * icmp_inbound deals with ICMP messages in the following ways.
1557  *
1558  * 1) It needs to send a reply back and possibly delivering it
1559  *    to the "interested" upper clients.
1560  * 2) It needs to send it to the upper clients only.
1561  * 3) It needs to change some values in IP only.
1562  * 4) It needs to change some values in IP and upper layers e.g TCP.
1563  *
1564  * We need to accomodate icmp messages coming in clear until we get
1565  * everything secure from the wire. If icmp_accept_clear_messages
1566  * is zero we check with the global policy and act accordingly. If
1567  * it is non-zero, we accept the message without any checks. But
1568  * *this does not mean* that this will be delivered to the upper
1569  * clients. By accepting we might send replies back, change our MTU
1570  * value etc. but delivery to the ULP/clients depends on their policy
1571  * dispositions.
1572  *
1573  * We handle the above 4 cases in the context of IPsec in the
1574  * following way :
1575  *
1576  * 1) Send the reply back in the same way as the request came in.
1577  *    If it came in encrypted, it goes out encrypted. If it came in
1578  *    clear, it goes out in clear. Thus, this will prevent chosen
1579  *    plain text attack.
1580  * 2) The client may or may not expect things to come in secure.
1581  *    If it comes in secure, the policy constraints are checked
1582  *    before delivering it to the upper layers. If it comes in
1583  *    clear, ipsec_inbound_accept_clear will decide whether to
1584  *    accept this in clear or not. In both the cases, if the returned
1585  *    message (IP header + 8 bytes) that caused the icmp message has
1586  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1587  *    sending up. If there are only 8 bytes of returned message, then
1588  *    upper client will not be notified.
1589  * 3) Check with global policy to see whether it matches the constaints.
1590  *    But this will be done only if icmp_accept_messages_in_clear is
1591  *    zero.
1592  * 4) If we need to change both in IP and ULP, then the decision taken
1593  *    while affecting the values in IP and while delivering up to TCP
1594  *    should be the same.
1595  *
1596  * 	There are two cases.
1597  *
1598  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1599  *	   failed), we will not deliver it to the ULP, even though they
1600  *	   are *willing* to accept in *clear*. This is fine as our global
1601  *	   disposition to icmp messages asks us reject the datagram.
1602  *
1603  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1604  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1605  *	   to deliver it to ULP (policy failed), it can lead to
1606  *	   consistency problems. The cases known at this time are
1607  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1608  *	   values :
1609  *
1610  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1611  *	     and Upper layer rejects. Then the communication will
1612  *	     come to a stop. This is solved by making similar decisions
1613  *	     at both levels. Currently, when we are unable to deliver
1614  *	     to the Upper Layer (due to policy failures) while IP has
1615  *	     adjusted ire_max_frag, the next outbound datagram would
1616  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1617  *	     will be with the right level of protection. Thus the right
1618  *	     value will be communicated even if we are not able to
1619  *	     communicate when we get from the wire initially. But this
1620  *	     assumes there would be at least one outbound datagram after
1621  *	     IP has adjusted its ire_max_frag value. To make things
1622  *	     simpler, we accept in clear after the validation of
1623  *	     AH/ESP headers.
1624  *
1625  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1626  *	     upper layer depending on the level of protection the upper
1627  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1628  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1629  *	     should be accepted in clear when the Upper layer expects secure.
1630  *	     Thus the communication may get aborted by some bad ICMP
1631  *	     packets.
1632  *
1633  * IPQoS Notes:
1634  * The only instance when a packet is sent for processing is when there
1635  * isn't an ICMP client and if we are interested in it.
1636  * If there is a client, IPPF processing will take place in the
1637  * ip_fanout_proto routine.
1638  *
1639  * Zones notes:
1640  * The packet is only processed in the context of the specified zone: typically
1641  * only this zone will reply to an echo request, and only interested clients in
1642  * this zone will receive a copy of the packet. This means that the caller must
1643  * call icmp_inbound() for each relevant zone.
1644  */
1645 static void
1646 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1647     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1648     ill_t *recv_ill, zoneid_t zoneid)
1649 {
1650 	icmph_t	*icmph;
1651 	ipha_t	*ipha;
1652 	int	iph_hdr_length;
1653 	int	hdr_length;
1654 	boolean_t	interested;
1655 	uint32_t	ts;
1656 	uchar_t	*wptr;
1657 	ipif_t	*ipif;
1658 	mblk_t *first_mp;
1659 	ipsec_in_t *ii;
1660 	timestruc_t now;
1661 	uint32_t ill_index;
1662 	ip_stack_t *ipst;
1663 
1664 	ASSERT(ill != NULL);
1665 	ipst = ill->ill_ipst;
1666 
1667 	first_mp = mp;
1668 	if (mctl_present) {
1669 		mp = first_mp->b_cont;
1670 		ASSERT(mp != NULL);
1671 	}
1672 
1673 	ipha = (ipha_t *)mp->b_rptr;
1674 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1675 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1676 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1677 		if (first_mp == NULL)
1678 			return;
1679 	}
1680 
1681 	/*
1682 	 * On a labeled system, we have to check whether the zone itself is
1683 	 * permitted to receive raw traffic.
1684 	 */
1685 	if (is_system_labeled()) {
1686 		if (zoneid == ALL_ZONES)
1687 			zoneid = tsol_packet_to_zoneid(mp);
1688 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1689 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1690 			    zoneid));
1691 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1692 			freemsg(first_mp);
1693 			return;
1694 		}
1695 	}
1696 
1697 	/*
1698 	 * We have accepted the ICMP message. It means that we will
1699 	 * respond to the packet if needed. It may not be delivered
1700 	 * to the upper client depending on the policy constraints
1701 	 * and the disposition in ipsec_inbound_accept_clear.
1702 	 */
1703 
1704 	ASSERT(ill != NULL);
1705 
1706 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1707 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1708 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1709 		/* Last chance to get real. */
1710 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1711 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1712 			freemsg(first_mp);
1713 			return;
1714 		}
1715 		/* Refresh iph following the pullup. */
1716 		ipha = (ipha_t *)mp->b_rptr;
1717 	}
1718 	/* ICMP header checksum, including checksum field, should be zero. */
1719 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1720 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1721 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1722 		freemsg(first_mp);
1723 		return;
1724 	}
1725 	/* The IP header will always be a multiple of four bytes */
1726 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1727 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1728 	    icmph->icmph_code));
1729 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1730 	/* We will set "interested" to "true" if we want a copy */
1731 	interested = B_FALSE;
1732 	switch (icmph->icmph_type) {
1733 	case ICMP_ECHO_REPLY:
1734 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1735 		break;
1736 	case ICMP_DEST_UNREACHABLE:
1737 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1738 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1739 		interested = B_TRUE;	/* Pass up to transport */
1740 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1741 		break;
1742 	case ICMP_SOURCE_QUENCH:
1743 		interested = B_TRUE;	/* Pass up to transport */
1744 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1745 		break;
1746 	case ICMP_REDIRECT:
1747 		if (!ipst->ips_ip_ignore_redirect)
1748 			interested = B_TRUE;
1749 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1750 		break;
1751 	case ICMP_ECHO_REQUEST:
1752 		/*
1753 		 * Whether to respond to echo requests that come in as IP
1754 		 * broadcasts or as IP multicast is subject to debate
1755 		 * (what isn't?).  We aim to please, you pick it.
1756 		 * Default is do it.
1757 		 */
1758 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1759 			/* unicast: always respond */
1760 			interested = B_TRUE;
1761 		} else if (CLASSD(ipha->ipha_dst)) {
1762 			/* multicast: respond based on tunable */
1763 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1764 		} else if (broadcast) {
1765 			/* broadcast: respond based on tunable */
1766 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1767 		}
1768 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1769 		break;
1770 	case ICMP_ROUTER_ADVERTISEMENT:
1771 	case ICMP_ROUTER_SOLICITATION:
1772 		break;
1773 	case ICMP_TIME_EXCEEDED:
1774 		interested = B_TRUE;	/* Pass up to transport */
1775 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1776 		break;
1777 	case ICMP_PARAM_PROBLEM:
1778 		interested = B_TRUE;	/* Pass up to transport */
1779 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1780 		break;
1781 	case ICMP_TIME_STAMP_REQUEST:
1782 		/* Response to Time Stamp Requests is local policy. */
1783 		if (ipst->ips_ip_g_resp_to_timestamp &&
1784 		    /* So is whether to respond if it was an IP broadcast. */
1785 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1786 			int tstamp_len = 3 * sizeof (uint32_t);
1787 
1788 			if (wptr +  tstamp_len > mp->b_wptr) {
1789 				if (!pullupmsg(mp, wptr + tstamp_len -
1790 				    mp->b_rptr)) {
1791 					BUMP_MIB(ill->ill_ip_mib,
1792 					    ipIfStatsInDiscards);
1793 					freemsg(first_mp);
1794 					return;
1795 				}
1796 				/* Refresh ipha following the pullup. */
1797 				ipha = (ipha_t *)mp->b_rptr;
1798 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1799 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1800 			}
1801 			interested = B_TRUE;
1802 		}
1803 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1804 		break;
1805 	case ICMP_TIME_STAMP_REPLY:
1806 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1807 		break;
1808 	case ICMP_INFO_REQUEST:
1809 		/* Per RFC 1122 3.2.2.7, ignore this. */
1810 	case ICMP_INFO_REPLY:
1811 		break;
1812 	case ICMP_ADDRESS_MASK_REQUEST:
1813 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1814 		    !broadcast) &&
1815 		    /* TODO m_pullup of complete header? */
1816 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1817 			interested = B_TRUE;
1818 		}
1819 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1820 		break;
1821 	case ICMP_ADDRESS_MASK_REPLY:
1822 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1823 		break;
1824 	default:
1825 		interested = B_TRUE;	/* Pass up to transport */
1826 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1827 		break;
1828 	}
1829 	/* See if there is an ICMP client. */
1830 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1831 		/* If there is an ICMP client and we want one too, copy it. */
1832 		mblk_t *first_mp1;
1833 
1834 		if (!interested) {
1835 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1836 			    ip_policy, recv_ill, zoneid);
1837 			return;
1838 		}
1839 		first_mp1 = ip_copymsg(first_mp);
1840 		if (first_mp1 != NULL) {
1841 			ip_fanout_proto(q, first_mp1, ill, ipha,
1842 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1843 		}
1844 	} else if (!interested) {
1845 		freemsg(first_mp);
1846 		return;
1847 	} else {
1848 		/*
1849 		 * Initiate policy processing for this packet if ip_policy
1850 		 * is true.
1851 		 */
1852 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1853 			ill_index = ill->ill_phyint->phyint_ifindex;
1854 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1855 			if (mp == NULL) {
1856 				if (mctl_present) {
1857 					freeb(first_mp);
1858 				}
1859 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1860 				return;
1861 			}
1862 		}
1863 	}
1864 	/* We want to do something with it. */
1865 	/* Check db_ref to make sure we can modify the packet. */
1866 	if (mp->b_datap->db_ref > 1) {
1867 		mblk_t	*first_mp1;
1868 
1869 		first_mp1 = ip_copymsg(first_mp);
1870 		freemsg(first_mp);
1871 		if (!first_mp1) {
1872 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1873 			return;
1874 		}
1875 		first_mp = first_mp1;
1876 		if (mctl_present) {
1877 			mp = first_mp->b_cont;
1878 			ASSERT(mp != NULL);
1879 		} else {
1880 			mp = first_mp;
1881 		}
1882 		ipha = (ipha_t *)mp->b_rptr;
1883 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1884 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1885 	}
1886 	switch (icmph->icmph_type) {
1887 	case ICMP_ADDRESS_MASK_REQUEST:
1888 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1889 		if (ipif == NULL) {
1890 			freemsg(first_mp);
1891 			return;
1892 		}
1893 		/*
1894 		 * outging interface must be IPv4
1895 		 */
1896 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1897 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1898 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1899 		ipif_refrele(ipif);
1900 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1901 		break;
1902 	case ICMP_ECHO_REQUEST:
1903 		icmph->icmph_type = ICMP_ECHO_REPLY;
1904 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1905 		break;
1906 	case ICMP_TIME_STAMP_REQUEST: {
1907 		uint32_t *tsp;
1908 
1909 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1910 		tsp = (uint32_t *)wptr;
1911 		tsp++;		/* Skip past 'originate time' */
1912 		/* Compute # of milliseconds since midnight */
1913 		gethrestime(&now);
1914 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1915 		    now.tv_nsec / (NANOSEC / MILLISEC);
1916 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1917 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1918 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1919 		break;
1920 	}
1921 	default:
1922 		ipha = (ipha_t *)&icmph[1];
1923 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1924 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1925 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1926 				freemsg(first_mp);
1927 				return;
1928 			}
1929 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1930 			ipha = (ipha_t *)&icmph[1];
1931 		}
1932 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1933 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1934 			freemsg(first_mp);
1935 			return;
1936 		}
1937 		hdr_length = IPH_HDR_LENGTH(ipha);
1938 		if (hdr_length < sizeof (ipha_t)) {
1939 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1940 			freemsg(first_mp);
1941 			return;
1942 		}
1943 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1944 			if (!pullupmsg(mp,
1945 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1946 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1947 				freemsg(first_mp);
1948 				return;
1949 			}
1950 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1951 			ipha = (ipha_t *)&icmph[1];
1952 		}
1953 		switch (icmph->icmph_type) {
1954 		case ICMP_REDIRECT:
1955 			/*
1956 			 * As there is no upper client to deliver, we don't
1957 			 * need the first_mp any more.
1958 			 */
1959 			if (mctl_present) {
1960 				freeb(first_mp);
1961 			}
1962 			icmp_redirect(ill, mp);
1963 			return;
1964 		case ICMP_DEST_UNREACHABLE:
1965 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1966 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1967 				    zoneid, mp, iph_hdr_length, ipst)) {
1968 					freemsg(first_mp);
1969 					return;
1970 				}
1971 				/*
1972 				 * icmp_inbound_too_big() may alter mp.
1973 				 * Resynch ipha and icmph accordingly.
1974 				 */
1975 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1976 				ipha = (ipha_t *)&icmph[1];
1977 			}
1978 			/* FALLTHRU */
1979 		default :
1980 			/*
1981 			 * IPQoS notes: Since we have already done IPQoS
1982 			 * processing we don't want to do it again in
1983 			 * the fanout routines called by
1984 			 * icmp_inbound_error_fanout, hence the last
1985 			 * argument, ip_policy, is B_FALSE.
1986 			 */
1987 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1988 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1989 			    B_FALSE, recv_ill, zoneid);
1990 		}
1991 		return;
1992 	}
1993 	/* Send out an ICMP packet */
1994 	icmph->icmph_checksum = 0;
1995 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1996 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1997 		ipif_t	*ipif_chosen;
1998 		/*
1999 		 * Make it look like it was directed to us, so we don't look
2000 		 * like a fool with a broadcast or multicast source address.
2001 		 */
2002 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2003 		/*
2004 		 * Make sure that we haven't grabbed an interface that's DOWN.
2005 		 */
2006 		if (ipif != NULL) {
2007 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2008 			    ipha->ipha_src, zoneid);
2009 			if (ipif_chosen != NULL) {
2010 				ipif_refrele(ipif);
2011 				ipif = ipif_chosen;
2012 			}
2013 		}
2014 		if (ipif == NULL) {
2015 			ip0dbg(("icmp_inbound: "
2016 			    "No source for broadcast/multicast:\n"
2017 			    "\tsrc 0x%x dst 0x%x ill %p "
2018 			    "ipif_lcl_addr 0x%x\n",
2019 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2020 			    (void *)ill,
2021 			    ill->ill_ipif->ipif_lcl_addr));
2022 			freemsg(first_mp);
2023 			return;
2024 		}
2025 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2026 		ipha->ipha_dst = ipif->ipif_src_addr;
2027 		ipif_refrele(ipif);
2028 	}
2029 	/* Reset time to live. */
2030 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2031 	{
2032 		/* Swap source and destination addresses */
2033 		ipaddr_t tmp;
2034 
2035 		tmp = ipha->ipha_src;
2036 		ipha->ipha_src = ipha->ipha_dst;
2037 		ipha->ipha_dst = tmp;
2038 	}
2039 	ipha->ipha_ident = 0;
2040 	if (!IS_SIMPLE_IPH(ipha))
2041 		icmp_options_update(ipha);
2042 
2043 	if (!mctl_present) {
2044 		/*
2045 		 * This packet should go out the same way as it
2046 		 * came in i.e in clear. To make sure that global
2047 		 * policy will not be applied to this in ip_wput_ire,
2048 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2049 		 */
2050 		ASSERT(first_mp == mp);
2051 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2052 		if (first_mp == NULL) {
2053 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2054 			freemsg(mp);
2055 			return;
2056 		}
2057 		ii = (ipsec_in_t *)first_mp->b_rptr;
2058 
2059 		/* This is not a secure packet */
2060 		ii->ipsec_in_secure = B_FALSE;
2061 		first_mp->b_cont = mp;
2062 	} else {
2063 		ii = (ipsec_in_t *)first_mp->b_rptr;
2064 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2065 	}
2066 	ii->ipsec_in_zoneid = zoneid;
2067 	ASSERT(zoneid != ALL_ZONES);
2068 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2069 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2070 		return;
2071 	}
2072 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2073 	put(WR(q), first_mp);
2074 }
2075 
2076 static ipaddr_t
2077 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2078 {
2079 	conn_t *connp;
2080 	connf_t *connfp;
2081 	ipaddr_t nexthop_addr = INADDR_ANY;
2082 	int hdr_length = IPH_HDR_LENGTH(ipha);
2083 	uint16_t *up;
2084 	uint32_t ports;
2085 	ip_stack_t *ipst = ill->ill_ipst;
2086 
2087 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2088 	switch (ipha->ipha_protocol) {
2089 		case IPPROTO_TCP:
2090 		{
2091 			tcph_t *tcph;
2092 
2093 			/* do a reverse lookup */
2094 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2095 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2096 			    TCPS_LISTEN, ipst);
2097 			break;
2098 		}
2099 		case IPPROTO_UDP:
2100 		{
2101 			uint32_t dstport, srcport;
2102 
2103 			((uint16_t *)&ports)[0] = up[1];
2104 			((uint16_t *)&ports)[1] = up[0];
2105 
2106 			/* Extract ports in net byte order */
2107 			dstport = htons(ntohl(ports) & 0xFFFF);
2108 			srcport = htons(ntohl(ports) >> 16);
2109 
2110 			connfp = &ipst->ips_ipcl_udp_fanout[
2111 			    IPCL_UDP_HASH(dstport, ipst)];
2112 			mutex_enter(&connfp->connf_lock);
2113 			connp = connfp->connf_head;
2114 
2115 			/* do a reverse lookup */
2116 			while ((connp != NULL) &&
2117 			    (!IPCL_UDP_MATCH(connp, dstport,
2118 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2119 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2120 				connp = connp->conn_next;
2121 			}
2122 			if (connp != NULL)
2123 				CONN_INC_REF(connp);
2124 			mutex_exit(&connfp->connf_lock);
2125 			break;
2126 		}
2127 		case IPPROTO_SCTP:
2128 		{
2129 			in6_addr_t map_src, map_dst;
2130 
2131 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2132 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2133 			((uint16_t *)&ports)[0] = up[1];
2134 			((uint16_t *)&ports)[1] = up[0];
2135 
2136 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2137 			    zoneid, ipst->ips_netstack->netstack_sctp);
2138 			if (connp == NULL) {
2139 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2140 				    zoneid, ports, ipha, ipst);
2141 			} else {
2142 				CONN_INC_REF(connp);
2143 				SCTP_REFRELE(CONN2SCTP(connp));
2144 			}
2145 			break;
2146 		}
2147 		default:
2148 		{
2149 			ipha_t ripha;
2150 
2151 			ripha.ipha_src = ipha->ipha_dst;
2152 			ripha.ipha_dst = ipha->ipha_src;
2153 			ripha.ipha_protocol = ipha->ipha_protocol;
2154 
2155 			connfp = &ipst->ips_ipcl_proto_fanout[
2156 			    ipha->ipha_protocol];
2157 			mutex_enter(&connfp->connf_lock);
2158 			connp = connfp->connf_head;
2159 			for (connp = connfp->connf_head; connp != NULL;
2160 			    connp = connp->conn_next) {
2161 				if (IPCL_PROTO_MATCH(connp,
2162 				    ipha->ipha_protocol, &ripha, ill,
2163 				    0, zoneid)) {
2164 					CONN_INC_REF(connp);
2165 					break;
2166 				}
2167 			}
2168 			mutex_exit(&connfp->connf_lock);
2169 		}
2170 	}
2171 	if (connp != NULL) {
2172 		if (connp->conn_nexthop_set)
2173 			nexthop_addr = connp->conn_nexthop_v4;
2174 		CONN_DEC_REF(connp);
2175 	}
2176 	return (nexthop_addr);
2177 }
2178 
2179 /* Table from RFC 1191 */
2180 static int icmp_frag_size_table[] =
2181 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2182 
2183 /*
2184  * Process received ICMP Packet too big.
2185  * After updating any IRE it does the fanout to any matching transport streams.
2186  * Assumes the message has been pulled up till the IP header that caused
2187  * the error.
2188  *
2189  * Returns B_FALSE on failure and B_TRUE on success.
2190  */
2191 static boolean_t
2192 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2193     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2194     ip_stack_t *ipst)
2195 {
2196 	ire_t	*ire, *first_ire;
2197 	int	mtu, orig_mtu;
2198 	int	hdr_length;
2199 	ipaddr_t nexthop_addr;
2200 	boolean_t disable_pmtud;
2201 
2202 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2203 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2204 	ASSERT(ill != NULL);
2205 
2206 	hdr_length = IPH_HDR_LENGTH(ipha);
2207 
2208 	/* Drop if the original packet contained a source route */
2209 	if (ip_source_route_included(ipha)) {
2210 		return (B_FALSE);
2211 	}
2212 	/*
2213 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2214 	 * header.
2215 	 */
2216 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2217 	    mp->b_wptr) {
2218 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2219 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2220 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2221 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2222 			return (B_FALSE);
2223 		}
2224 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2225 		ipha = (ipha_t *)&icmph[1];
2226 	}
2227 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2228 	if (nexthop_addr != INADDR_ANY) {
2229 		/* nexthop set */
2230 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2231 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2232 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2233 	} else {
2234 		/* nexthop not set */
2235 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2236 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2237 	}
2238 
2239 	if (!first_ire) {
2240 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2241 		    ntohl(ipha->ipha_dst)));
2242 		return (B_FALSE);
2243 	}
2244 
2245 	/* Check for MTU discovery advice as described in RFC 1191 */
2246 	mtu = ntohs(icmph->icmph_du_mtu);
2247 	orig_mtu = mtu;
2248 	disable_pmtud = B_FALSE;
2249 
2250 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2251 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2252 	    ire = ire->ire_next) {
2253 		/*
2254 		 * Look for the connection to which this ICMP message is
2255 		 * directed. If it has the IP_NEXTHOP option set, then the
2256 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2257 		 * option. Else the search is limited to regular IREs.
2258 		 */
2259 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2260 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2261 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2262 		    (nexthop_addr != INADDR_ANY)))
2263 			continue;
2264 
2265 		mutex_enter(&ire->ire_lock);
2266 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2267 			uint32_t length;
2268 			int	i;
2269 
2270 			/*
2271 			 * Use the table from RFC 1191 to figure out
2272 			 * the next "plateau" based on the length in
2273 			 * the original IP packet.
2274 			 */
2275 			length = ntohs(ipha->ipha_length);
2276 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2277 			    uint32_t, length);
2278 			if (ire->ire_max_frag <= length &&
2279 			    ire->ire_max_frag >= length - hdr_length) {
2280 				/*
2281 				 * Handle broken BSD 4.2 systems that
2282 				 * return the wrong iph_length in ICMP
2283 				 * errors.
2284 				 */
2285 				length -= hdr_length;
2286 			}
2287 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2288 				if (length > icmp_frag_size_table[i])
2289 					break;
2290 			}
2291 			if (i == A_CNT(icmp_frag_size_table)) {
2292 				/* Smaller than 68! */
2293 				disable_pmtud = B_TRUE;
2294 				mtu = ipst->ips_ip_pmtu_min;
2295 			} else {
2296 				mtu = icmp_frag_size_table[i];
2297 				if (mtu < ipst->ips_ip_pmtu_min) {
2298 					mtu = ipst->ips_ip_pmtu_min;
2299 					disable_pmtud = B_TRUE;
2300 				}
2301 			}
2302 			/* Fool the ULP into believing our guessed PMTU. */
2303 			icmph->icmph_du_zero = 0;
2304 			icmph->icmph_du_mtu = htons(mtu);
2305 		}
2306 		if (disable_pmtud)
2307 			ire->ire_frag_flag = 0;
2308 		/* Reduce the IRE max frag value as advised. */
2309 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2310 		mutex_exit(&ire->ire_lock);
2311 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2312 		    ire, int, orig_mtu, int, mtu);
2313 	}
2314 	rw_exit(&first_ire->ire_bucket->irb_lock);
2315 	ire_refrele(first_ire);
2316 	return (B_TRUE);
2317 }
2318 
2319 /*
2320  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2321  * calls this function.
2322  */
2323 static mblk_t *
2324 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2325 {
2326 	ipha_t *ipha;
2327 	icmph_t *icmph;
2328 	ipha_t *in_ipha;
2329 	int length;
2330 
2331 	ASSERT(mp->b_datap->db_type == M_DATA);
2332 
2333 	/*
2334 	 * For Self-encapsulated packets, we added an extra IP header
2335 	 * without the options. Inner IP header is the one from which
2336 	 * the outer IP header was formed. Thus, we need to remove the
2337 	 * outer IP header. To do this, we pullup the whole message
2338 	 * and overlay whatever follows the outer IP header over the
2339 	 * outer IP header.
2340 	 */
2341 
2342 	if (!pullupmsg(mp, -1))
2343 		return (NULL);
2344 
2345 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2346 	ipha = (ipha_t *)&icmph[1];
2347 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2348 
2349 	/*
2350 	 * The length that we want to overlay is following the inner
2351 	 * IP header. Subtracting the IP header + icmp header + outer
2352 	 * IP header's length should give us the length that we want to
2353 	 * overlay.
2354 	 */
2355 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2356 	    hdr_length;
2357 	/*
2358 	 * Overlay whatever follows the inner header over the
2359 	 * outer header.
2360 	 */
2361 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2362 
2363 	/* Set the wptr to account for the outer header */
2364 	mp->b_wptr -= hdr_length;
2365 	return (mp);
2366 }
2367 
2368 /*
2369  * Try to pass the ICMP message upstream in case the ULP cares.
2370  *
2371  * If the packet that caused the ICMP error is secure, we send
2372  * it to AH/ESP to make sure that the attached packet has a
2373  * valid association. ipha in the code below points to the
2374  * IP header of the packet that caused the error.
2375  *
2376  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2377  * in the context of IPsec. Normally we tell the upper layer
2378  * whenever we send the ire (including ip_bind), the IPsec header
2379  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2380  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2381  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2382  * same thing. As TCP has the IPsec options size that needs to be
2383  * adjusted, we just pass the MTU unchanged.
2384  *
2385  * IFN could have been generated locally or by some router.
2386  *
2387  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2388  *	    This happens because IP adjusted its value of MTU on an
2389  *	    earlier IFN message and could not tell the upper layer,
2390  *	    the new adjusted value of MTU e.g. Packet was encrypted
2391  *	    or there was not enough information to fanout to upper
2392  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2393  *	    generates the IFN, where IPsec processing has *not* been
2394  *	    done.
2395  *
2396  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2397  *	    could have generated this. This happens because ire_max_frag
2398  *	    value in IP was set to a new value, while the IPsec processing
2399  *	    was being done and after we made the fragmentation check in
2400  *	    ip_wput_ire. Thus on return from IPsec processing,
2401  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2402  *	    and generates the IFN. As IPsec processing is over, we fanout
2403  *	    to AH/ESP to remove the header.
2404  *
2405  *	    In both these cases, ipsec_in_loopback will be set indicating
2406  *	    that IFN was generated locally.
2407  *
2408  * ROUTER : IFN could be secure or non-secure.
2409  *
2410  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2411  *	      packet in error has AH/ESP headers to validate the AH/ESP
2412  *	      headers. AH/ESP will verify whether there is a valid SA or
2413  *	      not and send it back. We will fanout again if we have more
2414  *	      data in the packet.
2415  *
2416  *	      If the packet in error does not have AH/ESP, we handle it
2417  *	      like any other case.
2418  *
2419  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2420  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2421  *	      for validation. AH/ESP will verify whether there is a
2422  *	      valid SA or not and send it back. We will fanout again if
2423  *	      we have more data in the packet.
2424  *
2425  *	      If the packet in error does not have AH/ESP, we handle it
2426  *	      like any other case.
2427  */
2428 static void
2429 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2430     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2431     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2432     zoneid_t zoneid)
2433 {
2434 	uint16_t *up;	/* Pointer to ports in ULP header */
2435 	uint32_t ports;	/* reversed ports for fanout */
2436 	ipha_t ripha;	/* With reversed addresses */
2437 	mblk_t *first_mp;
2438 	ipsec_in_t *ii;
2439 	tcph_t	*tcph;
2440 	conn_t	*connp;
2441 	ip_stack_t *ipst;
2442 
2443 	ASSERT(ill != NULL);
2444 
2445 	ASSERT(recv_ill != NULL);
2446 	ipst = recv_ill->ill_ipst;
2447 
2448 	first_mp = mp;
2449 	if (mctl_present) {
2450 		mp = first_mp->b_cont;
2451 		ASSERT(mp != NULL);
2452 
2453 		ii = (ipsec_in_t *)first_mp->b_rptr;
2454 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2455 	} else {
2456 		ii = NULL;
2457 	}
2458 
2459 	switch (ipha->ipha_protocol) {
2460 	case IPPROTO_UDP:
2461 		/*
2462 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2463 		 * transport header.
2464 		 */
2465 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2466 		    mp->b_wptr) {
2467 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2468 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2469 				goto discard_pkt;
2470 			}
2471 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2472 			ipha = (ipha_t *)&icmph[1];
2473 		}
2474 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2475 
2476 		/*
2477 		 * Attempt to find a client stream based on port.
2478 		 * Note that we do a reverse lookup since the header is
2479 		 * in the form we sent it out.
2480 		 * The ripha header is only used for the IP_UDP_MATCH and we
2481 		 * only set the src and dst addresses and protocol.
2482 		 */
2483 		ripha.ipha_src = ipha->ipha_dst;
2484 		ripha.ipha_dst = ipha->ipha_src;
2485 		ripha.ipha_protocol = ipha->ipha_protocol;
2486 		((uint16_t *)&ports)[0] = up[1];
2487 		((uint16_t *)&ports)[1] = up[0];
2488 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2489 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2490 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2491 		    icmph->icmph_type, icmph->icmph_code));
2492 
2493 		/* Have to change db_type after any pullupmsg */
2494 		DB_TYPE(mp) = M_CTL;
2495 
2496 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2497 		    mctl_present, ip_policy, recv_ill, zoneid);
2498 		return;
2499 
2500 	case IPPROTO_TCP:
2501 		/*
2502 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2503 		 * transport header.
2504 		 */
2505 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2506 		    mp->b_wptr) {
2507 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2508 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2509 				goto discard_pkt;
2510 			}
2511 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2512 			ipha = (ipha_t *)&icmph[1];
2513 		}
2514 		/*
2515 		 * Find a TCP client stream for this packet.
2516 		 * Note that we do a reverse lookup since the header is
2517 		 * in the form we sent it out.
2518 		 */
2519 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2520 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2521 		    ipst);
2522 		if (connp == NULL)
2523 			goto discard_pkt;
2524 
2525 		/* Have to change db_type after any pullupmsg */
2526 		DB_TYPE(mp) = M_CTL;
2527 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2528 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2529 		return;
2530 
2531 	case IPPROTO_SCTP:
2532 		/*
2533 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2534 		 * transport header.
2535 		 */
2536 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2537 		    mp->b_wptr) {
2538 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2539 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2540 				goto discard_pkt;
2541 			}
2542 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2543 			ipha = (ipha_t *)&icmph[1];
2544 		}
2545 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2546 		/*
2547 		 * Find a SCTP client stream for this packet.
2548 		 * Note that we do a reverse lookup since the header is
2549 		 * in the form we sent it out.
2550 		 * The ripha header is only used for the matching and we
2551 		 * only set the src and dst addresses, protocol, and version.
2552 		 */
2553 		ripha.ipha_src = ipha->ipha_dst;
2554 		ripha.ipha_dst = ipha->ipha_src;
2555 		ripha.ipha_protocol = ipha->ipha_protocol;
2556 		ripha.ipha_version_and_hdr_length =
2557 		    ipha->ipha_version_and_hdr_length;
2558 		((uint16_t *)&ports)[0] = up[1];
2559 		((uint16_t *)&ports)[1] = up[0];
2560 
2561 		/* Have to change db_type after any pullupmsg */
2562 		DB_TYPE(mp) = M_CTL;
2563 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2564 		    mctl_present, ip_policy, zoneid);
2565 		return;
2566 
2567 	case IPPROTO_ESP:
2568 	case IPPROTO_AH: {
2569 		int ipsec_rc;
2570 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2571 
2572 		/*
2573 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2574 		 * We will re-use the IPSEC_IN if it is already present as
2575 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2576 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2577 		 * one and attach it in the front.
2578 		 */
2579 		if (ii != NULL) {
2580 			/*
2581 			 * ip_fanout_proto_again converts the ICMP errors
2582 			 * that come back from AH/ESP to M_DATA so that
2583 			 * if it is non-AH/ESP and we do a pullupmsg in
2584 			 * this function, it would work. Convert it back
2585 			 * to M_CTL before we send up as this is a ICMP
2586 			 * error. This could have been generated locally or
2587 			 * by some router. Validate the inner IPsec
2588 			 * headers.
2589 			 *
2590 			 * NOTE : ill_index is used by ip_fanout_proto_again
2591 			 * to locate the ill.
2592 			 */
2593 			ASSERT(ill != NULL);
2594 			ii->ipsec_in_ill_index =
2595 			    ill->ill_phyint->phyint_ifindex;
2596 			ii->ipsec_in_rill_index =
2597 			    recv_ill->ill_phyint->phyint_ifindex;
2598 			DB_TYPE(first_mp->b_cont) = M_CTL;
2599 		} else {
2600 			/*
2601 			 * IPSEC_IN is not present. We attach a ipsec_in
2602 			 * message and send up to IPsec for validating
2603 			 * and removing the IPsec headers. Clear
2604 			 * ipsec_in_secure so that when we return
2605 			 * from IPsec, we don't mistakenly think that this
2606 			 * is a secure packet came from the network.
2607 			 *
2608 			 * NOTE : ill_index is used by ip_fanout_proto_again
2609 			 * to locate the ill.
2610 			 */
2611 			ASSERT(first_mp == mp);
2612 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2613 			if (first_mp == NULL) {
2614 				freemsg(mp);
2615 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2616 				return;
2617 			}
2618 			ii = (ipsec_in_t *)first_mp->b_rptr;
2619 
2620 			/* This is not a secure packet */
2621 			ii->ipsec_in_secure = B_FALSE;
2622 			first_mp->b_cont = mp;
2623 			DB_TYPE(mp) = M_CTL;
2624 			ASSERT(ill != NULL);
2625 			ii->ipsec_in_ill_index =
2626 			    ill->ill_phyint->phyint_ifindex;
2627 			ii->ipsec_in_rill_index =
2628 			    recv_ill->ill_phyint->phyint_ifindex;
2629 		}
2630 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2631 
2632 		if (!ipsec_loaded(ipss)) {
2633 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2634 			return;
2635 		}
2636 
2637 		if (ipha->ipha_protocol == IPPROTO_ESP)
2638 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2639 		else
2640 			ipsec_rc = ipsecah_icmp_error(first_mp);
2641 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2642 			return;
2643 
2644 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2645 		return;
2646 	}
2647 	default:
2648 		/*
2649 		 * The ripha header is only used for the lookup and we
2650 		 * only set the src and dst addresses and protocol.
2651 		 */
2652 		ripha.ipha_src = ipha->ipha_dst;
2653 		ripha.ipha_dst = ipha->ipha_src;
2654 		ripha.ipha_protocol = ipha->ipha_protocol;
2655 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2656 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2657 		    ntohl(ipha->ipha_dst),
2658 		    icmph->icmph_type, icmph->icmph_code));
2659 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2660 			ipha_t *in_ipha;
2661 
2662 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2663 			    mp->b_wptr) {
2664 				if (!pullupmsg(mp, (uchar_t *)ipha +
2665 				    hdr_length + sizeof (ipha_t) -
2666 				    mp->b_rptr)) {
2667 					goto discard_pkt;
2668 				}
2669 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2670 				ipha = (ipha_t *)&icmph[1];
2671 			}
2672 			/*
2673 			 * Caller has verified that length has to be
2674 			 * at least the size of IP header.
2675 			 */
2676 			ASSERT(hdr_length >= sizeof (ipha_t));
2677 			/*
2678 			 * Check the sanity of the inner IP header like
2679 			 * we did for the outer header.
2680 			 */
2681 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2682 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2683 				goto discard_pkt;
2684 			}
2685 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2686 				goto discard_pkt;
2687 			}
2688 			/* Check for Self-encapsulated tunnels */
2689 			if (in_ipha->ipha_src == ipha->ipha_src &&
2690 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2691 
2692 				mp = icmp_inbound_self_encap_error(mp,
2693 				    iph_hdr_length, hdr_length);
2694 				if (mp == NULL)
2695 					goto discard_pkt;
2696 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2697 				ipha = (ipha_t *)&icmph[1];
2698 				hdr_length = IPH_HDR_LENGTH(ipha);
2699 				/*
2700 				 * The packet in error is self-encapsualted.
2701 				 * And we are finding it further encapsulated
2702 				 * which we could not have possibly generated.
2703 				 */
2704 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2705 					goto discard_pkt;
2706 				}
2707 				icmp_inbound_error_fanout(q, ill, first_mp,
2708 				    icmph, ipha, iph_hdr_length, hdr_length,
2709 				    mctl_present, ip_policy, recv_ill, zoneid);
2710 				return;
2711 			}
2712 		}
2713 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2714 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2715 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2716 		    ii != NULL &&
2717 		    ii->ipsec_in_loopback &&
2718 		    ii->ipsec_in_secure) {
2719 			/*
2720 			 * For IP tunnels that get a looped-back
2721 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2722 			 * reported new MTU to take into account the IPsec
2723 			 * headers protecting this configured tunnel.
2724 			 *
2725 			 * This allows the tunnel module (tun.c) to blindly
2726 			 * accept the MTU reported in an ICMP "too big"
2727 			 * message.
2728 			 *
2729 			 * Non-looped back ICMP messages will just be
2730 			 * handled by the security protocols (if needed),
2731 			 * and the first subsequent packet will hit this
2732 			 * path.
2733 			 */
2734 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2735 			    ipsec_in_extra_length(first_mp));
2736 		}
2737 		/* Have to change db_type after any pullupmsg */
2738 		DB_TYPE(mp) = M_CTL;
2739 
2740 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2741 		    ip_policy, recv_ill, zoneid);
2742 		return;
2743 	}
2744 	/* NOTREACHED */
2745 discard_pkt:
2746 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2747 drop_pkt:;
2748 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2749 	freemsg(first_mp);
2750 }
2751 
2752 /*
2753  * Common IP options parser.
2754  *
2755  * Setup routine: fill in *optp with options-parsing state, then
2756  * tail-call ipoptp_next to return the first option.
2757  */
2758 uint8_t
2759 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2760 {
2761 	uint32_t totallen; /* total length of all options */
2762 
2763 	totallen = ipha->ipha_version_and_hdr_length -
2764 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2765 	totallen <<= 2;
2766 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2767 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2768 	optp->ipoptp_flags = 0;
2769 	return (ipoptp_next(optp));
2770 }
2771 
2772 /*
2773  * Common IP options parser: extract next option.
2774  */
2775 uint8_t
2776 ipoptp_next(ipoptp_t *optp)
2777 {
2778 	uint8_t *end = optp->ipoptp_end;
2779 	uint8_t *cur = optp->ipoptp_next;
2780 	uint8_t opt, len, pointer;
2781 
2782 	/*
2783 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2784 	 * has been corrupted.
2785 	 */
2786 	ASSERT(cur <= end);
2787 
2788 	if (cur == end)
2789 		return (IPOPT_EOL);
2790 
2791 	opt = cur[IPOPT_OPTVAL];
2792 
2793 	/*
2794 	 * Skip any NOP options.
2795 	 */
2796 	while (opt == IPOPT_NOP) {
2797 		cur++;
2798 		if (cur == end)
2799 			return (IPOPT_EOL);
2800 		opt = cur[IPOPT_OPTVAL];
2801 	}
2802 
2803 	if (opt == IPOPT_EOL)
2804 		return (IPOPT_EOL);
2805 
2806 	/*
2807 	 * Option requiring a length.
2808 	 */
2809 	if ((cur + 1) >= end) {
2810 		optp->ipoptp_flags |= IPOPTP_ERROR;
2811 		return (IPOPT_EOL);
2812 	}
2813 	len = cur[IPOPT_OLEN];
2814 	if (len < 2) {
2815 		optp->ipoptp_flags |= IPOPTP_ERROR;
2816 		return (IPOPT_EOL);
2817 	}
2818 	optp->ipoptp_cur = cur;
2819 	optp->ipoptp_len = len;
2820 	optp->ipoptp_next = cur + len;
2821 	if (cur + len > end) {
2822 		optp->ipoptp_flags |= IPOPTP_ERROR;
2823 		return (IPOPT_EOL);
2824 	}
2825 
2826 	/*
2827 	 * For the options which require a pointer field, make sure
2828 	 * its there, and make sure it points to either something
2829 	 * inside this option, or the end of the option.
2830 	 */
2831 	switch (opt) {
2832 	case IPOPT_RR:
2833 	case IPOPT_TS:
2834 	case IPOPT_LSRR:
2835 	case IPOPT_SSRR:
2836 		if (len <= IPOPT_OFFSET) {
2837 			optp->ipoptp_flags |= IPOPTP_ERROR;
2838 			return (opt);
2839 		}
2840 		pointer = cur[IPOPT_OFFSET];
2841 		if (pointer - 1 > len) {
2842 			optp->ipoptp_flags |= IPOPTP_ERROR;
2843 			return (opt);
2844 		}
2845 		break;
2846 	}
2847 
2848 	/*
2849 	 * Sanity check the pointer field based on the type of the
2850 	 * option.
2851 	 */
2852 	switch (opt) {
2853 	case IPOPT_RR:
2854 	case IPOPT_SSRR:
2855 	case IPOPT_LSRR:
2856 		if (pointer < IPOPT_MINOFF_SR)
2857 			optp->ipoptp_flags |= IPOPTP_ERROR;
2858 		break;
2859 	case IPOPT_TS:
2860 		if (pointer < IPOPT_MINOFF_IT)
2861 			optp->ipoptp_flags |= IPOPTP_ERROR;
2862 		/*
2863 		 * Note that the Internet Timestamp option also
2864 		 * contains two four bit fields (the Overflow field,
2865 		 * and the Flag field), which follow the pointer
2866 		 * field.  We don't need to check that these fields
2867 		 * fall within the length of the option because this
2868 		 * was implicitely done above.  We've checked that the
2869 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2870 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2871 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2872 		 */
2873 		ASSERT(len > IPOPT_POS_OV_FLG);
2874 		break;
2875 	}
2876 
2877 	return (opt);
2878 }
2879 
2880 /*
2881  * Use the outgoing IP header to create an IP_OPTIONS option the way
2882  * it was passed down from the application.
2883  */
2884 int
2885 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2886 {
2887 	ipoptp_t	opts;
2888 	const uchar_t	*opt;
2889 	uint8_t		optval;
2890 	uint8_t		optlen;
2891 	uint32_t	len = 0;
2892 	uchar_t	*buf1 = buf;
2893 
2894 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2895 	len += IP_ADDR_LEN;
2896 	bzero(buf1, IP_ADDR_LEN);
2897 
2898 	/*
2899 	 * OK to cast away const here, as we don't store through the returned
2900 	 * opts.ipoptp_cur pointer.
2901 	 */
2902 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2903 	    optval != IPOPT_EOL;
2904 	    optval = ipoptp_next(&opts)) {
2905 		int	off;
2906 
2907 		opt = opts.ipoptp_cur;
2908 		optlen = opts.ipoptp_len;
2909 		switch (optval) {
2910 		case IPOPT_SSRR:
2911 		case IPOPT_LSRR:
2912 
2913 			/*
2914 			 * Insert ipha_dst as the first entry in the source
2915 			 * route and move down the entries on step.
2916 			 * The last entry gets placed at buf1.
2917 			 */
2918 			buf[IPOPT_OPTVAL] = optval;
2919 			buf[IPOPT_OLEN] = optlen;
2920 			buf[IPOPT_OFFSET] = optlen;
2921 
2922 			off = optlen - IP_ADDR_LEN;
2923 			if (off < 0) {
2924 				/* No entries in source route */
2925 				break;
2926 			}
2927 			/* Last entry in source route */
2928 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2929 			off -= IP_ADDR_LEN;
2930 
2931 			while (off > 0) {
2932 				bcopy(opt + off,
2933 				    buf + off + IP_ADDR_LEN,
2934 				    IP_ADDR_LEN);
2935 				off -= IP_ADDR_LEN;
2936 			}
2937 			/* ipha_dst into first slot */
2938 			bcopy(&ipha->ipha_dst,
2939 			    buf + off + IP_ADDR_LEN,
2940 			    IP_ADDR_LEN);
2941 			buf += optlen;
2942 			len += optlen;
2943 			break;
2944 
2945 		case IPOPT_COMSEC:
2946 		case IPOPT_SECURITY:
2947 			/* if passing up a label is not ok, then remove */
2948 			if (is_system_labeled())
2949 				break;
2950 			/* FALLTHROUGH */
2951 		default:
2952 			bcopy(opt, buf, optlen);
2953 			buf += optlen;
2954 			len += optlen;
2955 			break;
2956 		}
2957 	}
2958 done:
2959 	/* Pad the resulting options */
2960 	while (len & 0x3) {
2961 		*buf++ = IPOPT_EOL;
2962 		len++;
2963 	}
2964 	return (len);
2965 }
2966 
2967 /*
2968  * Update any record route or timestamp options to include this host.
2969  * Reverse any source route option.
2970  * This routine assumes that the options are well formed i.e. that they
2971  * have already been checked.
2972  */
2973 static void
2974 icmp_options_update(ipha_t *ipha)
2975 {
2976 	ipoptp_t	opts;
2977 	uchar_t		*opt;
2978 	uint8_t		optval;
2979 	ipaddr_t	src;		/* Our local address */
2980 	ipaddr_t	dst;
2981 
2982 	ip2dbg(("icmp_options_update\n"));
2983 	src = ipha->ipha_src;
2984 	dst = ipha->ipha_dst;
2985 
2986 	for (optval = ipoptp_first(&opts, ipha);
2987 	    optval != IPOPT_EOL;
2988 	    optval = ipoptp_next(&opts)) {
2989 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2990 		opt = opts.ipoptp_cur;
2991 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2992 		    optval, opts.ipoptp_len));
2993 		switch (optval) {
2994 			int off1, off2;
2995 		case IPOPT_SSRR:
2996 		case IPOPT_LSRR:
2997 			/*
2998 			 * Reverse the source route.  The first entry
2999 			 * should be the next to last one in the current
3000 			 * source route (the last entry is our address).
3001 			 * The last entry should be the final destination.
3002 			 */
3003 			off1 = IPOPT_MINOFF_SR - 1;
3004 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3005 			if (off2 < 0) {
3006 				/* No entries in source route */
3007 				ip1dbg((
3008 				    "icmp_options_update: bad src route\n"));
3009 				break;
3010 			}
3011 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3012 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3013 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3014 			off2 -= IP_ADDR_LEN;
3015 
3016 			while (off1 < off2) {
3017 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3018 				bcopy((char *)opt + off2, (char *)opt + off1,
3019 				    IP_ADDR_LEN);
3020 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3021 				off1 += IP_ADDR_LEN;
3022 				off2 -= IP_ADDR_LEN;
3023 			}
3024 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3025 			break;
3026 		}
3027 	}
3028 }
3029 
3030 /*
3031  * Process received ICMP Redirect messages.
3032  */
3033 static void
3034 icmp_redirect(ill_t *ill, mblk_t *mp)
3035 {
3036 	ipha_t	*ipha;
3037 	int	iph_hdr_length;
3038 	icmph_t	*icmph;
3039 	ipha_t	*ipha_err;
3040 	ire_t	*ire;
3041 	ire_t	*prev_ire;
3042 	ire_t	*save_ire;
3043 	ipaddr_t  src, dst, gateway;
3044 	iulp_t	ulp_info = { 0 };
3045 	int	error;
3046 	ip_stack_t *ipst;
3047 
3048 	ASSERT(ill != NULL);
3049 	ipst = ill->ill_ipst;
3050 
3051 	ipha = (ipha_t *)mp->b_rptr;
3052 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3053 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3054 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3055 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3056 		freemsg(mp);
3057 		return;
3058 	}
3059 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3060 	ipha_err = (ipha_t *)&icmph[1];
3061 	src = ipha->ipha_src;
3062 	dst = ipha_err->ipha_dst;
3063 	gateway = icmph->icmph_rd_gateway;
3064 	/* Make sure the new gateway is reachable somehow. */
3065 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3066 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3067 	/*
3068 	 * Make sure we had a route for the dest in question and that
3069 	 * that route was pointing to the old gateway (the source of the
3070 	 * redirect packet.)
3071 	 */
3072 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3073 	    NULL, MATCH_IRE_GW, ipst);
3074 	/*
3075 	 * Check that
3076 	 *	the redirect was not from ourselves
3077 	 *	the new gateway and the old gateway are directly reachable
3078 	 */
3079 	if (!prev_ire ||
3080 	    !ire ||
3081 	    ire->ire_type == IRE_LOCAL) {
3082 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3083 		freemsg(mp);
3084 		if (ire != NULL)
3085 			ire_refrele(ire);
3086 		if (prev_ire != NULL)
3087 			ire_refrele(prev_ire);
3088 		return;
3089 	}
3090 
3091 	/*
3092 	 * Should we use the old ULP info to create the new gateway?  From
3093 	 * a user's perspective, we should inherit the info so that it
3094 	 * is a "smooth" transition.  If we do not do that, then new
3095 	 * connections going thru the new gateway will have no route metrics,
3096 	 * which is counter-intuitive to user.  From a network point of
3097 	 * view, this may or may not make sense even though the new gateway
3098 	 * is still directly connected to us so the route metrics should not
3099 	 * change much.
3100 	 *
3101 	 * But if the old ire_uinfo is not initialized, we do another
3102 	 * recursive lookup on the dest using the new gateway.  There may
3103 	 * be a route to that.  If so, use it to initialize the redirect
3104 	 * route.
3105 	 */
3106 	if (prev_ire->ire_uinfo.iulp_set) {
3107 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3108 	} else {
3109 		ire_t *tmp_ire;
3110 		ire_t *sire;
3111 
3112 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3113 		    ALL_ZONES, 0, NULL,
3114 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3115 		    ipst);
3116 		if (sire != NULL) {
3117 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3118 			/*
3119 			 * If sire != NULL, ire_ftable_lookup() should not
3120 			 * return a NULL value.
3121 			 */
3122 			ASSERT(tmp_ire != NULL);
3123 			ire_refrele(tmp_ire);
3124 			ire_refrele(sire);
3125 		} else if (tmp_ire != NULL) {
3126 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3127 			    sizeof (iulp_t));
3128 			ire_refrele(tmp_ire);
3129 		}
3130 	}
3131 	if (prev_ire->ire_type == IRE_CACHE)
3132 		ire_delete(prev_ire);
3133 	ire_refrele(prev_ire);
3134 	/*
3135 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3136 	 * require TOS routing
3137 	 */
3138 	switch (icmph->icmph_code) {
3139 	case 0:
3140 	case 1:
3141 		/* TODO: TOS specificity for cases 2 and 3 */
3142 	case 2:
3143 	case 3:
3144 		break;
3145 	default:
3146 		freemsg(mp);
3147 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3148 		ire_refrele(ire);
3149 		return;
3150 	}
3151 	/*
3152 	 * Create a Route Association.  This will allow us to remember that
3153 	 * someone we believe told us to use the particular gateway.
3154 	 */
3155 	save_ire = ire;
3156 	ire = ire_create(
3157 	    (uchar_t *)&dst,			/* dest addr */
3158 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3159 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3160 	    (uchar_t *)&gateway,		/* gateway addr */
3161 	    &save_ire->ire_max_frag,		/* max frag */
3162 	    NULL,				/* no src nce */
3163 	    NULL,				/* no rfq */
3164 	    NULL,				/* no stq */
3165 	    IRE_HOST,
3166 	    NULL,				/* ipif */
3167 	    0,					/* cmask */
3168 	    0,					/* phandle */
3169 	    0,					/* ihandle */
3170 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3171 	    &ulp_info,
3172 	    NULL,				/* tsol_gc_t */
3173 	    NULL,				/* gcgrp */
3174 	    ipst);
3175 
3176 	if (ire == NULL) {
3177 		freemsg(mp);
3178 		ire_refrele(save_ire);
3179 		return;
3180 	}
3181 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3182 	ire_refrele(save_ire);
3183 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3184 
3185 	if (error == 0) {
3186 		ire_refrele(ire);		/* Held in ire_add_v4 */
3187 		/* tell routing sockets that we received a redirect */
3188 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3189 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3190 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3191 	}
3192 
3193 	/*
3194 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3195 	 * This together with the added IRE has the effect of
3196 	 * modifying an existing redirect.
3197 	 */
3198 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3199 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3200 	if (prev_ire != NULL) {
3201 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3202 			ire_delete(prev_ire);
3203 		ire_refrele(prev_ire);
3204 	}
3205 
3206 	freemsg(mp);
3207 }
3208 
3209 /*
3210  * Generate an ICMP parameter problem message.
3211  */
3212 static void
3213 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3214 	ip_stack_t *ipst)
3215 {
3216 	icmph_t	icmph;
3217 	boolean_t mctl_present;
3218 	mblk_t *first_mp;
3219 
3220 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3221 
3222 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3223 		if (mctl_present)
3224 			freeb(first_mp);
3225 		return;
3226 	}
3227 
3228 	bzero(&icmph, sizeof (icmph_t));
3229 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3230 	icmph.icmph_pp_ptr = ptr;
3231 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3232 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3233 	    ipst);
3234 }
3235 
3236 /*
3237  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3238  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3239  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3240  * an icmp error packet can be sent.
3241  * Assigns an appropriate source address to the packet. If ipha_dst is
3242  * one of our addresses use it for source. Otherwise pick a source based
3243  * on a route lookup back to ipha_src.
3244  * Note that ipha_src must be set here since the
3245  * packet is likely to arrive on an ill queue in ip_wput() which will
3246  * not set a source address.
3247  */
3248 static void
3249 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3250     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3251 {
3252 	ipaddr_t dst;
3253 	icmph_t	*icmph;
3254 	ipha_t	*ipha;
3255 	uint_t	len_needed;
3256 	size_t	msg_len;
3257 	mblk_t	*mp1;
3258 	ipaddr_t src;
3259 	ire_t	*ire;
3260 	mblk_t *ipsec_mp;
3261 	ipsec_out_t	*io = NULL;
3262 
3263 	if (mctl_present) {
3264 		/*
3265 		 * If it is :
3266 		 *
3267 		 * 1) a IPSEC_OUT, then this is caused by outbound
3268 		 *    datagram originating on this host. IPsec processing
3269 		 *    may or may not have been done. Refer to comments above
3270 		 *    icmp_inbound_error_fanout for details.
3271 		 *
3272 		 * 2) a IPSEC_IN if we are generating a icmp_message
3273 		 *    for an incoming datagram destined for us i.e called
3274 		 *    from ip_fanout_send_icmp.
3275 		 */
3276 		ipsec_info_t *in;
3277 		ipsec_mp = mp;
3278 		mp = ipsec_mp->b_cont;
3279 
3280 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3281 		ipha = (ipha_t *)mp->b_rptr;
3282 
3283 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3284 		    in->ipsec_info_type == IPSEC_IN);
3285 
3286 		if (in->ipsec_info_type == IPSEC_IN) {
3287 			/*
3288 			 * Convert the IPSEC_IN to IPSEC_OUT.
3289 			 */
3290 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3291 				BUMP_MIB(&ipst->ips_ip_mib,
3292 				    ipIfStatsOutDiscards);
3293 				return;
3294 			}
3295 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3296 		} else {
3297 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3298 			io = (ipsec_out_t *)in;
3299 			/*
3300 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3301 			 * ire lookup.
3302 			 */
3303 			io->ipsec_out_proc_begin = B_FALSE;
3304 		}
3305 		ASSERT(zoneid == io->ipsec_out_zoneid);
3306 		ASSERT(zoneid != ALL_ZONES);
3307 	} else {
3308 		/*
3309 		 * This is in clear. The icmp message we are building
3310 		 * here should go out in clear.
3311 		 *
3312 		 * Pardon the convolution of it all, but it's easier to
3313 		 * allocate a "use cleartext" IPSEC_IN message and convert
3314 		 * it than it is to allocate a new one.
3315 		 */
3316 		ipsec_in_t *ii;
3317 		ASSERT(DB_TYPE(mp) == M_DATA);
3318 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3319 		if (ipsec_mp == NULL) {
3320 			freemsg(mp);
3321 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3322 			return;
3323 		}
3324 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3325 
3326 		/* This is not a secure packet */
3327 		ii->ipsec_in_secure = B_FALSE;
3328 		/*
3329 		 * For trusted extensions using a shared IP address we can
3330 		 * send using any zoneid.
3331 		 */
3332 		if (zoneid == ALL_ZONES)
3333 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3334 		else
3335 			ii->ipsec_in_zoneid = zoneid;
3336 		ipsec_mp->b_cont = mp;
3337 		ipha = (ipha_t *)mp->b_rptr;
3338 		/*
3339 		 * Convert the IPSEC_IN to IPSEC_OUT.
3340 		 */
3341 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3342 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3343 			return;
3344 		}
3345 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3346 	}
3347 
3348 	/* Remember our eventual destination */
3349 	dst = ipha->ipha_src;
3350 
3351 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3352 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3353 	if (ire != NULL &&
3354 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3355 		src = ipha->ipha_dst;
3356 	} else {
3357 		if (ire != NULL)
3358 			ire_refrele(ire);
3359 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3360 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3361 		    ipst);
3362 		if (ire == NULL) {
3363 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3364 			freemsg(ipsec_mp);
3365 			return;
3366 		}
3367 		src = ire->ire_src_addr;
3368 	}
3369 
3370 	if (ire != NULL)
3371 		ire_refrele(ire);
3372 
3373 	/*
3374 	 * Check if we can send back more then 8 bytes in addition to
3375 	 * the IP header.  We try to send 64 bytes of data and the internal
3376 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3377 	 */
3378 	len_needed = IPH_HDR_LENGTH(ipha);
3379 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3380 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3381 
3382 		if (!pullupmsg(mp, -1)) {
3383 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3384 			freemsg(ipsec_mp);
3385 			return;
3386 		}
3387 		ipha = (ipha_t *)mp->b_rptr;
3388 
3389 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3390 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3391 			    len_needed));
3392 		} else {
3393 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3394 
3395 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3396 			len_needed += ip_hdr_length_v6(mp, ip6h);
3397 		}
3398 	}
3399 	len_needed += ipst->ips_ip_icmp_return;
3400 	msg_len = msgdsize(mp);
3401 	if (msg_len > len_needed) {
3402 		(void) adjmsg(mp, len_needed - msg_len);
3403 		msg_len = len_needed;
3404 	}
3405 	/* Make sure we propagate the cred/label for TX */
3406 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3407 	if (mp1 == NULL) {
3408 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3409 		freemsg(ipsec_mp);
3410 		return;
3411 	}
3412 	mp1->b_cont = mp;
3413 	mp = mp1;
3414 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3415 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3416 	    io->ipsec_out_type == IPSEC_OUT);
3417 	ipsec_mp->b_cont = mp;
3418 
3419 	/*
3420 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3421 	 * node generates be accepted in peace by all on-host destinations.
3422 	 * If we do NOT assume that all on-host destinations trust
3423 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3424 	 * (Look for ipsec_out_icmp_loopback).
3425 	 */
3426 	io->ipsec_out_icmp_loopback = B_TRUE;
3427 
3428 	ipha = (ipha_t *)mp->b_rptr;
3429 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3430 	*ipha = icmp_ipha;
3431 	ipha->ipha_src = src;
3432 	ipha->ipha_dst = dst;
3433 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3434 	msg_len += sizeof (icmp_ipha) + len;
3435 	if (msg_len > IP_MAXPACKET) {
3436 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3437 		msg_len = IP_MAXPACKET;
3438 	}
3439 	ipha->ipha_length = htons((uint16_t)msg_len);
3440 	icmph = (icmph_t *)&ipha[1];
3441 	bcopy(stuff, icmph, len);
3442 	icmph->icmph_checksum = 0;
3443 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3444 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3445 	put(q, ipsec_mp);
3446 }
3447 
3448 /*
3449  * Determine if an ICMP error packet can be sent given the rate limit.
3450  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3451  * in milliseconds) and a burst size. Burst size number of packets can
3452  * be sent arbitrarely closely spaced.
3453  * The state is tracked using two variables to implement an approximate
3454  * token bucket filter:
3455  *	icmp_pkt_err_last - lbolt value when the last burst started
3456  *	icmp_pkt_err_sent - number of packets sent in current burst
3457  */
3458 boolean_t
3459 icmp_err_rate_limit(ip_stack_t *ipst)
3460 {
3461 	clock_t now = TICK_TO_MSEC(lbolt);
3462 	uint_t refilled; /* Number of packets refilled in tbf since last */
3463 	/* Guard against changes by loading into local variable */
3464 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3465 
3466 	if (err_interval == 0)
3467 		return (B_FALSE);
3468 
3469 	if (ipst->ips_icmp_pkt_err_last > now) {
3470 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3471 		ipst->ips_icmp_pkt_err_last = 0;
3472 		ipst->ips_icmp_pkt_err_sent = 0;
3473 	}
3474 	/*
3475 	 * If we are in a burst update the token bucket filter.
3476 	 * Update the "last" time to be close to "now" but make sure
3477 	 * we don't loose precision.
3478 	 */
3479 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3480 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3481 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3482 			ipst->ips_icmp_pkt_err_sent = 0;
3483 		} else {
3484 			ipst->ips_icmp_pkt_err_sent -= refilled;
3485 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3486 		}
3487 	}
3488 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3489 		/* Start of new burst */
3490 		ipst->ips_icmp_pkt_err_last = now;
3491 	}
3492 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3493 		ipst->ips_icmp_pkt_err_sent++;
3494 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3495 		    ipst->ips_icmp_pkt_err_sent));
3496 		return (B_FALSE);
3497 	}
3498 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3499 	return (B_TRUE);
3500 }
3501 
3502 /*
3503  * Check if it is ok to send an IPv4 ICMP error packet in
3504  * response to the IPv4 packet in mp.
3505  * Free the message and return null if no
3506  * ICMP error packet should be sent.
3507  */
3508 static mblk_t *
3509 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3510 {
3511 	icmph_t	*icmph;
3512 	ipha_t	*ipha;
3513 	uint_t	len_needed;
3514 	ire_t	*src_ire;
3515 	ire_t	*dst_ire;
3516 
3517 	if (!mp)
3518 		return (NULL);
3519 	ipha = (ipha_t *)mp->b_rptr;
3520 	if (ip_csum_hdr(ipha)) {
3521 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3522 		freemsg(mp);
3523 		return (NULL);
3524 	}
3525 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3526 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3527 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3528 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3529 	if (src_ire != NULL || dst_ire != NULL ||
3530 	    CLASSD(ipha->ipha_dst) ||
3531 	    CLASSD(ipha->ipha_src) ||
3532 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3533 		/* Note: only errors to the fragment with offset 0 */
3534 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3535 		freemsg(mp);
3536 		if (src_ire != NULL)
3537 			ire_refrele(src_ire);
3538 		if (dst_ire != NULL)
3539 			ire_refrele(dst_ire);
3540 		return (NULL);
3541 	}
3542 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3543 		/*
3544 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3545 		 * errors in response to any ICMP errors.
3546 		 */
3547 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3548 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3549 			if (!pullupmsg(mp, len_needed)) {
3550 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3551 				freemsg(mp);
3552 				return (NULL);
3553 			}
3554 			ipha = (ipha_t *)mp->b_rptr;
3555 		}
3556 		icmph = (icmph_t *)
3557 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3558 		switch (icmph->icmph_type) {
3559 		case ICMP_DEST_UNREACHABLE:
3560 		case ICMP_SOURCE_QUENCH:
3561 		case ICMP_TIME_EXCEEDED:
3562 		case ICMP_PARAM_PROBLEM:
3563 		case ICMP_REDIRECT:
3564 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3565 			freemsg(mp);
3566 			return (NULL);
3567 		default:
3568 			break;
3569 		}
3570 	}
3571 	/*
3572 	 * If this is a labeled system, then check to see if we're allowed to
3573 	 * send a response to this particular sender.  If not, then just drop.
3574 	 */
3575 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3576 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3577 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3578 		freemsg(mp);
3579 		return (NULL);
3580 	}
3581 	if (icmp_err_rate_limit(ipst)) {
3582 		/*
3583 		 * Only send ICMP error packets every so often.
3584 		 * This should be done on a per port/source basis,
3585 		 * but for now this will suffice.
3586 		 */
3587 		freemsg(mp);
3588 		return (NULL);
3589 	}
3590 	return (mp);
3591 }
3592 
3593 /*
3594  * Generate an ICMP redirect message.
3595  */
3596 static void
3597 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3598 {
3599 	icmph_t	icmph;
3600 
3601 	/*
3602 	 * We are called from ip_rput where we could
3603 	 * not have attached an IPSEC_IN.
3604 	 */
3605 	ASSERT(mp->b_datap->db_type == M_DATA);
3606 
3607 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3608 		return;
3609 	}
3610 
3611 	bzero(&icmph, sizeof (icmph_t));
3612 	icmph.icmph_type = ICMP_REDIRECT;
3613 	icmph.icmph_code = 1;
3614 	icmph.icmph_rd_gateway = gateway;
3615 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3616 	/* Redirects sent by router, and router is global zone */
3617 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3618 }
3619 
3620 /*
3621  * Generate an ICMP time exceeded message.
3622  */
3623 void
3624 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3625     ip_stack_t *ipst)
3626 {
3627 	icmph_t	icmph;
3628 	boolean_t mctl_present;
3629 	mblk_t *first_mp;
3630 
3631 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3632 
3633 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3634 		if (mctl_present)
3635 			freeb(first_mp);
3636 		return;
3637 	}
3638 
3639 	bzero(&icmph, sizeof (icmph_t));
3640 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3641 	icmph.icmph_code = code;
3642 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3643 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3644 	    ipst);
3645 }
3646 
3647 /*
3648  * Generate an ICMP unreachable message.
3649  */
3650 void
3651 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3652     ip_stack_t *ipst)
3653 {
3654 	icmph_t	icmph;
3655 	mblk_t *first_mp;
3656 	boolean_t mctl_present;
3657 
3658 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3659 
3660 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3661 		if (mctl_present)
3662 			freeb(first_mp);
3663 		return;
3664 	}
3665 
3666 	bzero(&icmph, sizeof (icmph_t));
3667 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3668 	icmph.icmph_code = code;
3669 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3670 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3671 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3672 	    zoneid, ipst);
3673 }
3674 
3675 /*
3676  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3677  * duplicate.  As long as someone else holds the address, the interface will
3678  * stay down.  When that conflict goes away, the interface is brought back up.
3679  * This is done so that accidental shutdowns of addresses aren't made
3680  * permanent.  Your server will recover from a failure.
3681  *
3682  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3683  * user space process (dhcpagent).
3684  *
3685  * Recovery completes if ARP reports that the address is now ours (via
3686  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3687  *
3688  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3689  */
3690 static void
3691 ipif_dup_recovery(void *arg)
3692 {
3693 	ipif_t *ipif = arg;
3694 	ill_t *ill = ipif->ipif_ill;
3695 	mblk_t *arp_add_mp;
3696 	mblk_t *arp_del_mp;
3697 	ip_stack_t *ipst = ill->ill_ipst;
3698 
3699 	ipif->ipif_recovery_id = 0;
3700 
3701 	/*
3702 	 * No lock needed for moving or condemned check, as this is just an
3703 	 * optimization.
3704 	 */
3705 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3706 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3707 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3708 		/* No reason to try to bring this address back. */
3709 		return;
3710 	}
3711 
3712 	/* ACE_F_UNVERIFIED restarts DAD */
3713 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3714 		goto alloc_fail;
3715 
3716 	if (ipif->ipif_arp_del_mp == NULL) {
3717 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3718 			goto alloc_fail;
3719 		ipif->ipif_arp_del_mp = arp_del_mp;
3720 	}
3721 
3722 	putnext(ill->ill_rq, arp_add_mp);
3723 	return;
3724 
3725 alloc_fail:
3726 	/*
3727 	 * On allocation failure, just restart the timer.  Note that the ipif
3728 	 * is down here, so no other thread could be trying to start a recovery
3729 	 * timer.  The ill_lock protects the condemned flag and the recovery
3730 	 * timer ID.
3731 	 */
3732 	freemsg(arp_add_mp);
3733 	mutex_enter(&ill->ill_lock);
3734 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3735 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3736 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3737 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3738 	}
3739 	mutex_exit(&ill->ill_lock);
3740 }
3741 
3742 /*
3743  * This is for exclusive changes due to ARP.  Either tear down an interface due
3744  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3745  */
3746 /* ARGSUSED */
3747 static void
3748 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3749 {
3750 	ill_t	*ill = rq->q_ptr;
3751 	arh_t *arh;
3752 	ipaddr_t src;
3753 	ipif_t	*ipif;
3754 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3755 	char hbuf[MAC_STR_LEN];
3756 	char sbuf[INET_ADDRSTRLEN];
3757 	const char *failtype;
3758 	boolean_t bring_up;
3759 	ip_stack_t *ipst = ill->ill_ipst;
3760 
3761 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3762 	case AR_CN_READY:
3763 		failtype = NULL;
3764 		bring_up = B_TRUE;
3765 		break;
3766 	case AR_CN_FAILED:
3767 		failtype = "in use";
3768 		bring_up = B_FALSE;
3769 		break;
3770 	default:
3771 		failtype = "claimed";
3772 		bring_up = B_FALSE;
3773 		break;
3774 	}
3775 
3776 	arh = (arh_t *)mp->b_cont->b_rptr;
3777 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3778 
3779 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3780 	    sizeof (hbuf));
3781 	(void) ip_dot_addr(src, sbuf);
3782 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3783 
3784 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3785 		    ipif->ipif_lcl_addr != src) {
3786 			continue;
3787 		}
3788 
3789 		/*
3790 		 * If we failed on a recovery probe, then restart the timer to
3791 		 * try again later.
3792 		 */
3793 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3794 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3795 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3796 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3797 		    ipst->ips_ip_dup_recovery > 0 &&
3798 		    ipif->ipif_recovery_id == 0) {
3799 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3800 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3801 			continue;
3802 		}
3803 
3804 		/*
3805 		 * If what we're trying to do has already been done, then do
3806 		 * nothing.
3807 		 */
3808 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3809 			continue;
3810 
3811 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3812 
3813 		if (failtype == NULL) {
3814 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3815 			    ibuf);
3816 		} else {
3817 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3818 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3819 		}
3820 
3821 		if (bring_up) {
3822 			ASSERT(ill->ill_dl_up);
3823 			/*
3824 			 * Free up the ARP delete message so we can allocate
3825 			 * a fresh one through the normal path.
3826 			 */
3827 			freemsg(ipif->ipif_arp_del_mp);
3828 			ipif->ipif_arp_del_mp = NULL;
3829 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3830 			    EINPROGRESS) {
3831 				ipif->ipif_addr_ready = 1;
3832 				(void) ipif_up_done(ipif);
3833 				ASSERT(ill->ill_move_ipif == NULL);
3834 			}
3835 			continue;
3836 		}
3837 
3838 		mutex_enter(&ill->ill_lock);
3839 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3840 		ipif->ipif_flags |= IPIF_DUPLICATE;
3841 		ill->ill_ipif_dup_count++;
3842 		mutex_exit(&ill->ill_lock);
3843 		/*
3844 		 * Already exclusive on the ill; no need to handle deferred
3845 		 * processing here.
3846 		 */
3847 		(void) ipif_down(ipif, NULL, NULL);
3848 		ipif_down_tail(ipif);
3849 		mutex_enter(&ill->ill_lock);
3850 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3851 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3852 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3853 		    ipst->ips_ip_dup_recovery > 0) {
3854 			ASSERT(ipif->ipif_recovery_id == 0);
3855 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3856 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3857 		}
3858 		mutex_exit(&ill->ill_lock);
3859 	}
3860 	freemsg(mp);
3861 }
3862 
3863 /* ARGSUSED */
3864 static void
3865 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3866 {
3867 	ill_t	*ill = rq->q_ptr;
3868 	arh_t *arh;
3869 	ipaddr_t src;
3870 	ipif_t	*ipif;
3871 
3872 	arh = (arh_t *)mp->b_cont->b_rptr;
3873 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3874 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3875 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3876 			(void) ipif_resolver_up(ipif, Res_act_defend);
3877 	}
3878 	freemsg(mp);
3879 }
3880 
3881 /*
3882  * News from ARP.  ARP sends notification of interesting events down
3883  * to its clients using M_CTL messages with the interesting ARP packet
3884  * attached via b_cont.
3885  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3886  * queue as opposed to ARP sending the message to all the clients, i.e. all
3887  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3888  * table if a cache IRE is found to delete all the entries for the address in
3889  * the packet.
3890  */
3891 static void
3892 ip_arp_news(queue_t *q, mblk_t *mp)
3893 {
3894 	arcn_t		*arcn;
3895 	arh_t		*arh;
3896 	ire_t		*ire = NULL;
3897 	char		hbuf[MAC_STR_LEN];
3898 	char		sbuf[INET_ADDRSTRLEN];
3899 	ipaddr_t	src;
3900 	in6_addr_t	v6src;
3901 	boolean_t	isv6 = B_FALSE;
3902 	ipif_t		*ipif;
3903 	ill_t		*ill;
3904 	ip_stack_t	*ipst;
3905 
3906 	if (CONN_Q(q)) {
3907 		conn_t *connp = Q_TO_CONN(q);
3908 
3909 		ipst = connp->conn_netstack->netstack_ip;
3910 	} else {
3911 		ill_t *ill = (ill_t *)q->q_ptr;
3912 
3913 		ipst = ill->ill_ipst;
3914 	}
3915 
3916 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3917 		if (q->q_next) {
3918 			putnext(q, mp);
3919 		} else
3920 			freemsg(mp);
3921 		return;
3922 	}
3923 	arh = (arh_t *)mp->b_cont->b_rptr;
3924 	/* Is it one we are interested in? */
3925 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3926 		isv6 = B_TRUE;
3927 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3928 		    IPV6_ADDR_LEN);
3929 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3930 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3931 		    IP_ADDR_LEN);
3932 	} else {
3933 		freemsg(mp);
3934 		return;
3935 	}
3936 
3937 	ill = q->q_ptr;
3938 
3939 	arcn = (arcn_t *)mp->b_rptr;
3940 	switch (arcn->arcn_code) {
3941 	case AR_CN_BOGON:
3942 		/*
3943 		 * Someone is sending ARP packets with a source protocol
3944 		 * address that we have published and for which we believe our
3945 		 * entry is authoritative and (when ill_arp_extend is set)
3946 		 * verified to be unique on the network.
3947 		 *
3948 		 * The ARP module internally handles the cases where the sender
3949 		 * is just probing (for DAD) and where the hardware address of
3950 		 * a non-authoritative entry has changed.  Thus, these are the
3951 		 * real conflicts, and we have to do resolution.
3952 		 *
3953 		 * We back away quickly from the address if it's from DHCP or
3954 		 * otherwise temporary and hasn't been used recently (or at
3955 		 * all).  We'd like to include "deprecated" addresses here as
3956 		 * well (as there's no real reason to defend something we're
3957 		 * discarding), but IPMP "reuses" this flag to mean something
3958 		 * other than the standard meaning.
3959 		 *
3960 		 * If the ARP module above is not extended (meaning that it
3961 		 * doesn't know how to defend the address), then we just log
3962 		 * the problem as we always did and continue on.  It's not
3963 		 * right, but there's little else we can do, and those old ATM
3964 		 * users are going away anyway.
3965 		 */
3966 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3967 		    hbuf, sizeof (hbuf));
3968 		(void) ip_dot_addr(src, sbuf);
3969 		if (isv6) {
3970 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3971 			    ipst);
3972 		} else {
3973 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3974 		}
3975 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3976 			uint32_t now;
3977 			uint32_t maxage;
3978 			clock_t lused;
3979 			uint_t maxdefense;
3980 			uint_t defs;
3981 
3982 			/*
3983 			 * First, figure out if this address hasn't been used
3984 			 * in a while.  If it hasn't, then it's a better
3985 			 * candidate for abandoning.
3986 			 */
3987 			ipif = ire->ire_ipif;
3988 			ASSERT(ipif != NULL);
3989 			now = gethrestime_sec();
3990 			maxage = now - ire->ire_create_time;
3991 			if (maxage > ipst->ips_ip_max_temp_idle)
3992 				maxage = ipst->ips_ip_max_temp_idle;
3993 			lused = drv_hztousec(ddi_get_lbolt() -
3994 			    ire->ire_last_used_time) / MICROSEC + 1;
3995 			if (lused >= maxage && (ipif->ipif_flags &
3996 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3997 				maxdefense = ipst->ips_ip_max_temp_defend;
3998 			else
3999 				maxdefense = ipst->ips_ip_max_defend;
4000 
4001 			/*
4002 			 * Now figure out how many times we've defended
4003 			 * ourselves.  Ignore defenses that happened long in
4004 			 * the past.
4005 			 */
4006 			mutex_enter(&ire->ire_lock);
4007 			if ((defs = ire->ire_defense_count) > 0 &&
4008 			    now - ire->ire_defense_time >
4009 			    ipst->ips_ip_defend_interval) {
4010 				ire->ire_defense_count = defs = 0;
4011 			}
4012 			ire->ire_defense_count++;
4013 			ire->ire_defense_time = now;
4014 			mutex_exit(&ire->ire_lock);
4015 			ill_refhold(ill);
4016 			ire_refrele(ire);
4017 
4018 			/*
4019 			 * If we've defended ourselves too many times already,
4020 			 * then give up and tear down the interface(s) using
4021 			 * this address.  Otherwise, defend by sending out a
4022 			 * gratuitous ARP.
4023 			 */
4024 			if (defs >= maxdefense && ill->ill_arp_extend) {
4025 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4026 				    B_FALSE);
4027 			} else {
4028 				cmn_err(CE_WARN,
4029 				    "node %s is using our IP address %s on %s",
4030 				    hbuf, sbuf, ill->ill_name);
4031 				/*
4032 				 * If this is an old (ATM) ARP module, then
4033 				 * don't try to defend the address.  Remain
4034 				 * compatible with the old behavior.  Defend
4035 				 * only with new ARP.
4036 				 */
4037 				if (ill->ill_arp_extend) {
4038 					qwriter_ip(ill, q, mp, ip_arp_defend,
4039 					    NEW_OP, B_FALSE);
4040 				} else {
4041 					ill_refrele(ill);
4042 				}
4043 			}
4044 			return;
4045 		}
4046 		cmn_err(CE_WARN,
4047 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4048 		    hbuf, sbuf, ill->ill_name);
4049 		if (ire != NULL)
4050 			ire_refrele(ire);
4051 		break;
4052 	case AR_CN_ANNOUNCE:
4053 		if (isv6) {
4054 			/*
4055 			 * For XRESOLV interfaces.
4056 			 * Delete the IRE cache entry and NCE for this
4057 			 * v6 address
4058 			 */
4059 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4060 			/*
4061 			 * If v6src is a non-zero, it's a router address
4062 			 * as below. Do the same sort of thing to clean
4063 			 * out off-net IRE_CACHE entries that go through
4064 			 * the router.
4065 			 */
4066 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4067 				ire_walk_v6(ire_delete_cache_gw_v6,
4068 				    (char *)&v6src, ALL_ZONES, ipst);
4069 			}
4070 		} else {
4071 			nce_hw_map_t hwm;
4072 
4073 			/*
4074 			 * ARP gives us a copy of any packet where it thinks
4075 			 * the address has changed, so that we can update our
4076 			 * caches.  We're responsible for caching known answers
4077 			 * in the current design.  We check whether the
4078 			 * hardware address really has changed in all of our
4079 			 * entries that have cached this mapping, and if so, we
4080 			 * blow them away.  This way we will immediately pick
4081 			 * up the rare case of a host changing hardware
4082 			 * address.
4083 			 */
4084 			if (src == 0)
4085 				break;
4086 			hwm.hwm_addr = src;
4087 			hwm.hwm_hwlen = arh->arh_hlen;
4088 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4089 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4090 			ndp_walk_common(ipst->ips_ndp4, NULL,
4091 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4092 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4093 		}
4094 		break;
4095 	case AR_CN_READY:
4096 		/* No external v6 resolver has a contract to use this */
4097 		if (isv6)
4098 			break;
4099 		/* If the link is down, we'll retry this later */
4100 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4101 			break;
4102 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4103 		    NULL, NULL, ipst);
4104 		if (ipif != NULL) {
4105 			/*
4106 			 * If this is a duplicate recovery, then we now need to
4107 			 * go exclusive to bring this thing back up.
4108 			 */
4109 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4110 			    IPIF_DUPLICATE) {
4111 				ipif_refrele(ipif);
4112 				ill_refhold(ill);
4113 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4114 				    B_FALSE);
4115 				return;
4116 			}
4117 			/*
4118 			 * If this is the first notice that this address is
4119 			 * ready, then let the user know now.
4120 			 */
4121 			if ((ipif->ipif_flags & IPIF_UP) &&
4122 			    !ipif->ipif_addr_ready) {
4123 				ipif_mask_reply(ipif);
4124 				ipif_up_notify(ipif);
4125 			}
4126 			ipif->ipif_addr_ready = 1;
4127 			ipif_refrele(ipif);
4128 		}
4129 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4130 		if (ire != NULL) {
4131 			ire->ire_defense_count = 0;
4132 			ire_refrele(ire);
4133 		}
4134 		break;
4135 	case AR_CN_FAILED:
4136 		/* No external v6 resolver has a contract to use this */
4137 		if (isv6)
4138 			break;
4139 		if (!ill->ill_arp_extend) {
4140 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4141 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4142 			(void) ip_dot_addr(src, sbuf);
4143 
4144 			cmn_err(CE_WARN,
4145 			    "node %s is using our IP address %s on %s",
4146 			    hbuf, sbuf, ill->ill_name);
4147 			break;
4148 		}
4149 		ill_refhold(ill);
4150 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4151 		return;
4152 	}
4153 	freemsg(mp);
4154 }
4155 
4156 /*
4157  * Create a mblk suitable for carrying the interface index and/or source link
4158  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4159  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4160  * application.
4161  */
4162 mblk_t *
4163 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4164     ip_stack_t *ipst)
4165 {
4166 	mblk_t		*mp;
4167 	ip_pktinfo_t	*pinfo;
4168 	ipha_t 		*ipha;
4169 	struct ether_header *pether;
4170 	boolean_t	ipmp_ill_held = B_FALSE;
4171 
4172 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4173 	if (mp == NULL) {
4174 		ip1dbg(("ip_add_info: allocation failure.\n"));
4175 		return (data_mp);
4176 	}
4177 
4178 	ipha = (ipha_t *)data_mp->b_rptr;
4179 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4180 	bzero(pinfo, sizeof (ip_pktinfo_t));
4181 	pinfo->ip_pkt_flags = (uchar_t)flags;
4182 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4183 
4184 	pether = (struct ether_header *)((char *)ipha
4185 	    - sizeof (struct ether_header));
4186 
4187 	/*
4188 	 * Make sure the interface is an ethernet type, since this option
4189 	 * is currently supported only on this type of interface. Also make
4190 	 * sure we are pointing correctly above db_base.
4191 	 */
4192 	if ((flags & IPF_RECVSLLA) &&
4193 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4194 	    (ill->ill_type == IFT_ETHER) &&
4195 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4196 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4197 		bcopy(pether->ether_shost.ether_addr_octet,
4198 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4199 	} else {
4200 		/*
4201 		 * Clear the bit. Indicate to upper layer that IP is not
4202 		 * sending this ancillary info.
4203 		 */
4204 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4205 	}
4206 
4207 	/*
4208 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4209 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4210 	 * IPF_RECVADDR support on test addresses is not needed.)
4211 	 *
4212 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4213 	 * processing a packet looped back to an IPMP data address
4214 	 * (since those IRE_LOCALs are tied to IPMP ills).
4215 	 */
4216 	if (IS_UNDER_IPMP(ill)) {
4217 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4218 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4219 			freemsg(mp);
4220 			return (data_mp);
4221 		}
4222 		ipmp_ill_held = B_TRUE;
4223 	}
4224 
4225 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4226 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4227 	if (flags & IPF_RECVADDR) {
4228 		ipif_t	*ipif;
4229 		ire_t	*ire;
4230 
4231 		/*
4232 		 * Only valid for V4
4233 		 */
4234 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4235 		    (IPV4_VERSION << 4));
4236 
4237 		ipif = ipif_get_next_ipif(NULL, ill);
4238 		if (ipif != NULL) {
4239 			/*
4240 			 * Since a decision has already been made to deliver the
4241 			 * packet, there is no need to test for SECATTR and
4242 			 * ZONEONLY.
4243 			 * When a multicast packet is transmitted
4244 			 * a cache entry is created for the multicast address.
4245 			 * When delivering a copy of the packet or when new
4246 			 * packets are received we do not want to match on the
4247 			 * cached entry so explicitly match on
4248 			 * IRE_LOCAL and IRE_LOOPBACK
4249 			 */
4250 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4251 			    IRE_LOCAL | IRE_LOOPBACK,
4252 			    ipif, zoneid, NULL,
4253 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4254 			if (ire == NULL) {
4255 				/*
4256 				 * packet must have come on a different
4257 				 * interface.
4258 				 * Since a decision has already been made to
4259 				 * deliver the packet, there is no need to test
4260 				 * for SECATTR and ZONEONLY.
4261 				 * Only match on local and broadcast ire's.
4262 				 * See detailed comment above.
4263 				 */
4264 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4265 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4266 				    NULL, MATCH_IRE_TYPE, ipst);
4267 			}
4268 
4269 			if (ire == NULL) {
4270 				/*
4271 				 * This is either a multicast packet or
4272 				 * the address has been removed since
4273 				 * the packet was received.
4274 				 * Return INADDR_ANY so that normal source
4275 				 * selection occurs for the response.
4276 				 */
4277 
4278 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4279 			} else {
4280 				pinfo->ip_pkt_match_addr.s_addr =
4281 				    ire->ire_src_addr;
4282 				ire_refrele(ire);
4283 			}
4284 			ipif_refrele(ipif);
4285 		} else {
4286 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4287 		}
4288 	}
4289 
4290 	if (ipmp_ill_held)
4291 		ill_refrele(ill);
4292 
4293 	mp->b_datap->db_type = M_CTL;
4294 	mp->b_wptr += sizeof (ip_pktinfo_t);
4295 	mp->b_cont = data_mp;
4296 
4297 	return (mp);
4298 }
4299 
4300 /*
4301  * Used to determine the most accurate cred_t to use for TX.
4302  * First priority is SCM_UCRED having set the label in the message,
4303  * which is used for MLP on UDP. Second priority is the peers label (aka
4304  * conn_peercred), which is needed for MLP on TCP/SCTP. Last priority is the
4305  * open credentials.
4306  */
4307 cred_t *
4308 ip_best_cred(mblk_t *mp, conn_t *connp)
4309 {
4310 	cred_t *cr;
4311 
4312 	cr = msg_getcred(mp, NULL);
4313 	if (cr != NULL && crgetlabel(cr) != NULL)
4314 		return (cr);
4315 	return (CONN_CRED(connp));
4316 }
4317 
4318 /*
4319  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4320  * part of the bind request.
4321  */
4322 
4323 boolean_t
4324 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4325 {
4326 	ipsec_in_t *ii;
4327 
4328 	ASSERT(policy_mp != NULL);
4329 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4330 
4331 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4332 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4333 
4334 	connp->conn_policy = ii->ipsec_in_policy;
4335 	ii->ipsec_in_policy = NULL;
4336 
4337 	if (ii->ipsec_in_action != NULL) {
4338 		if (connp->conn_latch == NULL) {
4339 			connp->conn_latch = iplatch_create();
4340 			if (connp->conn_latch == NULL)
4341 				return (B_FALSE);
4342 		}
4343 		ipsec_latch_inbound(connp->conn_latch, ii);
4344 	}
4345 	return (B_TRUE);
4346 }
4347 
4348 static void
4349 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4350 {
4351 	/*
4352 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4353 	 * We can't do this in ip_bind_get_ire because the policy
4354 	 * may not have been inherited at that point in time and hence
4355 	 * conn_out_enforce_policy may not be set.
4356 	 */
4357 	if (ire_requested && connp->conn_out_enforce_policy &&
4358 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4359 		ire_t *ire = (ire_t *)mp->b_rptr;
4360 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4361 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4362 	}
4363 }
4364 
4365 /*
4366  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4367  * and to arrange for power-fanout assist.  The ULP is identified by
4368  * adding a single byte at the end of the original bind message.
4369  * A ULP other than UDP or TCP that wishes to be recognized passes
4370  * down a bind with a zero length address.
4371  *
4372  * The binding works as follows:
4373  * - A zero byte address means just bind to the protocol.
4374  * - A four byte address is treated as a request to validate
4375  *   that the address is a valid local address, appropriate for
4376  *   an application to bind to. This does not affect any fanout
4377  *   information in IP.
4378  * - A sizeof sin_t byte address is used to bind to only the local address
4379  *   and port.
4380  * - A sizeof ipa_conn_t byte address contains complete fanout information
4381  *   consisting of local and remote addresses and ports.  In
4382  *   this case, the addresses are both validated as appropriate
4383  *   for this operation, and, if so, the information is retained
4384  *   for use in the inbound fanout.
4385  *
4386  * The ULP (except in the zero-length bind) can append an
4387  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4388  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4389  * a copy of the source or destination IRE (source for local bind;
4390  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4391  * policy information contained should be copied on to the conn.
4392  *
4393  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4394  */
4395 mblk_t *
4396 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4397 {
4398 	ssize_t		len;
4399 	struct T_bind_req	*tbr;
4400 	sin_t		*sin;
4401 	ipa_conn_t	*ac;
4402 	uchar_t		*ucp;
4403 	mblk_t		*mp1;
4404 	boolean_t	ire_requested;
4405 	int		error = 0;
4406 	int		protocol;
4407 	ipa_conn_x_t	*acx;
4408 	cred_t		*cr;
4409 
4410 	/*
4411 	 * All Solaris components should pass a db_credp
4412 	 * for this TPI message, hence we ASSERT.
4413 	 * But in case there is some other M_PROTO that looks
4414 	 * like a TPI message sent by some other kernel
4415 	 * component, we check and return an error.
4416 	 */
4417 	cr = msg_getcred(mp, NULL);
4418 	ASSERT(cr != NULL);
4419 	if (cr == NULL) {
4420 		error = EINVAL;
4421 		goto bad_addr;
4422 	}
4423 
4424 	ASSERT(!connp->conn_af_isv6);
4425 	connp->conn_pkt_isv6 = B_FALSE;
4426 
4427 	len = MBLKL(mp);
4428 	if (len < (sizeof (*tbr) + 1)) {
4429 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4430 		    "ip_bind: bogus msg, len %ld", len);
4431 		/* XXX: Need to return something better */
4432 		goto bad_addr;
4433 	}
4434 	/* Back up and extract the protocol identifier. */
4435 	mp->b_wptr--;
4436 	protocol = *mp->b_wptr & 0xFF;
4437 	tbr = (struct T_bind_req *)mp->b_rptr;
4438 	/* Reset the message type in preparation for shipping it back. */
4439 	DB_TYPE(mp) = M_PCPROTO;
4440 
4441 	connp->conn_ulp = (uint8_t)protocol;
4442 
4443 	/*
4444 	 * Check for a zero length address.  This is from a protocol that
4445 	 * wants to register to receive all packets of its type.
4446 	 */
4447 	if (tbr->ADDR_length == 0) {
4448 		/*
4449 		 * These protocols are now intercepted in ip_bind_v6().
4450 		 * Reject protocol-level binds here for now.
4451 		 *
4452 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4453 		 * so that the protocol type cannot be SCTP.
4454 		 */
4455 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4456 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4457 			goto bad_addr;
4458 		}
4459 
4460 		/*
4461 		 *
4462 		 * The udp module never sends down a zero-length address,
4463 		 * and allowing this on a labeled system will break MLP
4464 		 * functionality.
4465 		 */
4466 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4467 			goto bad_addr;
4468 
4469 		if (connp->conn_mac_exempt)
4470 			goto bad_addr;
4471 
4472 		/* No hash here really.  The table is big enough. */
4473 		connp->conn_srcv6 = ipv6_all_zeros;
4474 
4475 		ipcl_proto_insert(connp, protocol);
4476 
4477 		tbr->PRIM_type = T_BIND_ACK;
4478 		return (mp);
4479 	}
4480 
4481 	/* Extract the address pointer from the message. */
4482 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4483 	    tbr->ADDR_length);
4484 	if (ucp == NULL) {
4485 		ip1dbg(("ip_bind: no address\n"));
4486 		goto bad_addr;
4487 	}
4488 	if (!OK_32PTR(ucp)) {
4489 		ip1dbg(("ip_bind: unaligned address\n"));
4490 		goto bad_addr;
4491 	}
4492 	/*
4493 	 * Check for trailing mps.
4494 	 */
4495 
4496 	mp1 = mp->b_cont;
4497 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4498 
4499 	switch (tbr->ADDR_length) {
4500 	default:
4501 		ip1dbg(("ip_bind: bad address length %d\n",
4502 		    (int)tbr->ADDR_length));
4503 		goto bad_addr;
4504 
4505 	case IP_ADDR_LEN:
4506 		/* Verification of local address only */
4507 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4508 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4509 		break;
4510 
4511 	case sizeof (sin_t):
4512 		sin = (sin_t *)ucp;
4513 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4514 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4515 		break;
4516 
4517 	case sizeof (ipa_conn_t):
4518 		ac = (ipa_conn_t *)ucp;
4519 		/* For raw socket, the local port is not set. */
4520 		if (ac->ac_lport == 0)
4521 			ac->ac_lport = connp->conn_lport;
4522 		/* Always verify destination reachability. */
4523 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4524 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4525 		    B_TRUE, B_TRUE, cr);
4526 		break;
4527 
4528 	case sizeof (ipa_conn_x_t):
4529 		acx = (ipa_conn_x_t *)ucp;
4530 		/*
4531 		 * Whether or not to verify destination reachability depends
4532 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4533 		 */
4534 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4535 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4536 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4537 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4538 		break;
4539 	}
4540 	ASSERT(error != EINPROGRESS);
4541 	if (error != 0)
4542 		goto bad_addr;
4543 
4544 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4545 
4546 	/* Send it home. */
4547 	mp->b_datap->db_type = M_PCPROTO;
4548 	tbr->PRIM_type = T_BIND_ACK;
4549 	return (mp);
4550 
4551 bad_addr:
4552 	/*
4553 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4554 	 * a unix errno.
4555 	 */
4556 	if (error > 0)
4557 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4558 	else
4559 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4560 	return (mp);
4561 }
4562 
4563 /*
4564  * Here address is verified to be a valid local address.
4565  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4566  * address is also considered a valid local address.
4567  * In the case of a broadcast/multicast address, however, the
4568  * upper protocol is expected to reset the src address
4569  * to 0 if it sees a IRE_BROADCAST type returned so that
4570  * no packets are emitted with broadcast/multicast address as
4571  * source address (that violates hosts requirements RFC 1122)
4572  * The addresses valid for bind are:
4573  *	(1) - INADDR_ANY (0)
4574  *	(2) - IP address of an UP interface
4575  *	(3) - IP address of a DOWN interface
4576  *	(4) - valid local IP broadcast addresses. In this case
4577  *	the conn will only receive packets destined to
4578  *	the specified broadcast address.
4579  *	(5) - a multicast address. In this case
4580  *	the conn will only receive packets destined to
4581  *	the specified multicast address. Note: the
4582  *	application still has to issue an
4583  *	IP_ADD_MEMBERSHIP socket option.
4584  *
4585  * On error, return -1 for TBADADDR otherwise pass the
4586  * errno with TSYSERR reply.
4587  *
4588  * In all the above cases, the bound address must be valid in the current zone.
4589  * When the address is loopback, multicast or broadcast, there might be many
4590  * matching IREs so bind has to look up based on the zone.
4591  *
4592  * Note: lport is in network byte order.
4593  *
4594  */
4595 int
4596 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4597     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4598 {
4599 	int		error = 0;
4600 	ire_t		*src_ire;
4601 	zoneid_t	zoneid;
4602 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4603 	mblk_t		*mp = NULL;
4604 	boolean_t	ire_requested = B_FALSE;
4605 	boolean_t	ipsec_policy_set = B_FALSE;
4606 
4607 	if (mpp)
4608 		mp = *mpp;
4609 
4610 	if (mp != NULL) {
4611 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4612 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4613 	}
4614 
4615 	/*
4616 	 * If it was previously connected, conn_fully_bound would have
4617 	 * been set.
4618 	 */
4619 	connp->conn_fully_bound = B_FALSE;
4620 
4621 	src_ire = NULL;
4622 
4623 	zoneid = IPCL_ZONEID(connp);
4624 
4625 	if (src_addr) {
4626 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4627 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4628 		/*
4629 		 * If an address other than 0.0.0.0 is requested,
4630 		 * we verify that it is a valid address for bind
4631 		 * Note: Following code is in if-else-if form for
4632 		 * readability compared to a condition check.
4633 		 */
4634 		/* LINTED - statement has no consequence */
4635 		if (IRE_IS_LOCAL(src_ire)) {
4636 			/*
4637 			 * (2) Bind to address of local UP interface
4638 			 */
4639 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4640 			/*
4641 			 * (4) Bind to broadcast address
4642 			 * Note: permitted only from transports that
4643 			 * request IRE
4644 			 */
4645 			if (!ire_requested)
4646 				error = EADDRNOTAVAIL;
4647 		} else {
4648 			/*
4649 			 * (3) Bind to address of local DOWN interface
4650 			 * (ipif_lookup_addr() looks up all interfaces
4651 			 * but we do not get here for UP interfaces
4652 			 * - case (2) above)
4653 			 */
4654 			/* LINTED - statement has no consequent */
4655 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4656 				/* The address exists */
4657 			} else if (CLASSD(src_addr)) {
4658 				error = 0;
4659 				if (src_ire != NULL)
4660 					ire_refrele(src_ire);
4661 				/*
4662 				 * (5) bind to multicast address.
4663 				 * Fake out the IRE returned to upper
4664 				 * layer to be a broadcast IRE.
4665 				 */
4666 				src_ire = ire_ctable_lookup(
4667 				    INADDR_BROADCAST, INADDR_ANY,
4668 				    IRE_BROADCAST, NULL, zoneid, NULL,
4669 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4670 				    ipst);
4671 				if (src_ire == NULL || !ire_requested)
4672 					error = EADDRNOTAVAIL;
4673 			} else {
4674 				/*
4675 				 * Not a valid address for bind
4676 				 */
4677 				error = EADDRNOTAVAIL;
4678 			}
4679 		}
4680 		if (error) {
4681 			/* Red Alert!  Attempting to be a bogon! */
4682 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4683 			    ntohl(src_addr)));
4684 			goto bad_addr;
4685 		}
4686 	}
4687 
4688 	/*
4689 	 * Allow setting new policies. For example, disconnects come
4690 	 * down as ipa_t bind. As we would have set conn_policy_cached
4691 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4692 	 * can change after the disconnect.
4693 	 */
4694 	connp->conn_policy_cached = B_FALSE;
4695 
4696 	/*
4697 	 * If not fanout_insert this was just an address verification
4698 	 */
4699 	if (fanout_insert) {
4700 		/*
4701 		 * The addresses have been verified. Time to insert in
4702 		 * the correct fanout list.
4703 		 */
4704 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4705 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4706 		connp->conn_lport = lport;
4707 		connp->conn_fport = 0;
4708 		/*
4709 		 * Do we need to add a check to reject Multicast packets
4710 		 */
4711 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4712 	}
4713 
4714 	if (error == 0) {
4715 		if (ire_requested) {
4716 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4717 				error = -1;
4718 				/* Falls through to bad_addr */
4719 			}
4720 		} else if (ipsec_policy_set) {
4721 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4722 				error = -1;
4723 				/* Falls through to bad_addr */
4724 			}
4725 		}
4726 	}
4727 bad_addr:
4728 	if (error != 0) {
4729 		if (connp->conn_anon_port) {
4730 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4731 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4732 			    B_FALSE);
4733 		}
4734 		connp->conn_mlp_type = mlptSingle;
4735 	}
4736 	if (src_ire != NULL)
4737 		IRE_REFRELE(src_ire);
4738 	return (error);
4739 }
4740 
4741 int
4742 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4743     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4744 {
4745 	int error;
4746 	mblk_t	*mp = NULL;
4747 	boolean_t ire_requested;
4748 
4749 	if (ire_mpp)
4750 		mp = *ire_mpp;
4751 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4752 
4753 	ASSERT(!connp->conn_af_isv6);
4754 	connp->conn_pkt_isv6 = B_FALSE;
4755 	connp->conn_ulp = protocol;
4756 
4757 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4758 	    fanout_insert);
4759 	if (error == 0) {
4760 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4761 		    ire_requested);
4762 	} else if (error < 0) {
4763 		error = -TBADADDR;
4764 	}
4765 	return (error);
4766 }
4767 
4768 /*
4769  * Verify that both the source and destination addresses
4770  * are valid.  If verify_dst is false, then the destination address may be
4771  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4772  * destination reachability, while tunnels do not.
4773  * Note that we allow connect to broadcast and multicast
4774  * addresses when ire_requested is set. Thus the ULP
4775  * has to check for IRE_BROADCAST and multicast.
4776  *
4777  * Returns zero if ok.
4778  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4779  * (for use with TSYSERR reply).
4780  *
4781  * Note: lport and fport are in network byte order.
4782  */
4783 int
4784 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4785     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4786     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4787 {
4788 
4789 	ire_t		*src_ire;
4790 	ire_t		*dst_ire;
4791 	int		error = 0;
4792 	ire_t		*sire = NULL;
4793 	ire_t		*md_dst_ire = NULL;
4794 	ire_t		*lso_dst_ire = NULL;
4795 	ill_t		*ill = NULL;
4796 	zoneid_t	zoneid;
4797 	ipaddr_t	src_addr = *src_addrp;
4798 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4799 	mblk_t		*mp = NULL;
4800 	boolean_t	ire_requested = B_FALSE;
4801 	boolean_t	ipsec_policy_set = B_FALSE;
4802 	ts_label_t	*tsl = NULL;
4803 
4804 	if (mpp)
4805 		mp = *mpp;
4806 
4807 	if (mp != NULL) {
4808 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4809 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4810 	}
4811 	if (cr != NULL)
4812 		tsl = crgetlabel(cr);
4813 
4814 	src_ire = dst_ire = NULL;
4815 
4816 	/*
4817 	 * If we never got a disconnect before, clear it now.
4818 	 */
4819 	connp->conn_fully_bound = B_FALSE;
4820 
4821 	zoneid = IPCL_ZONEID(connp);
4822 
4823 	if (CLASSD(dst_addr)) {
4824 		/* Pick up an IRE_BROADCAST */
4825 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4826 		    NULL, zoneid, tsl,
4827 		    (MATCH_IRE_RECURSIVE |
4828 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4829 		    MATCH_IRE_SECATTR), ipst);
4830 	} else {
4831 		/*
4832 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4833 		 * and onlink ipif is not found set ENETUNREACH error.
4834 		 */
4835 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4836 			ipif_t *ipif;
4837 
4838 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4839 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4840 			if (ipif == NULL) {
4841 				error = ENETUNREACH;
4842 				goto bad_addr;
4843 			}
4844 			ipif_refrele(ipif);
4845 		}
4846 
4847 		if (connp->conn_nexthop_set) {
4848 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4849 			    0, 0, NULL, NULL, zoneid, tsl,
4850 			    MATCH_IRE_SECATTR, ipst);
4851 		} else {
4852 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4853 			    &sire, zoneid, tsl,
4854 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4855 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4856 			    MATCH_IRE_SECATTR), ipst);
4857 		}
4858 	}
4859 	/*
4860 	 * dst_ire can't be a broadcast when not ire_requested.
4861 	 * We also prevent ire's with src address INADDR_ANY to
4862 	 * be used, which are created temporarily for
4863 	 * sending out packets from endpoints that have
4864 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4865 	 * reachable.  If verify_dst is false, the destination needn't be
4866 	 * reachable.
4867 	 *
4868 	 * If we match on a reject or black hole, then we've got a
4869 	 * local failure.  May as well fail out the connect() attempt,
4870 	 * since it's never going to succeed.
4871 	 */
4872 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4873 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4874 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4875 		/*
4876 		 * If we're verifying destination reachability, we always want
4877 		 * to complain here.
4878 		 *
4879 		 * If we're not verifying destination reachability but the
4880 		 * destination has a route, we still want to fail on the
4881 		 * temporary address and broadcast address tests.
4882 		 */
4883 		if (verify_dst || (dst_ire != NULL)) {
4884 			if (ip_debug > 2) {
4885 				pr_addr_dbg("ip_bind_connected_v4:"
4886 				    "bad connected dst %s\n",
4887 				    AF_INET, &dst_addr);
4888 			}
4889 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4890 				error = ENETUNREACH;
4891 			else
4892 				error = EHOSTUNREACH;
4893 			goto bad_addr;
4894 		}
4895 	}
4896 
4897 	/*
4898 	 * We now know that routing will allow us to reach the destination.
4899 	 * Check whether Trusted Solaris policy allows communication with this
4900 	 * host, and pretend that the destination is unreachable if not.
4901 	 *
4902 	 * This is never a problem for TCP, since that transport is known to
4903 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4904 	 * handling.  If the remote is unreachable, it will be detected at that
4905 	 * point, so there's no reason to check it here.
4906 	 *
4907 	 * Note that for sendto (and other datagram-oriented friends), this
4908 	 * check is done as part of the data path label computation instead.
4909 	 * The check here is just to make non-TCP connect() report the right
4910 	 * error.
4911 	 */
4912 	if (dst_ire != NULL && is_system_labeled() &&
4913 	    !IPCL_IS_TCP(connp) &&
4914 	    tsol_compute_label(cr, dst_addr, NULL,
4915 	    connp->conn_mac_exempt, ipst) != 0) {
4916 		error = EHOSTUNREACH;
4917 		if (ip_debug > 2) {
4918 			pr_addr_dbg("ip_bind_connected_v4:"
4919 			    " no label for dst %s\n",
4920 			    AF_INET, &dst_addr);
4921 		}
4922 		goto bad_addr;
4923 	}
4924 
4925 	/*
4926 	 * If the app does a connect(), it means that it will most likely
4927 	 * send more than 1 packet to the destination.  It makes sense
4928 	 * to clear the temporary flag.
4929 	 */
4930 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4931 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4932 		irb_t *irb = dst_ire->ire_bucket;
4933 
4934 		rw_enter(&irb->irb_lock, RW_WRITER);
4935 		/*
4936 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4937 		 * the lock to guarantee irb_tmp_ire_cnt.
4938 		 */
4939 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4940 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4941 			irb->irb_tmp_ire_cnt--;
4942 		}
4943 		rw_exit(&irb->irb_lock);
4944 	}
4945 
4946 	/*
4947 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4948 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4949 	 * eligibility tests for passive connects are handled separately
4950 	 * through tcp_adapt_ire().  We do this before the source address
4951 	 * selection, because dst_ire may change after a call to
4952 	 * ipif_select_source().  This is a best-effort check, as the
4953 	 * packet for this connection may not actually go through
4954 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4955 	 * calling ip_newroute().  This is why we further check on the
4956 	 * IRE during LSO/Multidata packet transmission in
4957 	 * tcp_lsosend()/tcp_multisend().
4958 	 */
4959 	if (!ipsec_policy_set && dst_ire != NULL &&
4960 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4961 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4962 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4963 			lso_dst_ire = dst_ire;
4964 			IRE_REFHOLD(lso_dst_ire);
4965 		} else if (ipst->ips_ip_multidata_outbound &&
4966 		    ILL_MDT_CAPABLE(ill)) {
4967 			md_dst_ire = dst_ire;
4968 			IRE_REFHOLD(md_dst_ire);
4969 		}
4970 	}
4971 
4972 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4973 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4974 		/*
4975 		 * If the IRE belongs to a different zone, look for a matching
4976 		 * route in the forwarding table and use the source address from
4977 		 * that route.
4978 		 */
4979 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4980 		    zoneid, 0, NULL,
4981 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4982 		    MATCH_IRE_RJ_BHOLE, ipst);
4983 		if (src_ire == NULL) {
4984 			error = EHOSTUNREACH;
4985 			goto bad_addr;
4986 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4987 			if (!(src_ire->ire_type & IRE_HOST))
4988 				error = ENETUNREACH;
4989 			else
4990 				error = EHOSTUNREACH;
4991 			goto bad_addr;
4992 		}
4993 		if (src_addr == INADDR_ANY)
4994 			src_addr = src_ire->ire_src_addr;
4995 		ire_refrele(src_ire);
4996 		src_ire = NULL;
4997 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4998 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4999 			src_addr = sire->ire_src_addr;
5000 			ire_refrele(dst_ire);
5001 			dst_ire = sire;
5002 			sire = NULL;
5003 		} else {
5004 			/*
5005 			 * Pick a source address so that a proper inbound
5006 			 * load spreading would happen.
5007 			 */
5008 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
5009 			ipif_t *src_ipif = NULL;
5010 			ire_t *ipif_ire;
5011 
5012 			/*
5013 			 * Supply a local source address such that inbound
5014 			 * load spreading happens.
5015 			 *
5016 			 * Determine the best source address on this ill for
5017 			 * the destination.
5018 			 *
5019 			 * 1) For broadcast, we should return a broadcast ire
5020 			 *    found above so that upper layers know that the
5021 			 *    destination address is a broadcast address.
5022 			 *
5023 			 * 2) If the ipif is DEPRECATED, select a better
5024 			 *    source address.  Similarly, if the ipif is on
5025 			 *    the IPMP meta-interface, pick a source address
5026 			 *    at random to improve inbound load spreading.
5027 			 *
5028 			 * 3) If the outgoing interface is part of a usesrc
5029 			 *    group, then try selecting a source address from
5030 			 *    the usesrc ILL.
5031 			 */
5032 			if ((dst_ire->ire_zoneid != zoneid &&
5033 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5034 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5035 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5036 			    (IS_IPMP(ire_ill) ||
5037 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5038 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
5039 				/*
5040 				 * If the destination is reachable via a
5041 				 * given gateway, the selected source address
5042 				 * should be in the same subnet as the gateway.
5043 				 * Otherwise, the destination is not reachable.
5044 				 *
5045 				 * If there are no interfaces on the same subnet
5046 				 * as the destination, ipif_select_source gives
5047 				 * first non-deprecated interface which might be
5048 				 * on a different subnet than the gateway.
5049 				 * This is not desirable. Hence pass the dst_ire
5050 				 * source address to ipif_select_source.
5051 				 * It is sure that the destination is reachable
5052 				 * with the dst_ire source address subnet.
5053 				 * So passing dst_ire source address to
5054 				 * ipif_select_source will make sure that the
5055 				 * selected source will be on the same subnet
5056 				 * as dst_ire source address.
5057 				 */
5058 				ipaddr_t saddr =
5059 				    dst_ire->ire_ipif->ipif_src_addr;
5060 				src_ipif = ipif_select_source(ire_ill,
5061 				    saddr, zoneid);
5062 				if (src_ipif != NULL) {
5063 					if (IS_VNI(src_ipif->ipif_ill)) {
5064 						/*
5065 						 * For VNI there is no
5066 						 * interface route
5067 						 */
5068 						src_addr =
5069 						    src_ipif->ipif_src_addr;
5070 					} else {
5071 						ipif_ire =
5072 						    ipif_to_ire(src_ipif);
5073 						if (ipif_ire != NULL) {
5074 							IRE_REFRELE(dst_ire);
5075 							dst_ire = ipif_ire;
5076 						}
5077 						src_addr =
5078 						    dst_ire->ire_src_addr;
5079 					}
5080 					ipif_refrele(src_ipif);
5081 				} else {
5082 					src_addr = dst_ire->ire_src_addr;
5083 				}
5084 			} else {
5085 				src_addr = dst_ire->ire_src_addr;
5086 			}
5087 		}
5088 	}
5089 
5090 	/*
5091 	 * We do ire_route_lookup() here (and not
5092 	 * interface lookup as we assert that
5093 	 * src_addr should only come from an
5094 	 * UP interface for hard binding.
5095 	 */
5096 	ASSERT(src_ire == NULL);
5097 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5098 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5099 	/* src_ire must be a local|loopback */
5100 	if (!IRE_IS_LOCAL(src_ire)) {
5101 		if (ip_debug > 2) {
5102 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5103 			    "src %s\n", AF_INET, &src_addr);
5104 		}
5105 		error = EADDRNOTAVAIL;
5106 		goto bad_addr;
5107 	}
5108 
5109 	/*
5110 	 * If the source address is a loopback address, the
5111 	 * destination had best be local or multicast.
5112 	 * The transports that can't handle multicast will reject
5113 	 * those addresses.
5114 	 */
5115 	if (src_ire->ire_type == IRE_LOOPBACK &&
5116 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5117 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5118 		error = -1;
5119 		goto bad_addr;
5120 	}
5121 
5122 	/*
5123 	 * Allow setting new policies. For example, disconnects come
5124 	 * down as ipa_t bind. As we would have set conn_policy_cached
5125 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5126 	 * can change after the disconnect.
5127 	 */
5128 	connp->conn_policy_cached = B_FALSE;
5129 
5130 	/*
5131 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5132 	 * can handle their passed-in conn's.
5133 	 */
5134 
5135 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5136 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5137 	connp->conn_lport = lport;
5138 	connp->conn_fport = fport;
5139 	*src_addrp = src_addr;
5140 
5141 	ASSERT(!(ipsec_policy_set && ire_requested));
5142 	if (ire_requested) {
5143 		iulp_t *ulp_info = NULL;
5144 
5145 		/*
5146 		 * Note that sire will not be NULL if this is an off-link
5147 		 * connection and there is not cache for that dest yet.
5148 		 *
5149 		 * XXX Because of an existing bug, if there are multiple
5150 		 * default routes, the IRE returned now may not be the actual
5151 		 * default route used (default routes are chosen in a
5152 		 * round robin fashion).  So if the metrics for different
5153 		 * default routes are different, we may return the wrong
5154 		 * metrics.  This will not be a problem if the existing
5155 		 * bug is fixed.
5156 		 */
5157 		if (sire != NULL) {
5158 			ulp_info = &(sire->ire_uinfo);
5159 		}
5160 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5161 			error = -1;
5162 			goto bad_addr;
5163 		}
5164 		mp = *mpp;
5165 	} else if (ipsec_policy_set) {
5166 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5167 			error = -1;
5168 			goto bad_addr;
5169 		}
5170 	}
5171 
5172 	/*
5173 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5174 	 * we'll cache that.  If we don't, we'll inherit global policy.
5175 	 *
5176 	 * We can't insert until the conn reflects the policy. Note that
5177 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5178 	 * connections where we don't have a policy. This is to prevent
5179 	 * global policy lookups in the inbound path.
5180 	 *
5181 	 * If we insert before we set conn_policy_cached,
5182 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5183 	 * because global policy cound be non-empty. We normally call
5184 	 * ipsec_check_policy() for conn_policy_cached connections only if
5185 	 * ipc_in_enforce_policy is set. But in this case,
5186 	 * conn_policy_cached can get set anytime since we made the
5187 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5188 	 * called, which will make the above assumption false.  Thus, we
5189 	 * need to insert after we set conn_policy_cached.
5190 	 */
5191 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5192 		goto bad_addr;
5193 
5194 	if (fanout_insert) {
5195 		/*
5196 		 * The addresses have been verified. Time to insert in
5197 		 * the correct fanout list.
5198 		 */
5199 		error = ipcl_conn_insert(connp, protocol, src_addr,
5200 		    dst_addr, connp->conn_ports);
5201 	}
5202 
5203 	if (error == 0) {
5204 		connp->conn_fully_bound = B_TRUE;
5205 		/*
5206 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5207 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5208 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5209 		 * ip_xxinfo_return(), which performs further checks
5210 		 * against them and upon success, returns the LSO/MDT info
5211 		 * mblk which we will attach to the bind acknowledgment.
5212 		 */
5213 		if (lso_dst_ire != NULL) {
5214 			mblk_t *lsoinfo_mp;
5215 
5216 			ASSERT(ill->ill_lso_capab != NULL);
5217 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5218 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5219 				if (mp == NULL) {
5220 					*mpp = lsoinfo_mp;
5221 				} else {
5222 					linkb(mp, lsoinfo_mp);
5223 				}
5224 			}
5225 		} else if (md_dst_ire != NULL) {
5226 			mblk_t *mdinfo_mp;
5227 
5228 			ASSERT(ill->ill_mdt_capab != NULL);
5229 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5230 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5231 				if (mp == NULL) {
5232 					*mpp = mdinfo_mp;
5233 				} else {
5234 					linkb(mp, mdinfo_mp);
5235 				}
5236 			}
5237 		}
5238 	}
5239 bad_addr:
5240 	if (ipsec_policy_set) {
5241 		ASSERT(mp != NULL);
5242 		freeb(mp);
5243 		/*
5244 		 * As of now assume that nothing else accompanies
5245 		 * IPSEC_POLICY_SET.
5246 		 */
5247 		*mpp = NULL;
5248 	}
5249 	if (src_ire != NULL)
5250 		IRE_REFRELE(src_ire);
5251 	if (dst_ire != NULL)
5252 		IRE_REFRELE(dst_ire);
5253 	if (sire != NULL)
5254 		IRE_REFRELE(sire);
5255 	if (md_dst_ire != NULL)
5256 		IRE_REFRELE(md_dst_ire);
5257 	if (lso_dst_ire != NULL)
5258 		IRE_REFRELE(lso_dst_ire);
5259 	return (error);
5260 }
5261 
5262 int
5263 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5264     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5265     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5266 {
5267 	int error;
5268 	mblk_t	*mp = NULL;
5269 	boolean_t ire_requested;
5270 
5271 	if (ire_mpp)
5272 		mp = *ire_mpp;
5273 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5274 
5275 	ASSERT(!connp->conn_af_isv6);
5276 	connp->conn_pkt_isv6 = B_FALSE;
5277 	connp->conn_ulp = protocol;
5278 
5279 	/* For raw socket, the local port is not set. */
5280 	if (lport == 0)
5281 		lport = connp->conn_lport;
5282 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5283 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5284 	if (error == 0) {
5285 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5286 		    ire_requested);
5287 	} else if (error < 0) {
5288 		error = -TBADADDR;
5289 	}
5290 	return (error);
5291 }
5292 
5293 /*
5294  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5295  * Prefers dst_ire over src_ire.
5296  */
5297 static boolean_t
5298 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5299 {
5300 	mblk_t	*mp = *mpp;
5301 	ire_t	*ret_ire;
5302 
5303 	ASSERT(mp != NULL);
5304 
5305 	if (ire != NULL) {
5306 		/*
5307 		 * mp initialized above to IRE_DB_REQ_TYPE
5308 		 * appended mblk. Its <upper protocol>'s
5309 		 * job to make sure there is room.
5310 		 */
5311 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5312 			return (B_FALSE);
5313 
5314 		mp->b_datap->db_type = IRE_DB_TYPE;
5315 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5316 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5317 		ret_ire = (ire_t *)mp->b_rptr;
5318 		/*
5319 		 * Pass the latest setting of the ip_path_mtu_discovery and
5320 		 * copy the ulp info if any.
5321 		 */
5322 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5323 		    IPH_DF : 0;
5324 		if (ulp_info != NULL) {
5325 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5326 			    sizeof (iulp_t));
5327 		}
5328 		ret_ire->ire_mp = mp;
5329 	} else {
5330 		/*
5331 		 * No IRE was found. Remove IRE mblk.
5332 		 */
5333 		*mpp = mp->b_cont;
5334 		freeb(mp);
5335 	}
5336 	return (B_TRUE);
5337 }
5338 
5339 /*
5340  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5341  * the final piece where we don't.  Return a pointer to the first mblk in the
5342  * result, and update the pointer to the next mblk to chew on.  If anything
5343  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5344  * NULL pointer.
5345  */
5346 mblk_t *
5347 ip_carve_mp(mblk_t **mpp, ssize_t len)
5348 {
5349 	mblk_t	*mp0;
5350 	mblk_t	*mp1;
5351 	mblk_t	*mp2;
5352 
5353 	if (!len || !mpp || !(mp0 = *mpp))
5354 		return (NULL);
5355 	/* If we aren't going to consume the first mblk, we need a dup. */
5356 	if (mp0->b_wptr - mp0->b_rptr > len) {
5357 		mp1 = dupb(mp0);
5358 		if (mp1) {
5359 			/* Partition the data between the two mblks. */
5360 			mp1->b_wptr = mp1->b_rptr + len;
5361 			mp0->b_rptr = mp1->b_wptr;
5362 			/*
5363 			 * after adjustments if mblk not consumed is now
5364 			 * unaligned, try to align it. If this fails free
5365 			 * all messages and let upper layer recover.
5366 			 */
5367 			if (!OK_32PTR(mp0->b_rptr)) {
5368 				if (!pullupmsg(mp0, -1)) {
5369 					freemsg(mp0);
5370 					freemsg(mp1);
5371 					*mpp = NULL;
5372 					return (NULL);
5373 				}
5374 			}
5375 		}
5376 		return (mp1);
5377 	}
5378 	/* Eat through as many mblks as we need to get len bytes. */
5379 	len -= mp0->b_wptr - mp0->b_rptr;
5380 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5381 		if (mp2->b_wptr - mp2->b_rptr > len) {
5382 			/*
5383 			 * We won't consume the entire last mblk.  Like
5384 			 * above, dup and partition it.
5385 			 */
5386 			mp1->b_cont = dupb(mp2);
5387 			mp1 = mp1->b_cont;
5388 			if (!mp1) {
5389 				/*
5390 				 * Trouble.  Rather than go to a lot of
5391 				 * trouble to clean up, we free the messages.
5392 				 * This won't be any worse than losing it on
5393 				 * the wire.
5394 				 */
5395 				freemsg(mp0);
5396 				freemsg(mp2);
5397 				*mpp = NULL;
5398 				return (NULL);
5399 			}
5400 			mp1->b_wptr = mp1->b_rptr + len;
5401 			mp2->b_rptr = mp1->b_wptr;
5402 			/*
5403 			 * after adjustments if mblk not consumed is now
5404 			 * unaligned, try to align it. If this fails free
5405 			 * all messages and let upper layer recover.
5406 			 */
5407 			if (!OK_32PTR(mp2->b_rptr)) {
5408 				if (!pullupmsg(mp2, -1)) {
5409 					freemsg(mp0);
5410 					freemsg(mp2);
5411 					*mpp = NULL;
5412 					return (NULL);
5413 				}
5414 			}
5415 			*mpp = mp2;
5416 			return (mp0);
5417 		}
5418 		/* Decrement len by the amount we just got. */
5419 		len -= mp2->b_wptr - mp2->b_rptr;
5420 	}
5421 	/*
5422 	 * len should be reduced to zero now.  If not our caller has
5423 	 * screwed up.
5424 	 */
5425 	if (len) {
5426 		/* Shouldn't happen! */
5427 		freemsg(mp0);
5428 		*mpp = NULL;
5429 		return (NULL);
5430 	}
5431 	/*
5432 	 * We consumed up to exactly the end of an mblk.  Detach the part
5433 	 * we are returning from the rest of the chain.
5434 	 */
5435 	mp1->b_cont = NULL;
5436 	*mpp = mp2;
5437 	return (mp0);
5438 }
5439 
5440 /* The ill stream is being unplumbed. Called from ip_close */
5441 int
5442 ip_modclose(ill_t *ill)
5443 {
5444 	boolean_t success;
5445 	ipsq_t	*ipsq;
5446 	ipif_t	*ipif;
5447 	queue_t	*q = ill->ill_rq;
5448 	ip_stack_t	*ipst = ill->ill_ipst;
5449 	int	i;
5450 
5451 	/*
5452 	 * The punlink prior to this may have initiated a capability
5453 	 * negotiation. But ipsq_enter will block until that finishes or
5454 	 * times out.
5455 	 */
5456 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5457 
5458 	/*
5459 	 * Open/close/push/pop is guaranteed to be single threaded
5460 	 * per stream by STREAMS. FS guarantees that all references
5461 	 * from top are gone before close is called. So there can't
5462 	 * be another close thread that has set CONDEMNED on this ill.
5463 	 * and cause ipsq_enter to return failure.
5464 	 */
5465 	ASSERT(success);
5466 	ipsq = ill->ill_phyint->phyint_ipsq;
5467 
5468 	/*
5469 	 * Mark it condemned. No new reference will be made to this ill.
5470 	 * Lookup functions will return an error. Threads that try to
5471 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5472 	 * that the refcnt will drop down to zero.
5473 	 */
5474 	mutex_enter(&ill->ill_lock);
5475 	ill->ill_state_flags |= ILL_CONDEMNED;
5476 	for (ipif = ill->ill_ipif; ipif != NULL;
5477 	    ipif = ipif->ipif_next) {
5478 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5479 	}
5480 	/*
5481 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5482 	 * returns  error if ILL_CONDEMNED is set
5483 	 */
5484 	cv_broadcast(&ill->ill_cv);
5485 	mutex_exit(&ill->ill_lock);
5486 
5487 	/*
5488 	 * Send all the deferred DLPI messages downstream which came in
5489 	 * during the small window right before ipsq_enter(). We do this
5490 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5491 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5492 	 */
5493 	ill_dlpi_send_deferred(ill);
5494 
5495 	/*
5496 	 * Shut down fragmentation reassembly.
5497 	 * ill_frag_timer won't start a timer again.
5498 	 * Now cancel any existing timer
5499 	 */
5500 	(void) untimeout(ill->ill_frag_timer_id);
5501 	(void) ill_frag_timeout(ill, 0);
5502 
5503 	/*
5504 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5505 	 * this ill. Then wait for the refcnts to drop to zero.
5506 	 * ill_is_freeable checks whether the ill is really quiescent.
5507 	 * Then make sure that threads that are waiting to enter the
5508 	 * ipsq have seen the error returned by ipsq_enter and have
5509 	 * gone away. Then we call ill_delete_tail which does the
5510 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5511 	 */
5512 	ill_delete(ill);
5513 	mutex_enter(&ill->ill_lock);
5514 	while (!ill_is_freeable(ill))
5515 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5516 	while (ill->ill_waiters)
5517 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5518 
5519 	mutex_exit(&ill->ill_lock);
5520 
5521 	/*
5522 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5523 	 * it held until the end of the function since the cleanup
5524 	 * below needs to be able to use the ip_stack_t.
5525 	 */
5526 	netstack_hold(ipst->ips_netstack);
5527 
5528 	/* qprocsoff is done via ill_delete_tail */
5529 	ill_delete_tail(ill);
5530 	ASSERT(ill->ill_ipst == NULL);
5531 
5532 	/*
5533 	 * Walk through all upper (conn) streams and qenable
5534 	 * those that have queued data.
5535 	 * close synchronization needs this to
5536 	 * be done to ensure that all upper layers blocked
5537 	 * due to flow control to the closing device
5538 	 * get unblocked.
5539 	 */
5540 	ip1dbg(("ip_wsrv: walking\n"));
5541 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5542 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5543 	}
5544 
5545 	mutex_enter(&ipst->ips_ip_mi_lock);
5546 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5547 	mutex_exit(&ipst->ips_ip_mi_lock);
5548 
5549 	/*
5550 	 * credp could be null if the open didn't succeed and ip_modopen
5551 	 * itself calls ip_close.
5552 	 */
5553 	if (ill->ill_credp != NULL)
5554 		crfree(ill->ill_credp);
5555 
5556 	/*
5557 	 * Now we are done with the module close pieces that
5558 	 * need the netstack_t.
5559 	 */
5560 	netstack_rele(ipst->ips_netstack);
5561 
5562 	mi_close_free((IDP)ill);
5563 	q->q_ptr = WR(q)->q_ptr = NULL;
5564 
5565 	ipsq_exit(ipsq);
5566 
5567 	return (0);
5568 }
5569 
5570 /*
5571  * This is called as part of close() for IP, UDP, ICMP, and RTS
5572  * in order to quiesce the conn.
5573  */
5574 void
5575 ip_quiesce_conn(conn_t *connp)
5576 {
5577 	boolean_t	drain_cleanup_reqd = B_FALSE;
5578 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5579 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5580 	ip_stack_t	*ipst;
5581 
5582 	ASSERT(!IPCL_IS_TCP(connp));
5583 	ipst = connp->conn_netstack->netstack_ip;
5584 
5585 	/*
5586 	 * Mark the conn as closing, and this conn must not be
5587 	 * inserted in future into any list. Eg. conn_drain_insert(),
5588 	 * won't insert this conn into the conn_drain_list.
5589 	 * Similarly ill_pending_mp_add() will not add any mp to
5590 	 * the pending mp list, after this conn has started closing.
5591 	 *
5592 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5593 	 * cannot get set henceforth.
5594 	 */
5595 	mutex_enter(&connp->conn_lock);
5596 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5597 	connp->conn_state_flags |= CONN_CLOSING;
5598 	if (connp->conn_idl != NULL)
5599 		drain_cleanup_reqd = B_TRUE;
5600 	if (connp->conn_oper_pending_ill != NULL)
5601 		conn_ioctl_cleanup_reqd = B_TRUE;
5602 	if (connp->conn_dhcpinit_ill != NULL) {
5603 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5604 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5605 		connp->conn_dhcpinit_ill = NULL;
5606 	}
5607 	if (connp->conn_ilg_inuse != 0)
5608 		ilg_cleanup_reqd = B_TRUE;
5609 	mutex_exit(&connp->conn_lock);
5610 
5611 	if (conn_ioctl_cleanup_reqd)
5612 		conn_ioctl_cleanup(connp);
5613 
5614 	if (is_system_labeled() && connp->conn_anon_port) {
5615 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5616 		    connp->conn_mlp_type, connp->conn_ulp,
5617 		    ntohs(connp->conn_lport), B_FALSE);
5618 		connp->conn_anon_port = 0;
5619 	}
5620 	connp->conn_mlp_type = mlptSingle;
5621 
5622 	/*
5623 	 * Remove this conn from any fanout list it is on.
5624 	 * and then wait for any threads currently operating
5625 	 * on this endpoint to finish
5626 	 */
5627 	ipcl_hash_remove(connp);
5628 
5629 	/*
5630 	 * Remove this conn from the drain list, and do
5631 	 * any other cleanup that may be required.
5632 	 * (Only non-tcp streams may have a non-null conn_idl.
5633 	 * TCP streams are never flow controlled, and
5634 	 * conn_idl will be null)
5635 	 */
5636 	if (drain_cleanup_reqd)
5637 		conn_drain_tail(connp, B_TRUE);
5638 
5639 	if (connp == ipst->ips_ip_g_mrouter)
5640 		(void) ip_mrouter_done(NULL, ipst);
5641 
5642 	if (ilg_cleanup_reqd)
5643 		ilg_delete_all(connp);
5644 
5645 	conn_delete_ire(connp, NULL);
5646 
5647 	/*
5648 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5649 	 * callers from write side can't be there now because close
5650 	 * is in progress. The only other caller is ipcl_walk
5651 	 * which checks for the condemned flag.
5652 	 */
5653 	mutex_enter(&connp->conn_lock);
5654 	connp->conn_state_flags |= CONN_CONDEMNED;
5655 	while (connp->conn_ref != 1)
5656 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5657 	connp->conn_state_flags |= CONN_QUIESCED;
5658 	mutex_exit(&connp->conn_lock);
5659 }
5660 
5661 /* ARGSUSED */
5662 int
5663 ip_close(queue_t *q, int flags)
5664 {
5665 	conn_t		*connp;
5666 
5667 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5668 
5669 	/*
5670 	 * Call the appropriate delete routine depending on whether this is
5671 	 * a module or device.
5672 	 */
5673 	if (WR(q)->q_next != NULL) {
5674 		/* This is a module close */
5675 		return (ip_modclose((ill_t *)q->q_ptr));
5676 	}
5677 
5678 	connp = q->q_ptr;
5679 	ip_quiesce_conn(connp);
5680 
5681 	qprocsoff(q);
5682 
5683 	/*
5684 	 * Now we are truly single threaded on this stream, and can
5685 	 * delete the things hanging off the connp, and finally the connp.
5686 	 * We removed this connp from the fanout list, it cannot be
5687 	 * accessed thru the fanouts, and we already waited for the
5688 	 * conn_ref to drop to 0. We are already in close, so
5689 	 * there cannot be any other thread from the top. qprocsoff
5690 	 * has completed, and service has completed or won't run in
5691 	 * future.
5692 	 */
5693 	ASSERT(connp->conn_ref == 1);
5694 
5695 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5696 
5697 	connp->conn_ref--;
5698 	ipcl_conn_destroy(connp);
5699 
5700 	q->q_ptr = WR(q)->q_ptr = NULL;
5701 	return (0);
5702 }
5703 
5704 /*
5705  * Wapper around putnext() so that ip_rts_request can merely use
5706  * conn_recv.
5707  */
5708 /*ARGSUSED2*/
5709 static void
5710 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5711 {
5712 	conn_t *connp = (conn_t *)arg1;
5713 
5714 	putnext(connp->conn_rq, mp);
5715 }
5716 
5717 /*
5718  * Called when the module is about to be unloaded
5719  */
5720 void
5721 ip_ddi_destroy(void)
5722 {
5723 	tnet_fini();
5724 
5725 	icmp_ddi_g_destroy();
5726 	rts_ddi_g_destroy();
5727 	udp_ddi_g_destroy();
5728 	sctp_ddi_g_destroy();
5729 	tcp_ddi_g_destroy();
5730 	ipsec_policy_g_destroy();
5731 	ipcl_g_destroy();
5732 	ip_net_g_destroy();
5733 	ip_ire_g_fini();
5734 	inet_minor_destroy(ip_minor_arena_sa);
5735 #if defined(_LP64)
5736 	inet_minor_destroy(ip_minor_arena_la);
5737 #endif
5738 
5739 #ifdef DEBUG
5740 	list_destroy(&ip_thread_list);
5741 	rw_destroy(&ip_thread_rwlock);
5742 	tsd_destroy(&ip_thread_data);
5743 #endif
5744 
5745 	netstack_unregister(NS_IP);
5746 }
5747 
5748 /*
5749  * First step in cleanup.
5750  */
5751 /* ARGSUSED */
5752 static void
5753 ip_stack_shutdown(netstackid_t stackid, void *arg)
5754 {
5755 	ip_stack_t *ipst = (ip_stack_t *)arg;
5756 
5757 #ifdef NS_DEBUG
5758 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5759 #endif
5760 
5761 	/* Get rid of loopback interfaces and their IREs */
5762 	ip_loopback_cleanup(ipst);
5763 
5764 	/*
5765 	 * The *_hook_shutdown()s start the process of notifying any
5766 	 * consumers that things are going away.... nothing is destroyed.
5767 	 */
5768 	ipv4_hook_shutdown(ipst);
5769 	ipv6_hook_shutdown(ipst);
5770 
5771 	mutex_enter(&ipst->ips_capab_taskq_lock);
5772 	ipst->ips_capab_taskq_quit = B_TRUE;
5773 	cv_signal(&ipst->ips_capab_taskq_cv);
5774 	mutex_exit(&ipst->ips_capab_taskq_lock);
5775 
5776 	mutex_enter(&ipst->ips_mrt_lock);
5777 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5778 	cv_signal(&ipst->ips_mrt_cv);
5779 	mutex_exit(&ipst->ips_mrt_lock);
5780 }
5781 
5782 /*
5783  * Free the IP stack instance.
5784  */
5785 static void
5786 ip_stack_fini(netstackid_t stackid, void *arg)
5787 {
5788 	ip_stack_t *ipst = (ip_stack_t *)arg;
5789 	int ret;
5790 
5791 #ifdef NS_DEBUG
5792 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5793 #endif
5794 	/*
5795 	 * At this point, all of the notifications that the events and
5796 	 * protocols are going away have been run, meaning that we can
5797 	 * now set about starting to clean things up.
5798 	 */
5799 	ipv4_hook_destroy(ipst);
5800 	ipv6_hook_destroy(ipst);
5801 	ip_net_destroy(ipst);
5802 
5803 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5804 	cv_destroy(&ipst->ips_capab_taskq_cv);
5805 	list_destroy(&ipst->ips_capab_taskq_list);
5806 
5807 	mutex_enter(&ipst->ips_mrt_lock);
5808 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5809 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5810 	mutex_destroy(&ipst->ips_mrt_lock);
5811 	cv_destroy(&ipst->ips_mrt_cv);
5812 	cv_destroy(&ipst->ips_mrt_done_cv);
5813 
5814 	ipmp_destroy(ipst);
5815 	rw_destroy(&ipst->ips_srcid_lock);
5816 
5817 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5818 	ipst->ips_ip_mibkp = NULL;
5819 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5820 	ipst->ips_icmp_mibkp = NULL;
5821 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5822 	ipst->ips_ip_kstat = NULL;
5823 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5824 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5825 	ipst->ips_ip6_kstat = NULL;
5826 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5827 
5828 	nd_free(&ipst->ips_ip_g_nd);
5829 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5830 	ipst->ips_param_arr = NULL;
5831 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5832 	ipst->ips_ndp_arr = NULL;
5833 
5834 	ip_mrouter_stack_destroy(ipst);
5835 
5836 	mutex_destroy(&ipst->ips_ip_mi_lock);
5837 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5838 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5839 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5840 
5841 	ret = untimeout(ipst->ips_igmp_timeout_id);
5842 	if (ret == -1) {
5843 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5844 	} else {
5845 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5846 		ipst->ips_igmp_timeout_id = 0;
5847 	}
5848 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5849 	if (ret == -1) {
5850 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5851 	} else {
5852 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5853 		ipst->ips_igmp_slowtimeout_id = 0;
5854 	}
5855 	ret = untimeout(ipst->ips_mld_timeout_id);
5856 	if (ret == -1) {
5857 		ASSERT(ipst->ips_mld_timeout_id == 0);
5858 	} else {
5859 		ASSERT(ipst->ips_mld_timeout_id != 0);
5860 		ipst->ips_mld_timeout_id = 0;
5861 	}
5862 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5863 	if (ret == -1) {
5864 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5865 	} else {
5866 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5867 		ipst->ips_mld_slowtimeout_id = 0;
5868 	}
5869 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5870 	if (ret == -1) {
5871 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5872 	} else {
5873 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5874 		ipst->ips_ip_ire_expire_id = 0;
5875 	}
5876 
5877 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5878 	mutex_destroy(&ipst->ips_mld_timer_lock);
5879 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5880 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5881 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5882 	rw_destroy(&ipst->ips_ill_g_lock);
5883 
5884 	ipobs_fini(ipst);
5885 	ip_ire_fini(ipst);
5886 	ip6_asp_free(ipst);
5887 	conn_drain_fini(ipst);
5888 	ipcl_destroy(ipst);
5889 
5890 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5891 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5892 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5893 	ipst->ips_ndp4 = NULL;
5894 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5895 	ipst->ips_ndp6 = NULL;
5896 
5897 	if (ipst->ips_loopback_ksp != NULL) {
5898 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5899 		ipst->ips_loopback_ksp = NULL;
5900 	}
5901 
5902 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5903 	ipst->ips_phyint_g_list = NULL;
5904 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5905 	ipst->ips_ill_g_heads = NULL;
5906 
5907 	ldi_ident_release(ipst->ips_ldi_ident);
5908 	kmem_free(ipst, sizeof (*ipst));
5909 }
5910 
5911 /*
5912  * This function is called from the TSD destructor, and is used to debug
5913  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5914  * details.
5915  */
5916 static void
5917 ip_thread_exit(void *phash)
5918 {
5919 	th_hash_t *thh = phash;
5920 
5921 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5922 	list_remove(&ip_thread_list, thh);
5923 	rw_exit(&ip_thread_rwlock);
5924 	mod_hash_destroy_hash(thh->thh_hash);
5925 	kmem_free(thh, sizeof (*thh));
5926 }
5927 
5928 /*
5929  * Called when the IP kernel module is loaded into the kernel
5930  */
5931 void
5932 ip_ddi_init(void)
5933 {
5934 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5935 
5936 	/*
5937 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5938 	 * initial devices: ip, ip6, tcp, tcp6.
5939 	 */
5940 	/*
5941 	 * If this is a 64-bit kernel, then create two separate arenas -
5942 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5943 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5944 	 */
5945 	ip_minor_arena_la = NULL;
5946 	ip_minor_arena_sa = NULL;
5947 #if defined(_LP64)
5948 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5949 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5950 		cmn_err(CE_PANIC,
5951 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5952 	}
5953 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5954 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5955 		cmn_err(CE_PANIC,
5956 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5957 	}
5958 #else
5959 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5960 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5961 		cmn_err(CE_PANIC,
5962 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5963 	}
5964 #endif
5965 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5966 
5967 	ipcl_g_init();
5968 	ip_ire_g_init();
5969 	ip_net_g_init();
5970 
5971 #ifdef DEBUG
5972 	tsd_create(&ip_thread_data, ip_thread_exit);
5973 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5974 	list_create(&ip_thread_list, sizeof (th_hash_t),
5975 	    offsetof(th_hash_t, thh_link));
5976 #endif
5977 
5978 	/*
5979 	 * We want to be informed each time a stack is created or
5980 	 * destroyed in the kernel, so we can maintain the
5981 	 * set of udp_stack_t's.
5982 	 */
5983 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5984 	    ip_stack_fini);
5985 
5986 	ipsec_policy_g_init();
5987 	tcp_ddi_g_init();
5988 	sctp_ddi_g_init();
5989 
5990 	tnet_init();
5991 
5992 	udp_ddi_g_init();
5993 	rts_ddi_g_init();
5994 	icmp_ddi_g_init();
5995 }
5996 
5997 /*
5998  * Initialize the IP stack instance.
5999  */
6000 static void *
6001 ip_stack_init(netstackid_t stackid, netstack_t *ns)
6002 {
6003 	ip_stack_t	*ipst;
6004 	ipparam_t	*pa;
6005 	ipndp_t		*na;
6006 	major_t		major;
6007 
6008 #ifdef NS_DEBUG
6009 	printf("ip_stack_init(stack %d)\n", stackid);
6010 #endif
6011 
6012 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6013 	ipst->ips_netstack = ns;
6014 
6015 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6016 	    KM_SLEEP);
6017 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6018 	    KM_SLEEP);
6019 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6020 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6021 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6022 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6023 
6024 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6025 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6026 	ipst->ips_igmp_deferred_next = INFINITY;
6027 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6028 	ipst->ips_mld_deferred_next = INFINITY;
6029 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6030 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6031 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6032 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6033 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6034 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6035 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6036 
6037 	ipcl_init(ipst);
6038 	ip_ire_init(ipst);
6039 	ip6_asp_init(ipst);
6040 	ipif_init(ipst);
6041 	conn_drain_init(ipst);
6042 	ip_mrouter_stack_init(ipst);
6043 
6044 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6045 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6046 
6047 	ipst->ips_ip_multirt_log_interval = 1000;
6048 
6049 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6050 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6051 	ipst->ips_ill_index = 1;
6052 
6053 	ipst->ips_saved_ip_g_forward = -1;
6054 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6055 
6056 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6057 	ipst->ips_param_arr = pa;
6058 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6059 
6060 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6061 	ipst->ips_ndp_arr = na;
6062 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6063 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6064 	    (caddr_t)&ipst->ips_ip_g_forward;
6065 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6066 	    (caddr_t)&ipst->ips_ipv6_forward;
6067 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6068 	    "ip_cgtp_filter") == 0);
6069 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6070 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6071 
6072 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6073 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6074 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6075 
6076 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6077 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6078 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6079 	ipst->ips_ip6_kstat =
6080 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6081 
6082 	ipst->ips_ip_src_id = 1;
6083 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6084 
6085 	ipobs_init(ipst);
6086 	ip_net_init(ipst, ns);
6087 	ipv4_hook_init(ipst);
6088 	ipv6_hook_init(ipst);
6089 	ipmp_init(ipst);
6090 
6091 	/*
6092 	 * Create the taskq dispatcher thread and initialize related stuff.
6093 	 */
6094 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6095 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6096 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6097 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6098 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6099 	    offsetof(mblk_t, b_next));
6100 
6101 	/*
6102 	 * Create the mcast_restart_timers_thread() worker thread.
6103 	 */
6104 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6105 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6106 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6107 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6108 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6109 
6110 	major = mod_name_to_major(INET_NAME);
6111 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6112 	return (ipst);
6113 }
6114 
6115 /*
6116  * Allocate and initialize a DLPI template of the specified length.  (May be
6117  * called as writer.)
6118  */
6119 mblk_t *
6120 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6121 {
6122 	mblk_t	*mp;
6123 
6124 	mp = allocb(len, BPRI_MED);
6125 	if (!mp)
6126 		return (NULL);
6127 
6128 	/*
6129 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6130 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6131 	 * that other DLPI are M_PROTO.
6132 	 */
6133 	if (prim == DL_INFO_REQ) {
6134 		mp->b_datap->db_type = M_PCPROTO;
6135 	} else {
6136 		mp->b_datap->db_type = M_PROTO;
6137 	}
6138 
6139 	mp->b_wptr = mp->b_rptr + len;
6140 	bzero(mp->b_rptr, len);
6141 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6142 	return (mp);
6143 }
6144 
6145 /*
6146  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6147  */
6148 mblk_t *
6149 ip_dlnotify_alloc(uint_t notification, uint_t data)
6150 {
6151 	dl_notify_ind_t	*notifyp;
6152 	mblk_t		*mp;
6153 
6154 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6155 		return (NULL);
6156 
6157 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6158 	notifyp->dl_notification = notification;
6159 	notifyp->dl_data = data;
6160 	return (mp);
6161 }
6162 
6163 /*
6164  * Debug formatting routine.  Returns a character string representation of the
6165  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6166  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6167  *
6168  * Once the ndd table-printing interfaces are removed, this can be changed to
6169  * standard dotted-decimal form.
6170  */
6171 char *
6172 ip_dot_addr(ipaddr_t addr, char *buf)
6173 {
6174 	uint8_t *ap = (uint8_t *)&addr;
6175 
6176 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6177 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6178 	return (buf);
6179 }
6180 
6181 /*
6182  * Write the given MAC address as a printable string in the usual colon-
6183  * separated format.
6184  */
6185 const char *
6186 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6187 {
6188 	char *bp;
6189 
6190 	if (alen == 0 || buflen < 4)
6191 		return ("?");
6192 	bp = buf;
6193 	for (;;) {
6194 		/*
6195 		 * If there are more MAC address bytes available, but we won't
6196 		 * have any room to print them, then add "..." to the string
6197 		 * instead.  See below for the 'magic number' explanation.
6198 		 */
6199 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6200 			(void) strcpy(bp, "...");
6201 			break;
6202 		}
6203 		(void) sprintf(bp, "%02x", *addr++);
6204 		bp += 2;
6205 		if (--alen == 0)
6206 			break;
6207 		*bp++ = ':';
6208 		buflen -= 3;
6209 		/*
6210 		 * At this point, based on the first 'if' statement above,
6211 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6212 		 * buflen >= 4.  The first case leaves room for the final "xx"
6213 		 * number and trailing NUL byte.  The second leaves room for at
6214 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6215 		 * that statement.
6216 		 */
6217 	}
6218 	return (buf);
6219 }
6220 
6221 /*
6222  * Send an ICMP error after patching up the packet appropriately.  Returns
6223  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6224  */
6225 static boolean_t
6226 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6227     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6228     zoneid_t zoneid, ip_stack_t *ipst)
6229 {
6230 	ipha_t *ipha;
6231 	mblk_t *first_mp;
6232 	boolean_t secure;
6233 	unsigned char db_type;
6234 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6235 
6236 	first_mp = mp;
6237 	if (mctl_present) {
6238 		mp = mp->b_cont;
6239 		secure = ipsec_in_is_secure(first_mp);
6240 		ASSERT(mp != NULL);
6241 	} else {
6242 		/*
6243 		 * If this is an ICMP error being reported - which goes
6244 		 * up as M_CTLs, we need to convert them to M_DATA till
6245 		 * we finish checking with global policy because
6246 		 * ipsec_check_global_policy() assumes M_DATA as clear
6247 		 * and M_CTL as secure.
6248 		 */
6249 		db_type = DB_TYPE(mp);
6250 		DB_TYPE(mp) = M_DATA;
6251 		secure = B_FALSE;
6252 	}
6253 	/*
6254 	 * We are generating an icmp error for some inbound packet.
6255 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6256 	 * Before we generate an error, check with global policy
6257 	 * to see whether this is allowed to enter the system. As
6258 	 * there is no "conn", we are checking with global policy.
6259 	 */
6260 	ipha = (ipha_t *)mp->b_rptr;
6261 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6262 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6263 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6264 		if (first_mp == NULL)
6265 			return (B_FALSE);
6266 	}
6267 
6268 	if (!mctl_present)
6269 		DB_TYPE(mp) = db_type;
6270 
6271 	if (flags & IP_FF_SEND_ICMP) {
6272 		if (flags & IP_FF_HDR_COMPLETE) {
6273 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6274 				freemsg(first_mp);
6275 				return (B_TRUE);
6276 			}
6277 		}
6278 		if (flags & IP_FF_CKSUM) {
6279 			/*
6280 			 * Have to correct checksum since
6281 			 * the packet might have been
6282 			 * fragmented and the reassembly code in ip_rput
6283 			 * does not restore the IP checksum.
6284 			 */
6285 			ipha->ipha_hdr_checksum = 0;
6286 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6287 		}
6288 		switch (icmp_type) {
6289 		case ICMP_DEST_UNREACHABLE:
6290 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6291 			    ipst);
6292 			break;
6293 		default:
6294 			freemsg(first_mp);
6295 			break;
6296 		}
6297 	} else {
6298 		freemsg(first_mp);
6299 		return (B_FALSE);
6300 	}
6301 
6302 	return (B_TRUE);
6303 }
6304 
6305 /*
6306  * Used to send an ICMP error message when a packet is received for
6307  * a protocol that is not supported. The mblk passed as argument
6308  * is consumed by this function.
6309  */
6310 void
6311 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6312     ip_stack_t *ipst)
6313 {
6314 	mblk_t *mp;
6315 	ipha_t *ipha;
6316 	ill_t *ill;
6317 	ipsec_in_t *ii;
6318 
6319 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6320 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6321 
6322 	mp = ipsec_mp->b_cont;
6323 	ipsec_mp->b_cont = NULL;
6324 	ipha = (ipha_t *)mp->b_rptr;
6325 	/* Get ill from index in ipsec_in_t. */
6326 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6327 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6328 	    ipst);
6329 	if (ill != NULL) {
6330 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6331 			if (ip_fanout_send_icmp(q, mp, flags,
6332 			    ICMP_DEST_UNREACHABLE,
6333 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6334 				BUMP_MIB(ill->ill_ip_mib,
6335 				    ipIfStatsInUnknownProtos);
6336 			}
6337 		} else {
6338 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6339 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6340 			    0, B_FALSE, zoneid, ipst)) {
6341 				BUMP_MIB(ill->ill_ip_mib,
6342 				    ipIfStatsInUnknownProtos);
6343 			}
6344 		}
6345 		ill_refrele(ill);
6346 	} else { /* re-link for the freemsg() below. */
6347 		ipsec_mp->b_cont = mp;
6348 	}
6349 
6350 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6351 	freemsg(ipsec_mp);
6352 }
6353 
6354 /*
6355  * See if the inbound datagram has had IPsec processing applied to it.
6356  */
6357 boolean_t
6358 ipsec_in_is_secure(mblk_t *ipsec_mp)
6359 {
6360 	ipsec_in_t *ii;
6361 
6362 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6363 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6364 
6365 	if (ii->ipsec_in_loopback) {
6366 		return (ii->ipsec_in_secure);
6367 	} else {
6368 		return (ii->ipsec_in_ah_sa != NULL ||
6369 		    ii->ipsec_in_esp_sa != NULL ||
6370 		    ii->ipsec_in_decaps);
6371 	}
6372 }
6373 
6374 /*
6375  * Handle protocols with which IP is less intimate.  There
6376  * can be more than one stream bound to a particular
6377  * protocol.  When this is the case, normally each one gets a copy
6378  * of any incoming packets.
6379  *
6380  * IPsec NOTE :
6381  *
6382  * Don't allow a secure packet going up a non-secure connection.
6383  * We don't allow this because
6384  *
6385  * 1) Reply might go out in clear which will be dropped at
6386  *    the sending side.
6387  * 2) If the reply goes out in clear it will give the
6388  *    adversary enough information for getting the key in
6389  *    most of the cases.
6390  *
6391  * Moreover getting a secure packet when we expect clear
6392  * implies that SA's were added without checking for
6393  * policy on both ends. This should not happen once ISAKMP
6394  * is used to negotiate SAs as SAs will be added only after
6395  * verifying the policy.
6396  *
6397  * NOTE : If the packet was tunneled and not multicast we only send
6398  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6399  * back to delivering packets to AF_INET6 raw sockets.
6400  *
6401  * IPQoS Notes:
6402  * Once we have determined the client, invoke IPPF processing.
6403  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6404  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6405  * ip_policy will be false.
6406  *
6407  * Zones notes:
6408  * Currently only applications in the global zone can create raw sockets for
6409  * protocols other than ICMP. So unlike the broadcast / multicast case of
6410  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6411  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6412  */
6413 static void
6414 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6415     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6416     zoneid_t zoneid)
6417 {
6418 	queue_t	*rq;
6419 	mblk_t	*mp1, *first_mp1;
6420 	uint_t	protocol = ipha->ipha_protocol;
6421 	ipaddr_t dst;
6422 	boolean_t one_only;
6423 	mblk_t *first_mp = mp;
6424 	boolean_t secure;
6425 	uint32_t ill_index;
6426 	conn_t	*connp, *first_connp, *next_connp;
6427 	connf_t	*connfp;
6428 	boolean_t shared_addr;
6429 	mib2_ipIfStatsEntry_t *mibptr;
6430 	ip_stack_t *ipst = recv_ill->ill_ipst;
6431 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6432 
6433 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6434 	if (mctl_present) {
6435 		mp = first_mp->b_cont;
6436 		secure = ipsec_in_is_secure(first_mp);
6437 		ASSERT(mp != NULL);
6438 	} else {
6439 		secure = B_FALSE;
6440 	}
6441 	dst = ipha->ipha_dst;
6442 	/*
6443 	 * If the packet was tunneled and not multicast we only send to it
6444 	 * the first match.
6445 	 */
6446 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6447 	    !CLASSD(dst));
6448 
6449 	shared_addr = (zoneid == ALL_ZONES);
6450 	if (shared_addr) {
6451 		/*
6452 		 * We don't allow multilevel ports for raw IP, so no need to
6453 		 * check for that here.
6454 		 */
6455 		zoneid = tsol_packet_to_zoneid(mp);
6456 	}
6457 
6458 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6459 	mutex_enter(&connfp->connf_lock);
6460 	connp = connfp->connf_head;
6461 	for (connp = connfp->connf_head; connp != NULL;
6462 	    connp = connp->conn_next) {
6463 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6464 		    zoneid) &&
6465 		    (!is_system_labeled() ||
6466 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6467 		    connp))) {
6468 			break;
6469 		}
6470 	}
6471 
6472 	if (connp == NULL) {
6473 		/*
6474 		 * No one bound to these addresses.  Is
6475 		 * there a client that wants all
6476 		 * unclaimed datagrams?
6477 		 */
6478 		mutex_exit(&connfp->connf_lock);
6479 		/*
6480 		 * Check for IPPROTO_ENCAP...
6481 		 */
6482 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6483 			/*
6484 			 * If an IPsec mblk is here on a multicast
6485 			 * tunnel (using ip_mroute stuff), check policy here,
6486 			 * THEN ship off to ip_mroute_decap().
6487 			 *
6488 			 * BTW,  If I match a configured IP-in-IP
6489 			 * tunnel, this path will not be reached, and
6490 			 * ip_mroute_decap will never be called.
6491 			 */
6492 			first_mp = ipsec_check_global_policy(first_mp, connp,
6493 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6494 			if (first_mp != NULL) {
6495 				if (mctl_present)
6496 					freeb(first_mp);
6497 				ip_mroute_decap(q, mp, ill);
6498 			} /* Else we already freed everything! */
6499 		} else {
6500 			/*
6501 			 * Otherwise send an ICMP protocol unreachable.
6502 			 */
6503 			if (ip_fanout_send_icmp(q, first_mp, flags,
6504 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6505 			    mctl_present, zoneid, ipst)) {
6506 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6507 			}
6508 		}
6509 		return;
6510 	}
6511 
6512 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6513 
6514 	CONN_INC_REF(connp);
6515 	first_connp = connp;
6516 
6517 	/*
6518 	 * Only send message to one tunnel driver by immediately
6519 	 * terminating the loop.
6520 	 */
6521 	connp = one_only ? NULL : connp->conn_next;
6522 
6523 	for (;;) {
6524 		while (connp != NULL) {
6525 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6526 			    flags, zoneid) &&
6527 			    (!is_system_labeled() ||
6528 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6529 			    shared_addr, connp)))
6530 				break;
6531 			connp = connp->conn_next;
6532 		}
6533 
6534 		/*
6535 		 * Copy the packet.
6536 		 */
6537 		if (connp == NULL ||
6538 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6539 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6540 			/*
6541 			 * No more interested clients or memory
6542 			 * allocation failed
6543 			 */
6544 			connp = first_connp;
6545 			break;
6546 		}
6547 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6548 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6549 		CONN_INC_REF(connp);
6550 		mutex_exit(&connfp->connf_lock);
6551 		rq = connp->conn_rq;
6552 
6553 		/*
6554 		 * Check flow control
6555 		 */
6556 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6557 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6558 			if (flags & IP_FF_RAWIP) {
6559 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6560 			} else {
6561 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6562 			}
6563 
6564 			freemsg(first_mp1);
6565 		} else {
6566 			/*
6567 			 * Don't enforce here if we're an actual tunnel -
6568 			 * let "tun" do it instead.
6569 			 */
6570 			if (!IPCL_IS_IPTUN(connp) &&
6571 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6572 			    secure)) {
6573 				first_mp1 = ipsec_check_inbound_policy
6574 				    (first_mp1, connp, ipha, NULL,
6575 				    mctl_present);
6576 			}
6577 			if (first_mp1 != NULL) {
6578 				int in_flags = 0;
6579 				/*
6580 				 * ip_fanout_proto also gets called from
6581 				 * icmp_inbound_error_fanout, in which case
6582 				 * the msg type is M_CTL.  Don't add info
6583 				 * in this case for the time being. In future
6584 				 * when there is a need for knowing the
6585 				 * inbound iface index for ICMP error msgs,
6586 				 * then this can be changed.
6587 				 */
6588 				if (connp->conn_recvif)
6589 					in_flags = IPF_RECVIF;
6590 				/*
6591 				 * The ULP may support IP_RECVPKTINFO for both
6592 				 * IP v4 and v6 so pass the appropriate argument
6593 				 * based on conn IP version.
6594 				 */
6595 				if (connp->conn_ip_recvpktinfo) {
6596 					if (connp->conn_af_isv6) {
6597 						/*
6598 						 * V6 only needs index
6599 						 */
6600 						in_flags |= IPF_RECVIF;
6601 					} else {
6602 						/*
6603 						 * V4 needs index +
6604 						 * matching address.
6605 						 */
6606 						in_flags |= IPF_RECVADDR;
6607 					}
6608 				}
6609 				if ((in_flags != 0) &&
6610 				    (mp->b_datap->db_type != M_CTL)) {
6611 					/*
6612 					 * the actual data will be
6613 					 * contained in b_cont upon
6614 					 * successful return of the
6615 					 * following call else
6616 					 * original mblk is returned
6617 					 */
6618 					ASSERT(recv_ill != NULL);
6619 					mp1 = ip_add_info(mp1, recv_ill,
6620 					    in_flags, IPCL_ZONEID(connp), ipst);
6621 				}
6622 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6623 				if (mctl_present)
6624 					freeb(first_mp1);
6625 				(connp->conn_recv)(connp, mp1, NULL);
6626 			}
6627 		}
6628 		mutex_enter(&connfp->connf_lock);
6629 		/* Follow the next pointer before releasing the conn. */
6630 		next_connp = connp->conn_next;
6631 		CONN_DEC_REF(connp);
6632 		connp = next_connp;
6633 	}
6634 
6635 	/* Last one.  Send it upstream. */
6636 	mutex_exit(&connfp->connf_lock);
6637 
6638 	/*
6639 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6640 	 * will be set to false.
6641 	 */
6642 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6643 		ill_index = ill->ill_phyint->phyint_ifindex;
6644 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6645 		if (mp == NULL) {
6646 			CONN_DEC_REF(connp);
6647 			if (mctl_present) {
6648 				freeb(first_mp);
6649 			}
6650 			return;
6651 		}
6652 	}
6653 
6654 	rq = connp->conn_rq;
6655 	/*
6656 	 * Check flow control
6657 	 */
6658 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6659 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6660 		if (flags & IP_FF_RAWIP) {
6661 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6662 		} else {
6663 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6664 		}
6665 
6666 		freemsg(first_mp);
6667 	} else {
6668 		if (IPCL_IS_IPTUN(connp)) {
6669 			/*
6670 			 * Tunneled packet.  We enforce policy in the tunnel
6671 			 * module itself.
6672 			 *
6673 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6674 			 * a policy check.
6675 			 * FIXME to use conn_recv for tun later.
6676 			 */
6677 			putnext(rq, first_mp);
6678 			CONN_DEC_REF(connp);
6679 			return;
6680 		}
6681 
6682 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6683 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6684 			    ipha, NULL, mctl_present);
6685 		}
6686 
6687 		if (first_mp != NULL) {
6688 			int in_flags = 0;
6689 
6690 			/*
6691 			 * ip_fanout_proto also gets called
6692 			 * from icmp_inbound_error_fanout, in
6693 			 * which case the msg type is M_CTL.
6694 			 * Don't add info in this case for time
6695 			 * being. In future when there is a
6696 			 * need for knowing the inbound iface
6697 			 * index for ICMP error msgs, then this
6698 			 * can be changed
6699 			 */
6700 			if (connp->conn_recvif)
6701 				in_flags = IPF_RECVIF;
6702 			if (connp->conn_ip_recvpktinfo) {
6703 				if (connp->conn_af_isv6) {
6704 					/*
6705 					 * V6 only needs index
6706 					 */
6707 					in_flags |= IPF_RECVIF;
6708 				} else {
6709 					/*
6710 					 * V4 needs index +
6711 					 * matching address.
6712 					 */
6713 					in_flags |= IPF_RECVADDR;
6714 				}
6715 			}
6716 			if ((in_flags != 0) &&
6717 			    (mp->b_datap->db_type != M_CTL)) {
6718 
6719 				/*
6720 				 * the actual data will be contained in
6721 				 * b_cont upon successful return
6722 				 * of the following call else original
6723 				 * mblk is returned
6724 				 */
6725 				ASSERT(recv_ill != NULL);
6726 				mp = ip_add_info(mp, recv_ill,
6727 				    in_flags, IPCL_ZONEID(connp), ipst);
6728 			}
6729 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6730 			(connp->conn_recv)(connp, mp, NULL);
6731 			if (mctl_present)
6732 				freeb(first_mp);
6733 		}
6734 	}
6735 	CONN_DEC_REF(connp);
6736 }
6737 
6738 /*
6739  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6740  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6741  * the correct squeue, in this case the same squeue as a valid listener with
6742  * no current connection state for the packet we are processing. The function
6743  * is called for synchronizing both IPv4 and IPv6.
6744  */
6745 void
6746 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6747     tcp_stack_t *tcps, conn_t *connp)
6748 {
6749 	mblk_t *rst_mp;
6750 	tcp_xmit_reset_event_t *eventp;
6751 
6752 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6753 
6754 	if (rst_mp == NULL) {
6755 		freemsg(mp);
6756 		return;
6757 	}
6758 
6759 	rst_mp->b_datap->db_type = M_PROTO;
6760 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6761 
6762 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6763 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6764 	eventp->tcp_xre_iphdrlen = hdrlen;
6765 	eventp->tcp_xre_zoneid = zoneid;
6766 	eventp->tcp_xre_tcps = tcps;
6767 
6768 	rst_mp->b_cont = mp;
6769 	mp = rst_mp;
6770 
6771 	/*
6772 	 * Increment the connref, this ref will be released by the squeue
6773 	 * framework.
6774 	 */
6775 	CONN_INC_REF(connp);
6776 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6777 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6778 }
6779 
6780 /*
6781  * Fanout for TCP packets
6782  * The caller puts <fport, lport> in the ports parameter.
6783  *
6784  * IPQoS Notes
6785  * Before sending it to the client, invoke IPPF processing.
6786  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6787  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6788  * ip_policy is false.
6789  */
6790 static void
6791 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6792     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6793 {
6794 	mblk_t  *first_mp;
6795 	boolean_t secure;
6796 	uint32_t ill_index;
6797 	int	ip_hdr_len;
6798 	tcph_t	*tcph;
6799 	boolean_t syn_present = B_FALSE;
6800 	conn_t	*connp;
6801 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6802 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6803 
6804 	ASSERT(recv_ill != NULL);
6805 
6806 	first_mp = mp;
6807 	if (mctl_present) {
6808 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6809 		mp = first_mp->b_cont;
6810 		secure = ipsec_in_is_secure(first_mp);
6811 		ASSERT(mp != NULL);
6812 	} else {
6813 		secure = B_FALSE;
6814 	}
6815 
6816 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6817 
6818 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6819 	    zoneid, ipst)) == NULL) {
6820 		/*
6821 		 * No connected connection or listener. Send a
6822 		 * TH_RST via tcp_xmit_listeners_reset.
6823 		 */
6824 
6825 		/* Initiate IPPf processing, if needed. */
6826 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6827 			uint32_t ill_index;
6828 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6829 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6830 			if (first_mp == NULL)
6831 				return;
6832 		}
6833 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6834 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6835 		    zoneid));
6836 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6837 		    ipst->ips_netstack->netstack_tcp, NULL);
6838 		return;
6839 	}
6840 
6841 	/*
6842 	 * Allocate the SYN for the TCP connection here itself
6843 	 */
6844 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6845 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6846 		if (IPCL_IS_TCP(connp)) {
6847 			squeue_t *sqp;
6848 
6849 			/*
6850 			 * For fused tcp loopback, assign the eager's
6851 			 * squeue to be that of the active connect's.
6852 			 * Note that we don't check for IP_FF_LOOPBACK
6853 			 * here since this routine gets called only
6854 			 * for loopback (unlike the IPv6 counterpart).
6855 			 */
6856 			ASSERT(Q_TO_CONN(q) != NULL);
6857 			if (do_tcp_fusion &&
6858 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6859 			    !secure &&
6860 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6861 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6862 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6863 				sqp = Q_TO_CONN(q)->conn_sqp;
6864 			} else {
6865 				sqp = IP_SQUEUE_GET(lbolt);
6866 			}
6867 
6868 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6869 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6870 			syn_present = B_TRUE;
6871 		}
6872 	}
6873 
6874 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6875 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6876 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6877 		if ((flags & TH_RST) || (flags & TH_URG)) {
6878 			CONN_DEC_REF(connp);
6879 			freemsg(first_mp);
6880 			return;
6881 		}
6882 		if (flags & TH_ACK) {
6883 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6884 			    ipst->ips_netstack->netstack_tcp, connp);
6885 			CONN_DEC_REF(connp);
6886 			return;
6887 		}
6888 
6889 		CONN_DEC_REF(connp);
6890 		freemsg(first_mp);
6891 		return;
6892 	}
6893 
6894 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6895 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6896 		    NULL, mctl_present);
6897 		if (first_mp == NULL) {
6898 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6899 			CONN_DEC_REF(connp);
6900 			return;
6901 		}
6902 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6903 			ASSERT(syn_present);
6904 			if (mctl_present) {
6905 				ASSERT(first_mp != mp);
6906 				first_mp->b_datap->db_struioflag |=
6907 				    STRUIO_POLICY;
6908 			} else {
6909 				ASSERT(first_mp == mp);
6910 				mp->b_datap->db_struioflag &=
6911 				    ~STRUIO_EAGER;
6912 				mp->b_datap->db_struioflag |=
6913 				    STRUIO_POLICY;
6914 			}
6915 		} else {
6916 			/*
6917 			 * Discard first_mp early since we're dealing with a
6918 			 * fully-connected conn_t and tcp doesn't do policy in
6919 			 * this case.
6920 			 */
6921 			if (mctl_present) {
6922 				freeb(first_mp);
6923 				mctl_present = B_FALSE;
6924 			}
6925 			first_mp = mp;
6926 		}
6927 	}
6928 
6929 	/*
6930 	 * Initiate policy processing here if needed. If we get here from
6931 	 * icmp_inbound_error_fanout, ip_policy is false.
6932 	 */
6933 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6934 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6935 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6936 		if (mp == NULL) {
6937 			CONN_DEC_REF(connp);
6938 			if (mctl_present)
6939 				freeb(first_mp);
6940 			return;
6941 		} else if (mctl_present) {
6942 			ASSERT(first_mp != mp);
6943 			first_mp->b_cont = mp;
6944 		} else {
6945 			first_mp = mp;
6946 		}
6947 	}
6948 
6949 	/* Handle socket options. */
6950 	if (!syn_present &&
6951 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6952 		/* Add header */
6953 		ASSERT(recv_ill != NULL);
6954 		/*
6955 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6956 		 * IPF_RECVIF.
6957 		 */
6958 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6959 		    ipst);
6960 		if (mp == NULL) {
6961 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6962 			CONN_DEC_REF(connp);
6963 			if (mctl_present)
6964 				freeb(first_mp);
6965 			return;
6966 		} else if (mctl_present) {
6967 			/*
6968 			 * ip_add_info might return a new mp.
6969 			 */
6970 			ASSERT(first_mp != mp);
6971 			first_mp->b_cont = mp;
6972 		} else {
6973 			first_mp = mp;
6974 		}
6975 	}
6976 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6977 	if (IPCL_IS_TCP(connp)) {
6978 		/* do not drain, certain use cases can blow the stack */
6979 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6980 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6981 	} else {
6982 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6983 		(connp->conn_recv)(connp, first_mp, NULL);
6984 		CONN_DEC_REF(connp);
6985 	}
6986 }
6987 
6988 /*
6989  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6990  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6991  * is not consumed.
6992  *
6993  * One of four things can happen, all of which affect the passed-in mblk:
6994  *
6995  * 1.) ICMP messages that go through here just get returned TRUE.
6996  *
6997  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6998  *
6999  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
7000  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
7001  *
7002  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
7003  */
7004 static boolean_t
7005 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
7006     ipsec_stack_t *ipss)
7007 {
7008 	int shift, plen, iph_len;
7009 	ipha_t *ipha;
7010 	udpha_t *udpha;
7011 	uint32_t *spi;
7012 	uint32_t esp_ports;
7013 	uint8_t *orptr;
7014 	boolean_t free_ire;
7015 
7016 	if (DB_TYPE(mp) == M_CTL) {
7017 		/*
7018 		 * ICMP message with UDP inside.  Don't bother stripping, just
7019 		 * send it up.
7020 		 *
7021 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
7022 		 * to ignore errors set by ICMP anyway ('cause they might be
7023 		 * forged), but that's the app's decision, not ours.
7024 		 */
7025 
7026 		/* Bunch of reality checks for DEBUG kernels... */
7027 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
7028 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
7029 
7030 		return (B_TRUE);
7031 	}
7032 
7033 	ipha = (ipha_t *)mp->b_rptr;
7034 	iph_len = IPH_HDR_LENGTH(ipha);
7035 	plen = ntohs(ipha->ipha_length);
7036 
7037 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
7038 		/*
7039 		 * Most likely a keepalive for the benefit of an intervening
7040 		 * NAT.  These aren't for us, per se, so drop it.
7041 		 *
7042 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
7043 		 * byte packets (keepalives are 1-byte), but we'll drop them
7044 		 * also.
7045 		 */
7046 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7047 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7048 		return (B_FALSE);
7049 	}
7050 
7051 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7052 		/* might as well pull it all up - it might be ESP. */
7053 		if (!pullupmsg(mp, -1)) {
7054 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7055 			    DROPPER(ipss, ipds_esp_nomem),
7056 			    &ipss->ipsec_dropper);
7057 			return (B_FALSE);
7058 		}
7059 
7060 		ipha = (ipha_t *)mp->b_rptr;
7061 	}
7062 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7063 	if (*spi == 0) {
7064 		/* UDP packet - remove 0-spi. */
7065 		shift = sizeof (uint32_t);
7066 	} else {
7067 		/* ESP-in-UDP packet - reduce to ESP. */
7068 		ipha->ipha_protocol = IPPROTO_ESP;
7069 		shift = sizeof (udpha_t);
7070 	}
7071 
7072 	/* Fix IP header */
7073 	ipha->ipha_length = htons(plen - shift);
7074 	ipha->ipha_hdr_checksum = 0;
7075 
7076 	orptr = mp->b_rptr;
7077 	mp->b_rptr += shift;
7078 
7079 	udpha = (udpha_t *)(orptr + iph_len);
7080 	if (*spi == 0) {
7081 		ASSERT((uint8_t *)ipha == orptr);
7082 		udpha->uha_length = htons(plen - shift - iph_len);
7083 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7084 		esp_ports = 0;
7085 	} else {
7086 		esp_ports = *((uint32_t *)udpha);
7087 		ASSERT(esp_ports != 0);
7088 	}
7089 	ovbcopy(orptr, orptr + shift, iph_len);
7090 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7091 		ipha = (ipha_t *)(orptr + shift);
7092 
7093 		free_ire = (ire == NULL);
7094 		if (free_ire) {
7095 			/* Re-acquire ire. */
7096 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7097 			    ipss->ipsec_netstack->netstack_ip);
7098 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7099 				if (ire != NULL)
7100 					ire_refrele(ire);
7101 				/*
7102 				 * Do a regular freemsg(), as this is an IP
7103 				 * error (no local route) not an IPsec one.
7104 				 */
7105 				freemsg(mp);
7106 			}
7107 		}
7108 
7109 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7110 		if (free_ire)
7111 			ire_refrele(ire);
7112 	}
7113 
7114 	return (esp_ports == 0);
7115 }
7116 
7117 /*
7118  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7119  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7120  * Caller is responsible for dropping references to the conn, and freeing
7121  * first_mp.
7122  *
7123  * IPQoS Notes
7124  * Before sending it to the client, invoke IPPF processing. Policy processing
7125  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7126  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7127  * ip_wput_local, ip_policy is false.
7128  */
7129 static void
7130 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7131     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7132     boolean_t ip_policy)
7133 {
7134 	boolean_t	mctl_present = (first_mp != NULL);
7135 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7136 	uint32_t	ill_index;
7137 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7138 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7139 
7140 	ASSERT(ill != NULL);
7141 
7142 	if (mctl_present)
7143 		first_mp->b_cont = mp;
7144 	else
7145 		first_mp = mp;
7146 
7147 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7148 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7149 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7150 		freemsg(first_mp);
7151 		return;
7152 	}
7153 
7154 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7155 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7156 		    NULL, mctl_present);
7157 		/* Freed by ipsec_check_inbound_policy(). */
7158 		if (first_mp == NULL) {
7159 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7160 			return;
7161 		}
7162 	}
7163 	if (mctl_present)
7164 		freeb(first_mp);
7165 
7166 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7167 	if (connp->conn_udp->udp_nat_t_endpoint) {
7168 		if (mctl_present) {
7169 			/* mctl_present *shouldn't* happen. */
7170 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7171 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7172 			    &ipss->ipsec_dropper);
7173 			return;
7174 		}
7175 
7176 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7177 			return;
7178 	}
7179 
7180 	/* Handle options. */
7181 	if (connp->conn_recvif)
7182 		in_flags = IPF_RECVIF;
7183 	/*
7184 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7185 	 * passed to ip_add_info is based on IP version of connp.
7186 	 */
7187 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7188 		if (connp->conn_af_isv6) {
7189 			/*
7190 			 * V6 only needs index
7191 			 */
7192 			in_flags |= IPF_RECVIF;
7193 		} else {
7194 			/*
7195 			 * V4 needs index + matching address.
7196 			 */
7197 			in_flags |= IPF_RECVADDR;
7198 		}
7199 	}
7200 
7201 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7202 		in_flags |= IPF_RECVSLLA;
7203 
7204 	/*
7205 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7206 	 * freed if the packet is dropped. The caller will do so.
7207 	 */
7208 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7209 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7210 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7211 		if (mp == NULL) {
7212 			return;
7213 		}
7214 	}
7215 	if ((in_flags != 0) &&
7216 	    (mp->b_datap->db_type != M_CTL)) {
7217 		/*
7218 		 * The actual data will be contained in b_cont
7219 		 * upon successful return of the following call
7220 		 * else original mblk is returned
7221 		 */
7222 		ASSERT(recv_ill != NULL);
7223 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7224 		    ipst);
7225 	}
7226 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7227 	/* Send it upstream */
7228 	(connp->conn_recv)(connp, mp, NULL);
7229 }
7230 
7231 /*
7232  * Fanout for UDP packets.
7233  * The caller puts <fport, lport> in the ports parameter.
7234  *
7235  * If SO_REUSEADDR is set all multicast and broadcast packets
7236  * will be delivered to all streams bound to the same port.
7237  *
7238  * Zones notes:
7239  * Multicast and broadcast packets will be distributed to streams in all zones.
7240  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7241  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7242  * packets. To maintain this behavior with multiple zones, the conns are grouped
7243  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7244  * each zone. If unset, all the following conns in the same zone are skipped.
7245  */
7246 static void
7247 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7248     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7249     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7250 {
7251 	uint32_t	dstport, srcport;
7252 	ipaddr_t	dst;
7253 	mblk_t		*first_mp;
7254 	boolean_t	secure;
7255 	in6_addr_t	v6src;
7256 	conn_t		*connp;
7257 	connf_t		*connfp;
7258 	conn_t		*first_connp;
7259 	conn_t		*next_connp;
7260 	mblk_t		*mp1, *first_mp1;
7261 	ipaddr_t	src;
7262 	zoneid_t	last_zoneid;
7263 	boolean_t	reuseaddr;
7264 	boolean_t	shared_addr;
7265 	boolean_t	unlabeled;
7266 	ip_stack_t	*ipst;
7267 
7268 	ASSERT(recv_ill != NULL);
7269 	ipst = recv_ill->ill_ipst;
7270 
7271 	first_mp = mp;
7272 	if (mctl_present) {
7273 		mp = first_mp->b_cont;
7274 		first_mp->b_cont = NULL;
7275 		secure = ipsec_in_is_secure(first_mp);
7276 		ASSERT(mp != NULL);
7277 	} else {
7278 		first_mp = NULL;
7279 		secure = B_FALSE;
7280 	}
7281 
7282 	/* Extract ports in net byte order */
7283 	dstport = htons(ntohl(ports) & 0xFFFF);
7284 	srcport = htons(ntohl(ports) >> 16);
7285 	dst = ipha->ipha_dst;
7286 	src = ipha->ipha_src;
7287 
7288 	unlabeled = B_FALSE;
7289 	if (is_system_labeled())
7290 		/* Cred cannot be null on IPv4 */
7291 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7292 		    TSLF_UNLABELED) != 0;
7293 	shared_addr = (zoneid == ALL_ZONES);
7294 	if (shared_addr) {
7295 		/*
7296 		 * No need to handle exclusive-stack zones since ALL_ZONES
7297 		 * only applies to the shared stack.
7298 		 */
7299 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7300 		/*
7301 		 * If no shared MLP is found, tsol_mlp_findzone returns
7302 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7303 		 * search for the zone based on the packet label.
7304 		 *
7305 		 * If there is such a zone, we prefer to find a
7306 		 * connection in it.  Otherwise, we look for a
7307 		 * MAC-exempt connection in any zone whose label
7308 		 * dominates the default label on the packet.
7309 		 */
7310 		if (zoneid == ALL_ZONES)
7311 			zoneid = tsol_packet_to_zoneid(mp);
7312 		else
7313 			unlabeled = B_FALSE;
7314 	}
7315 
7316 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7317 	mutex_enter(&connfp->connf_lock);
7318 	connp = connfp->connf_head;
7319 	if (!broadcast && !CLASSD(dst)) {
7320 		/*
7321 		 * Not broadcast or multicast. Send to the one (first)
7322 		 * client we find. No need to check conn_wantpacket()
7323 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7324 		 * IPv4 unicast packets.
7325 		 */
7326 		while ((connp != NULL) &&
7327 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7328 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7329 		    !(unlabeled && connp->conn_mac_exempt)))) {
7330 			/*
7331 			 * We keep searching since the conn did not match,
7332 			 * or its zone did not match and it is not either
7333 			 * an allzones conn or a mac exempt conn (if the
7334 			 * sender is unlabeled.)
7335 			 */
7336 			connp = connp->conn_next;
7337 		}
7338 
7339 		if (connp == NULL ||
7340 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7341 			goto notfound;
7342 
7343 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7344 
7345 		if (is_system_labeled() &&
7346 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7347 		    connp))
7348 			goto notfound;
7349 
7350 		CONN_INC_REF(connp);
7351 		mutex_exit(&connfp->connf_lock);
7352 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7353 		    flags, recv_ill, ip_policy);
7354 		IP_STAT(ipst, ip_udp_fannorm);
7355 		CONN_DEC_REF(connp);
7356 		return;
7357 	}
7358 
7359 	/*
7360 	 * Broadcast and multicast case
7361 	 *
7362 	 * Need to check conn_wantpacket().
7363 	 * If SO_REUSEADDR has been set on the first we send the
7364 	 * packet to all clients that have joined the group and
7365 	 * match the port.
7366 	 */
7367 
7368 	while (connp != NULL) {
7369 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7370 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7371 		    (!is_system_labeled() ||
7372 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7373 		    connp)))
7374 			break;
7375 		connp = connp->conn_next;
7376 	}
7377 
7378 	if (connp == NULL ||
7379 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7380 		goto notfound;
7381 
7382 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7383 
7384 	first_connp = connp;
7385 	/*
7386 	 * When SO_REUSEADDR is not set, send the packet only to the first
7387 	 * matching connection in its zone by keeping track of the zoneid.
7388 	 */
7389 	reuseaddr = first_connp->conn_reuseaddr;
7390 	last_zoneid = first_connp->conn_zoneid;
7391 
7392 	CONN_INC_REF(connp);
7393 	connp = connp->conn_next;
7394 	for (;;) {
7395 		while (connp != NULL) {
7396 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7397 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7398 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7399 			    (!is_system_labeled() ||
7400 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7401 			    shared_addr, connp)))
7402 				break;
7403 			connp = connp->conn_next;
7404 		}
7405 		/*
7406 		 * Just copy the data part alone. The mctl part is
7407 		 * needed just for verifying policy and it is never
7408 		 * sent up.
7409 		 */
7410 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7411 		    ((mp1 = copymsg(mp)) == NULL))) {
7412 			/*
7413 			 * No more interested clients or memory
7414 			 * allocation failed
7415 			 */
7416 			connp = first_connp;
7417 			break;
7418 		}
7419 		if (connp->conn_zoneid != last_zoneid) {
7420 			/*
7421 			 * Update the zoneid so that the packet isn't sent to
7422 			 * any more conns in the same zone unless SO_REUSEADDR
7423 			 * is set.
7424 			 */
7425 			reuseaddr = connp->conn_reuseaddr;
7426 			last_zoneid = connp->conn_zoneid;
7427 		}
7428 		if (first_mp != NULL) {
7429 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7430 			    ipsec_info_type == IPSEC_IN);
7431 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7432 			    ipst->ips_netstack);
7433 			if (first_mp1 == NULL) {
7434 				freemsg(mp1);
7435 				connp = first_connp;
7436 				break;
7437 			}
7438 		} else {
7439 			first_mp1 = NULL;
7440 		}
7441 		CONN_INC_REF(connp);
7442 		mutex_exit(&connfp->connf_lock);
7443 		/*
7444 		 * IPQoS notes: We don't send the packet for policy
7445 		 * processing here, will do it for the last one (below).
7446 		 * i.e. we do it per-packet now, but if we do policy
7447 		 * processing per-conn, then we would need to do it
7448 		 * here too.
7449 		 */
7450 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7451 		    ipha, flags, recv_ill, B_FALSE);
7452 		mutex_enter(&connfp->connf_lock);
7453 		/* Follow the next pointer before releasing the conn. */
7454 		next_connp = connp->conn_next;
7455 		IP_STAT(ipst, ip_udp_fanmb);
7456 		CONN_DEC_REF(connp);
7457 		connp = next_connp;
7458 	}
7459 
7460 	/* Last one.  Send it upstream. */
7461 	mutex_exit(&connfp->connf_lock);
7462 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7463 	    recv_ill, ip_policy);
7464 	IP_STAT(ipst, ip_udp_fanmb);
7465 	CONN_DEC_REF(connp);
7466 	return;
7467 
7468 notfound:
7469 
7470 	mutex_exit(&connfp->connf_lock);
7471 	IP_STAT(ipst, ip_udp_fanothers);
7472 	/*
7473 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7474 	 * have already been matched above, since they live in the IPv4
7475 	 * fanout tables. This implies we only need to
7476 	 * check for IPv6 in6addr_any endpoints here.
7477 	 * Thus we compare using ipv6_all_zeros instead of the destination
7478 	 * address, except for the multicast group membership lookup which
7479 	 * uses the IPv4 destination.
7480 	 */
7481 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7482 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7483 	mutex_enter(&connfp->connf_lock);
7484 	connp = connfp->connf_head;
7485 	if (!broadcast && !CLASSD(dst)) {
7486 		while (connp != NULL) {
7487 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7488 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7489 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7490 			    !connp->conn_ipv6_v6only)
7491 				break;
7492 			connp = connp->conn_next;
7493 		}
7494 
7495 		if (connp != NULL && is_system_labeled() &&
7496 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7497 		    connp))
7498 			connp = NULL;
7499 
7500 		if (connp == NULL ||
7501 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7502 			/*
7503 			 * No one bound to this port.  Is
7504 			 * there a client that wants all
7505 			 * unclaimed datagrams?
7506 			 */
7507 			mutex_exit(&connfp->connf_lock);
7508 
7509 			if (mctl_present)
7510 				first_mp->b_cont = mp;
7511 			else
7512 				first_mp = mp;
7513 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7514 			    connf_head != NULL) {
7515 				ip_fanout_proto(q, first_mp, ill, ipha,
7516 				    flags | IP_FF_RAWIP, mctl_present,
7517 				    ip_policy, recv_ill, zoneid);
7518 			} else {
7519 				if (ip_fanout_send_icmp(q, first_mp, flags,
7520 				    ICMP_DEST_UNREACHABLE,
7521 				    ICMP_PORT_UNREACHABLE,
7522 				    mctl_present, zoneid, ipst)) {
7523 					BUMP_MIB(ill->ill_ip_mib,
7524 					    udpIfStatsNoPorts);
7525 				}
7526 			}
7527 			return;
7528 		}
7529 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7530 
7531 		CONN_INC_REF(connp);
7532 		mutex_exit(&connfp->connf_lock);
7533 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7534 		    flags, recv_ill, ip_policy);
7535 		CONN_DEC_REF(connp);
7536 		return;
7537 	}
7538 	/*
7539 	 * IPv4 multicast packet being delivered to an AF_INET6
7540 	 * in6addr_any endpoint.
7541 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7542 	 * and not conn_wantpacket_v6() since any multicast membership is
7543 	 * for an IPv4-mapped multicast address.
7544 	 * The packet is sent to all clients in all zones that have joined the
7545 	 * group and match the port.
7546 	 */
7547 	while (connp != NULL) {
7548 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7549 		    srcport, v6src) &&
7550 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7551 		    (!is_system_labeled() ||
7552 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7553 		    connp)))
7554 			break;
7555 		connp = connp->conn_next;
7556 	}
7557 
7558 	if (connp == NULL ||
7559 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7560 		/*
7561 		 * No one bound to this port.  Is
7562 		 * there a client that wants all
7563 		 * unclaimed datagrams?
7564 		 */
7565 		mutex_exit(&connfp->connf_lock);
7566 
7567 		if (mctl_present)
7568 			first_mp->b_cont = mp;
7569 		else
7570 			first_mp = mp;
7571 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7572 		    NULL) {
7573 			ip_fanout_proto(q, first_mp, ill, ipha,
7574 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7575 			    recv_ill, zoneid);
7576 		} else {
7577 			/*
7578 			 * We used to attempt to send an icmp error here, but
7579 			 * since this is known to be a multicast packet
7580 			 * and we don't send icmp errors in response to
7581 			 * multicast, just drop the packet and give up sooner.
7582 			 */
7583 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7584 			freemsg(first_mp);
7585 		}
7586 		return;
7587 	}
7588 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7589 
7590 	first_connp = connp;
7591 
7592 	CONN_INC_REF(connp);
7593 	connp = connp->conn_next;
7594 	for (;;) {
7595 		while (connp != NULL) {
7596 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7597 			    ipv6_all_zeros, srcport, v6src) &&
7598 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7599 			    (!is_system_labeled() ||
7600 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7601 			    shared_addr, connp)))
7602 				break;
7603 			connp = connp->conn_next;
7604 		}
7605 		/*
7606 		 * Just copy the data part alone. The mctl part is
7607 		 * needed just for verifying policy and it is never
7608 		 * sent up.
7609 		 */
7610 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7611 		    ((mp1 = copymsg(mp)) == NULL))) {
7612 			/*
7613 			 * No more intested clients or memory
7614 			 * allocation failed
7615 			 */
7616 			connp = first_connp;
7617 			break;
7618 		}
7619 		if (first_mp != NULL) {
7620 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7621 			    ipsec_info_type == IPSEC_IN);
7622 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7623 			    ipst->ips_netstack);
7624 			if (first_mp1 == NULL) {
7625 				freemsg(mp1);
7626 				connp = first_connp;
7627 				break;
7628 			}
7629 		} else {
7630 			first_mp1 = NULL;
7631 		}
7632 		CONN_INC_REF(connp);
7633 		mutex_exit(&connfp->connf_lock);
7634 		/*
7635 		 * IPQoS notes: We don't send the packet for policy
7636 		 * processing here, will do it for the last one (below).
7637 		 * i.e. we do it per-packet now, but if we do policy
7638 		 * processing per-conn, then we would need to do it
7639 		 * here too.
7640 		 */
7641 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7642 		    ipha, flags, recv_ill, B_FALSE);
7643 		mutex_enter(&connfp->connf_lock);
7644 		/* Follow the next pointer before releasing the conn. */
7645 		next_connp = connp->conn_next;
7646 		CONN_DEC_REF(connp);
7647 		connp = next_connp;
7648 	}
7649 
7650 	/* Last one.  Send it upstream. */
7651 	mutex_exit(&connfp->connf_lock);
7652 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7653 	    recv_ill, ip_policy);
7654 	CONN_DEC_REF(connp);
7655 }
7656 
7657 /*
7658  * Complete the ip_wput header so that it
7659  * is possible to generate ICMP
7660  * errors.
7661  */
7662 int
7663 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7664 {
7665 	ire_t *ire;
7666 
7667 	if (ipha->ipha_src == INADDR_ANY) {
7668 		ire = ire_lookup_local(zoneid, ipst);
7669 		if (ire == NULL) {
7670 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7671 			return (1);
7672 		}
7673 		ipha->ipha_src = ire->ire_addr;
7674 		ire_refrele(ire);
7675 	}
7676 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7677 	ipha->ipha_hdr_checksum = 0;
7678 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7679 	return (0);
7680 }
7681 
7682 /*
7683  * Nobody should be sending
7684  * packets up this stream
7685  */
7686 static void
7687 ip_lrput(queue_t *q, mblk_t *mp)
7688 {
7689 	mblk_t *mp1;
7690 
7691 	switch (mp->b_datap->db_type) {
7692 	case M_FLUSH:
7693 		/* Turn around */
7694 		if (*mp->b_rptr & FLUSHW) {
7695 			*mp->b_rptr &= ~FLUSHR;
7696 			qreply(q, mp);
7697 			return;
7698 		}
7699 		break;
7700 	}
7701 	/* Could receive messages that passed through ar_rput */
7702 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7703 		mp1->b_prev = mp1->b_next = NULL;
7704 	freemsg(mp);
7705 }
7706 
7707 /* Nobody should be sending packets down this stream */
7708 /* ARGSUSED */
7709 void
7710 ip_lwput(queue_t *q, mblk_t *mp)
7711 {
7712 	freemsg(mp);
7713 }
7714 
7715 /*
7716  * Move the first hop in any source route to ipha_dst and remove that part of
7717  * the source route.  Called by other protocols.  Errors in option formatting
7718  * are ignored - will be handled by ip_wput_options Return the final
7719  * destination (either ipha_dst or the last entry in a source route.)
7720  */
7721 ipaddr_t
7722 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7723 {
7724 	ipoptp_t	opts;
7725 	uchar_t		*opt;
7726 	uint8_t		optval;
7727 	uint8_t		optlen;
7728 	ipaddr_t	dst;
7729 	int		i;
7730 	ire_t		*ire;
7731 	ip_stack_t	*ipst = ns->netstack_ip;
7732 
7733 	ip2dbg(("ip_massage_options\n"));
7734 	dst = ipha->ipha_dst;
7735 	for (optval = ipoptp_first(&opts, ipha);
7736 	    optval != IPOPT_EOL;
7737 	    optval = ipoptp_next(&opts)) {
7738 		opt = opts.ipoptp_cur;
7739 		switch (optval) {
7740 			uint8_t off;
7741 		case IPOPT_SSRR:
7742 		case IPOPT_LSRR:
7743 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7744 				ip1dbg(("ip_massage_options: bad src route\n"));
7745 				break;
7746 			}
7747 			optlen = opts.ipoptp_len;
7748 			off = opt[IPOPT_OFFSET];
7749 			off--;
7750 		redo_srr:
7751 			if (optlen < IP_ADDR_LEN ||
7752 			    off > optlen - IP_ADDR_LEN) {
7753 				/* End of source route */
7754 				ip1dbg(("ip_massage_options: end of SR\n"));
7755 				break;
7756 			}
7757 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7758 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7759 			    ntohl(dst)));
7760 			/*
7761 			 * Check if our address is present more than
7762 			 * once as consecutive hops in source route.
7763 			 * XXX verify per-interface ip_forwarding
7764 			 * for source route?
7765 			 */
7766 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7767 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7768 			if (ire != NULL) {
7769 				ire_refrele(ire);
7770 				off += IP_ADDR_LEN;
7771 				goto redo_srr;
7772 			}
7773 			if (dst == htonl(INADDR_LOOPBACK)) {
7774 				ip1dbg(("ip_massage_options: loopback addr in "
7775 				    "source route!\n"));
7776 				break;
7777 			}
7778 			/*
7779 			 * Update ipha_dst to be the first hop and remove the
7780 			 * first hop from the source route (by overwriting
7781 			 * part of the option with NOP options).
7782 			 */
7783 			ipha->ipha_dst = dst;
7784 			/* Put the last entry in dst */
7785 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7786 			    3;
7787 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7788 
7789 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7790 			    ntohl(dst)));
7791 			/* Move down and overwrite */
7792 			opt[IP_ADDR_LEN] = opt[0];
7793 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7794 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7795 			for (i = 0; i < IP_ADDR_LEN; i++)
7796 				opt[i] = IPOPT_NOP;
7797 			break;
7798 		}
7799 	}
7800 	return (dst);
7801 }
7802 
7803 /*
7804  * Return the network mask
7805  * associated with the specified address.
7806  */
7807 ipaddr_t
7808 ip_net_mask(ipaddr_t addr)
7809 {
7810 	uchar_t	*up = (uchar_t *)&addr;
7811 	ipaddr_t mask = 0;
7812 	uchar_t	*maskp = (uchar_t *)&mask;
7813 
7814 #if defined(__i386) || defined(__amd64)
7815 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7816 #endif
7817 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7818 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7819 #endif
7820 	if (CLASSD(addr)) {
7821 		maskp[0] = 0xF0;
7822 		return (mask);
7823 	}
7824 
7825 	/* We assume Class E default netmask to be 32 */
7826 	if (CLASSE(addr))
7827 		return (0xffffffffU);
7828 
7829 	if (addr == 0)
7830 		return (0);
7831 	maskp[0] = 0xFF;
7832 	if ((up[0] & 0x80) == 0)
7833 		return (mask);
7834 
7835 	maskp[1] = 0xFF;
7836 	if ((up[0] & 0xC0) == 0x80)
7837 		return (mask);
7838 
7839 	maskp[2] = 0xFF;
7840 	if ((up[0] & 0xE0) == 0xC0)
7841 		return (mask);
7842 
7843 	/* Otherwise return no mask */
7844 	return ((ipaddr_t)0);
7845 }
7846 
7847 /*
7848  * Helper ill lookup function used by IPsec.
7849  */
7850 ill_t *
7851 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7852 {
7853 	ill_t *ret_ill;
7854 
7855 	ASSERT(ifindex != 0);
7856 
7857 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7858 	    ipst);
7859 	if (ret_ill == NULL) {
7860 		if (isv6) {
7861 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7862 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7863 			    ifindex));
7864 		} else {
7865 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7866 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7867 			    ifindex));
7868 		}
7869 		freemsg(first_mp);
7870 		return (NULL);
7871 	}
7872 	return (ret_ill);
7873 }
7874 
7875 /*
7876  * IPv4 -
7877  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7878  * out a packet to a destination address for which we do not have specific
7879  * (or sufficient) routing information.
7880  *
7881  * NOTE : These are the scopes of some of the variables that point at IRE,
7882  *	  which needs to be followed while making any future modifications
7883  *	  to avoid memory leaks.
7884  *
7885  *	- ire and sire are the entries looked up initially by
7886  *	  ire_ftable_lookup.
7887  *	- ipif_ire is used to hold the interface ire associated with
7888  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7889  *	  it before branching out to error paths.
7890  *	- save_ire is initialized before ire_create, so that ire returned
7891  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7892  *	  before breaking out of the switch.
7893  *
7894  *	Thus on failures, we have to REFRELE only ire and sire, if they
7895  *	are not NULL.
7896  */
7897 void
7898 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7899     zoneid_t zoneid, ip_stack_t *ipst)
7900 {
7901 	areq_t	*areq;
7902 	ipaddr_t gw = 0;
7903 	ire_t	*ire = NULL;
7904 	mblk_t	*res_mp;
7905 	ipaddr_t *addrp;
7906 	ipaddr_t nexthop_addr;
7907 	ipif_t  *src_ipif = NULL;
7908 	ill_t	*dst_ill = NULL;
7909 	ipha_t  *ipha;
7910 	ire_t	*sire = NULL;
7911 	mblk_t	*first_mp;
7912 	ire_t	*save_ire;
7913 	ushort_t ire_marks = 0;
7914 	boolean_t mctl_present;
7915 	ipsec_out_t *io;
7916 	mblk_t	*saved_mp;
7917 	ire_t	*first_sire = NULL;
7918 	mblk_t	*copy_mp = NULL;
7919 	mblk_t	*xmit_mp = NULL;
7920 	ipaddr_t save_dst;
7921 	uint32_t multirt_flags =
7922 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7923 	boolean_t multirt_is_resolvable;
7924 	boolean_t multirt_resolve_next;
7925 	boolean_t unspec_src;
7926 	boolean_t ip_nexthop = B_FALSE;
7927 	tsol_ire_gw_secattr_t *attrp = NULL;
7928 	tsol_gcgrp_t *gcgrp = NULL;
7929 	tsol_gcgrp_addr_t ga;
7930 
7931 	if (ip_debug > 2) {
7932 		/* ip1dbg */
7933 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7934 	}
7935 
7936 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7937 	if (mctl_present) {
7938 		io = (ipsec_out_t *)first_mp->b_rptr;
7939 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7940 		ASSERT(zoneid == io->ipsec_out_zoneid);
7941 		ASSERT(zoneid != ALL_ZONES);
7942 	}
7943 
7944 	ipha = (ipha_t *)mp->b_rptr;
7945 
7946 	/* All multicast lookups come through ip_newroute_ipif() */
7947 	if (CLASSD(dst)) {
7948 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7949 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7950 		freemsg(first_mp);
7951 		return;
7952 	}
7953 
7954 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7955 		ip_nexthop = B_TRUE;
7956 		nexthop_addr = io->ipsec_out_nexthop_addr;
7957 	}
7958 	/*
7959 	 * If this IRE is created for forwarding or it is not for
7960 	 * traffic for congestion controlled protocols, mark it as temporary.
7961 	 */
7962 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7963 		ire_marks |= IRE_MARK_TEMPORARY;
7964 
7965 	/*
7966 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7967 	 * chain until it gets the most specific information available.
7968 	 * For example, we know that there is no IRE_CACHE for this dest,
7969 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7970 	 * ire_ftable_lookup will look up the gateway, etc.
7971 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7972 	 * to the destination, of equal netmask length in the forward table,
7973 	 * will be recursively explored. If no information is available
7974 	 * for the final gateway of that route, we force the returned ire
7975 	 * to be equal to sire using MATCH_IRE_PARENT.
7976 	 * At least, in this case we have a starting point (in the buckets)
7977 	 * to look for other routes to the destination in the forward table.
7978 	 * This is actually used only for multirouting, where a list
7979 	 * of routes has to be processed in sequence.
7980 	 *
7981 	 * In the process of coming up with the most specific information,
7982 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7983 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7984 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7985 	 * Two caveats when handling incomplete ire's in ip_newroute:
7986 	 * - we should be careful when accessing its ire_nce (specifically
7987 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7988 	 * - not all legacy code path callers are prepared to handle
7989 	 *   incomplete ire's, so we should not create/add incomplete
7990 	 *   ire_cache entries here. (See discussion about temporary solution
7991 	 *   further below).
7992 	 *
7993 	 * In order to minimize packet dropping, and to preserve existing
7994 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7995 	 * gateway, and instead use the IF_RESOLVER ire to send out
7996 	 * another request to ARP (this is achieved by passing the
7997 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7998 	 * arp response comes back in ip_wput_nondata, we will create
7999 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8000 	 *
8001 	 * Note that this is a temporary solution; the correct solution is
8002 	 * to create an incomplete  per-dst ire_cache entry, and send the
8003 	 * packet out when the gw's nce is resolved. In order to achieve this,
8004 	 * all packet processing must have been completed prior to calling
8005 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8006 	 * to be modified to accomodate this solution.
8007 	 */
8008 	if (ip_nexthop) {
8009 		/*
8010 		 * The first time we come here, we look for an IRE_INTERFACE
8011 		 * entry for the specified nexthop, set the dst to be the
8012 		 * nexthop address and create an IRE_CACHE entry for the
8013 		 * nexthop. The next time around, we are able to find an
8014 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8015 		 * nexthop address and create an IRE_CACHE entry for the
8016 		 * destination address via the specified nexthop.
8017 		 */
8018 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8019 		    msg_getlabel(mp), ipst);
8020 		if (ire != NULL) {
8021 			gw = nexthop_addr;
8022 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8023 		} else {
8024 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8025 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8026 			    msg_getlabel(mp),
8027 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8028 			    ipst);
8029 			if (ire != NULL) {
8030 				dst = nexthop_addr;
8031 			}
8032 		}
8033 	} else {
8034 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8035 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
8036 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8037 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8038 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8039 		    ipst);
8040 	}
8041 
8042 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8043 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8044 
8045 	/*
8046 	 * This loop is run only once in most cases.
8047 	 * We loop to resolve further routes only when the destination
8048 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8049 	 */
8050 	do {
8051 		/* Clear the previous iteration's values */
8052 		if (src_ipif != NULL) {
8053 			ipif_refrele(src_ipif);
8054 			src_ipif = NULL;
8055 		}
8056 		if (dst_ill != NULL) {
8057 			ill_refrele(dst_ill);
8058 			dst_ill = NULL;
8059 		}
8060 
8061 		multirt_resolve_next = B_FALSE;
8062 		/*
8063 		 * We check if packets have to be multirouted.
8064 		 * In this case, given the current <ire, sire> couple,
8065 		 * we look for the next suitable <ire, sire>.
8066 		 * This check is done in ire_multirt_lookup(),
8067 		 * which applies various criteria to find the next route
8068 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8069 		 * unchanged if it detects it has not been tried yet.
8070 		 */
8071 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8072 			ip3dbg(("ip_newroute: starting next_resolution "
8073 			    "with first_mp %p, tag %d\n",
8074 			    (void *)first_mp,
8075 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8076 
8077 			ASSERT(sire != NULL);
8078 			multirt_is_resolvable =
8079 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8080 			    msg_getlabel(mp), ipst);
8081 
8082 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8083 			    "ire %p, sire %p\n",
8084 			    multirt_is_resolvable,
8085 			    (void *)ire, (void *)sire));
8086 
8087 			if (!multirt_is_resolvable) {
8088 				/*
8089 				 * No more multirt route to resolve; give up
8090 				 * (all routes resolved or no more
8091 				 * resolvable routes).
8092 				 */
8093 				if (ire != NULL) {
8094 					ire_refrele(ire);
8095 					ire = NULL;
8096 				}
8097 			} else {
8098 				ASSERT(sire != NULL);
8099 				ASSERT(ire != NULL);
8100 				/*
8101 				 * We simply use first_sire as a flag that
8102 				 * indicates if a resolvable multirt route
8103 				 * has already been found.
8104 				 * If it is not the case, we may have to send
8105 				 * an ICMP error to report that the
8106 				 * destination is unreachable.
8107 				 * We do not IRE_REFHOLD first_sire.
8108 				 */
8109 				if (first_sire == NULL) {
8110 					first_sire = sire;
8111 				}
8112 			}
8113 		}
8114 		if (ire == NULL) {
8115 			if (ip_debug > 3) {
8116 				/* ip2dbg */
8117 				pr_addr_dbg("ip_newroute: "
8118 				    "can't resolve %s\n", AF_INET, &dst);
8119 			}
8120 			ip3dbg(("ip_newroute: "
8121 			    "ire %p, sire %p, first_sire %p\n",
8122 			    (void *)ire, (void *)sire, (void *)first_sire));
8123 
8124 			if (sire != NULL) {
8125 				ire_refrele(sire);
8126 				sire = NULL;
8127 			}
8128 
8129 			if (first_sire != NULL) {
8130 				/*
8131 				 * At least one multirt route has been found
8132 				 * in the same call to ip_newroute();
8133 				 * there is no need to report an ICMP error.
8134 				 * first_sire was not IRE_REFHOLDed.
8135 				 */
8136 				MULTIRT_DEBUG_UNTAG(first_mp);
8137 				freemsg(first_mp);
8138 				return;
8139 			}
8140 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8141 			    RTA_DST, ipst);
8142 			goto icmp_err_ret;
8143 		}
8144 
8145 		/*
8146 		 * Verify that the returned IRE does not have either
8147 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8148 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8149 		 */
8150 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8151 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8152 			goto icmp_err_ret;
8153 		}
8154 		/*
8155 		 * Increment the ire_ob_pkt_count field for ire if it is an
8156 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8157 		 * increment the same for the parent IRE, sire, if it is some
8158 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8159 		 */
8160 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8161 			UPDATE_OB_PKT_COUNT(ire);
8162 			ire->ire_last_used_time = lbolt;
8163 		}
8164 
8165 		if (sire != NULL) {
8166 			gw = sire->ire_gateway_addr;
8167 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8168 			    IRE_INTERFACE)) == 0);
8169 			UPDATE_OB_PKT_COUNT(sire);
8170 			sire->ire_last_used_time = lbolt;
8171 		}
8172 		/*
8173 		 * We have a route to reach the destination.  Find the
8174 		 * appropriate ill, then get a source address using
8175 		 * ipif_select_source().
8176 		 *
8177 		 * If we are here trying to create an IRE_CACHE for an offlink
8178 		 * destination and have an IRE_CACHE entry for VNI, then use
8179 		 * ire_stq instead since VNI's queue is a black hole.
8180 		 */
8181 		if ((ire->ire_type == IRE_CACHE) &&
8182 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8183 			dst_ill = ire->ire_stq->q_ptr;
8184 			ill_refhold(dst_ill);
8185 		} else {
8186 			ill_t *ill = ire->ire_ipif->ipif_ill;
8187 
8188 			if (IS_IPMP(ill)) {
8189 				dst_ill =
8190 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8191 			} else {
8192 				dst_ill = ill;
8193 				ill_refhold(dst_ill);
8194 			}
8195 		}
8196 
8197 		if (dst_ill == NULL) {
8198 			if (ip_debug > 2) {
8199 				pr_addr_dbg("ip_newroute: no dst "
8200 				    "ill for dst %s\n", AF_INET, &dst);
8201 			}
8202 			goto icmp_err_ret;
8203 		}
8204 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8205 
8206 		/*
8207 		 * Pick the best source address from dst_ill.
8208 		 *
8209 		 * 1) Try to pick the source address from the destination
8210 		 *    route. Clustering assumes that when we have multiple
8211 		 *    prefixes hosted on an interface, the prefix of the
8212 		 *    source address matches the prefix of the destination
8213 		 *    route. We do this only if the address is not
8214 		 *    DEPRECATED.
8215 		 *
8216 		 * 2) If the conn is in a different zone than the ire, we
8217 		 *    need to pick a source address from the right zone.
8218 		 */
8219 		ASSERT(src_ipif == NULL);
8220 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8221 			/*
8222 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8223 			 * Check that the ipif matching the requested source
8224 			 * address still exists.
8225 			 */
8226 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8227 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8228 		}
8229 
8230 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8231 
8232 		if (src_ipif == NULL &&
8233 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8234 			ire_marks |= IRE_MARK_USESRC_CHECK;
8235 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8236 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8237 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8238 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8239 			    ire->ire_zoneid != ALL_ZONES) ||
8240 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8241 				/*
8242 				 * If the destination is reachable via a
8243 				 * given gateway, the selected source address
8244 				 * should be in the same subnet as the gateway.
8245 				 * Otherwise, the destination is not reachable.
8246 				 *
8247 				 * If there are no interfaces on the same subnet
8248 				 * as the destination, ipif_select_source gives
8249 				 * first non-deprecated interface which might be
8250 				 * on a different subnet than the gateway.
8251 				 * This is not desirable. Hence pass the dst_ire
8252 				 * source address to ipif_select_source.
8253 				 * It is sure that the destination is reachable
8254 				 * with the dst_ire source address subnet.
8255 				 * So passing dst_ire source address to
8256 				 * ipif_select_source will make sure that the
8257 				 * selected source will be on the same subnet
8258 				 * as dst_ire source address.
8259 				 */
8260 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8261 
8262 				src_ipif = ipif_select_source(dst_ill, saddr,
8263 				    zoneid);
8264 				if (src_ipif == NULL) {
8265 					if (ip_debug > 2) {
8266 						pr_addr_dbg("ip_newroute: "
8267 						    "no src for dst %s ",
8268 						    AF_INET, &dst);
8269 						printf("on interface %s\n",
8270 						    dst_ill->ill_name);
8271 					}
8272 					goto icmp_err_ret;
8273 				}
8274 			} else {
8275 				src_ipif = ire->ire_ipif;
8276 				ASSERT(src_ipif != NULL);
8277 				/* hold src_ipif for uniformity */
8278 				ipif_refhold(src_ipif);
8279 			}
8280 		}
8281 
8282 		/*
8283 		 * Assign a source address while we have the conn.
8284 		 * We can't have ip_wput_ire pick a source address when the
8285 		 * packet returns from arp since we need to look at
8286 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8287 		 * going through arp.
8288 		 *
8289 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8290 		 *	  it uses ip6i to store this information.
8291 		 */
8292 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8293 			ipha->ipha_src = src_ipif->ipif_src_addr;
8294 
8295 		if (ip_debug > 3) {
8296 			/* ip2dbg */
8297 			pr_addr_dbg("ip_newroute: first hop %s\n",
8298 			    AF_INET, &gw);
8299 		}
8300 		ip2dbg(("\tire type %s (%d)\n",
8301 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8302 
8303 		/*
8304 		 * The TTL of multirouted packets is bounded by the
8305 		 * ip_multirt_ttl ndd variable.
8306 		 */
8307 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8308 			/* Force TTL of multirouted packets */
8309 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8310 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8311 				ip2dbg(("ip_newroute: forcing multirt TTL "
8312 				    "to %d (was %d), dst 0x%08x\n",
8313 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8314 				    ntohl(sire->ire_addr)));
8315 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8316 			}
8317 		}
8318 		/*
8319 		 * At this point in ip_newroute(), ire is either the
8320 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8321 		 * destination or an IRE_INTERFACE type that should be used
8322 		 * to resolve an on-subnet destination or an on-subnet
8323 		 * next-hop gateway.
8324 		 *
8325 		 * In the IRE_CACHE case, we have the following :
8326 		 *
8327 		 * 1) src_ipif - used for getting a source address.
8328 		 *
8329 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8330 		 *    means packets using this IRE_CACHE will go out on
8331 		 *    dst_ill.
8332 		 *
8333 		 * 3) The IRE sire will point to the prefix that is the
8334 		 *    longest  matching route for the destination. These
8335 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8336 		 *
8337 		 *    The newly created IRE_CACHE entry for the off-subnet
8338 		 *    destination is tied to both the prefix route and the
8339 		 *    interface route used to resolve the next-hop gateway
8340 		 *    via the ire_phandle and ire_ihandle fields,
8341 		 *    respectively.
8342 		 *
8343 		 * In the IRE_INTERFACE case, we have the following :
8344 		 *
8345 		 * 1) src_ipif - used for getting a source address.
8346 		 *
8347 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8348 		 *    means packets using the IRE_CACHE that we will build
8349 		 *    here will go out on dst_ill.
8350 		 *
8351 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8352 		 *    to be created will only be tied to the IRE_INTERFACE
8353 		 *    that was derived from the ire_ihandle field.
8354 		 *
8355 		 *    If sire is non-NULL, it means the destination is
8356 		 *    off-link and we will first create the IRE_CACHE for the
8357 		 *    gateway. Next time through ip_newroute, we will create
8358 		 *    the IRE_CACHE for the final destination as described
8359 		 *    above.
8360 		 *
8361 		 * In both cases, after the current resolution has been
8362 		 * completed (or possibly initialised, in the IRE_INTERFACE
8363 		 * case), the loop may be re-entered to attempt the resolution
8364 		 * of another RTF_MULTIRT route.
8365 		 *
8366 		 * When an IRE_CACHE entry for the off-subnet destination is
8367 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8368 		 * for further processing in emission loops.
8369 		 */
8370 		save_ire = ire;
8371 		switch (ire->ire_type) {
8372 		case IRE_CACHE: {
8373 			ire_t	*ipif_ire;
8374 
8375 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8376 			if (gw == 0)
8377 				gw = ire->ire_gateway_addr;
8378 			/*
8379 			 * We need 3 ire's to create a new cache ire for an
8380 			 * off-link destination from the cache ire of the
8381 			 * gateway.
8382 			 *
8383 			 *	1. The prefix ire 'sire' (Note that this does
8384 			 *	   not apply to the conn_nexthop_set case)
8385 			 *	2. The cache ire of the gateway 'ire'
8386 			 *	3. The interface ire 'ipif_ire'
8387 			 *
8388 			 * We have (1) and (2). We lookup (3) below.
8389 			 *
8390 			 * If there is no interface route to the gateway,
8391 			 * it is a race condition, where we found the cache
8392 			 * but the interface route has been deleted.
8393 			 */
8394 			if (ip_nexthop) {
8395 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8396 			} else {
8397 				ipif_ire =
8398 				    ire_ihandle_lookup_offlink(ire, sire);
8399 			}
8400 			if (ipif_ire == NULL) {
8401 				ip1dbg(("ip_newroute: "
8402 				    "ire_ihandle_lookup_offlink failed\n"));
8403 				goto icmp_err_ret;
8404 			}
8405 
8406 			/*
8407 			 * Check cached gateway IRE for any security
8408 			 * attributes; if found, associate the gateway
8409 			 * credentials group to the destination IRE.
8410 			 */
8411 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8412 				mutex_enter(&attrp->igsa_lock);
8413 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8414 					GCGRP_REFHOLD(gcgrp);
8415 				mutex_exit(&attrp->igsa_lock);
8416 			}
8417 
8418 			/*
8419 			 * XXX For the source of the resolver mp,
8420 			 * we are using the same DL_UNITDATA_REQ
8421 			 * (from save_ire->ire_nce->nce_res_mp)
8422 			 * though the save_ire is not pointing at the same ill.
8423 			 * This is incorrect. We need to send it up to the
8424 			 * resolver to get the right res_mp. For ethernets
8425 			 * this may be okay (ill_type == DL_ETHER).
8426 			 */
8427 
8428 			ire = ire_create(
8429 			    (uchar_t *)&dst,		/* dest address */
8430 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8431 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8432 			    (uchar_t *)&gw,		/* gateway address */
8433 			    &save_ire->ire_max_frag,
8434 			    save_ire->ire_nce,		/* src nce */
8435 			    dst_ill->ill_rq,		/* recv-from queue */
8436 			    dst_ill->ill_wq,		/* send-to queue */
8437 			    IRE_CACHE,			/* IRE type */
8438 			    src_ipif,
8439 			    (sire != NULL) ?
8440 			    sire->ire_mask : 0, 	/* Parent mask */
8441 			    (sire != NULL) ?
8442 			    sire->ire_phandle : 0,	/* Parent handle */
8443 			    ipif_ire->ire_ihandle,	/* Interface handle */
8444 			    (sire != NULL) ? (sire->ire_flags &
8445 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8446 			    (sire != NULL) ?
8447 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8448 			    NULL,
8449 			    gcgrp,
8450 			    ipst);
8451 
8452 			if (ire == NULL) {
8453 				if (gcgrp != NULL) {
8454 					GCGRP_REFRELE(gcgrp);
8455 					gcgrp = NULL;
8456 				}
8457 				ire_refrele(ipif_ire);
8458 				ire_refrele(save_ire);
8459 				break;
8460 			}
8461 
8462 			/* reference now held by IRE */
8463 			gcgrp = NULL;
8464 
8465 			ire->ire_marks |= ire_marks;
8466 
8467 			/*
8468 			 * Prevent sire and ipif_ire from getting deleted.
8469 			 * The newly created ire is tied to both of them via
8470 			 * the phandle and ihandle respectively.
8471 			 */
8472 			if (sire != NULL) {
8473 				IRB_REFHOLD(sire->ire_bucket);
8474 				/* Has it been removed already ? */
8475 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8476 					IRB_REFRELE(sire->ire_bucket);
8477 					ire_refrele(ipif_ire);
8478 					ire_refrele(save_ire);
8479 					break;
8480 				}
8481 			}
8482 
8483 			IRB_REFHOLD(ipif_ire->ire_bucket);
8484 			/* Has it been removed already ? */
8485 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8486 				IRB_REFRELE(ipif_ire->ire_bucket);
8487 				if (sire != NULL)
8488 					IRB_REFRELE(sire->ire_bucket);
8489 				ire_refrele(ipif_ire);
8490 				ire_refrele(save_ire);
8491 				break;
8492 			}
8493 
8494 			xmit_mp = first_mp;
8495 			/*
8496 			 * In the case of multirouting, a copy
8497 			 * of the packet is done before its sending.
8498 			 * The copy is used to attempt another
8499 			 * route resolution, in a next loop.
8500 			 */
8501 			if (ire->ire_flags & RTF_MULTIRT) {
8502 				copy_mp = copymsg(first_mp);
8503 				if (copy_mp != NULL) {
8504 					xmit_mp = copy_mp;
8505 					MULTIRT_DEBUG_TAG(first_mp);
8506 				}
8507 			}
8508 
8509 			ire_add_then_send(q, ire, xmit_mp);
8510 			ire_refrele(save_ire);
8511 
8512 			/* Assert that sire is not deleted yet. */
8513 			if (sire != NULL) {
8514 				ASSERT(sire->ire_ptpn != NULL);
8515 				IRB_REFRELE(sire->ire_bucket);
8516 			}
8517 
8518 			/* Assert that ipif_ire is not deleted yet. */
8519 			ASSERT(ipif_ire->ire_ptpn != NULL);
8520 			IRB_REFRELE(ipif_ire->ire_bucket);
8521 			ire_refrele(ipif_ire);
8522 
8523 			/*
8524 			 * If copy_mp is not NULL, multirouting was
8525 			 * requested. We loop to initiate a next
8526 			 * route resolution attempt, starting from sire.
8527 			 */
8528 			if (copy_mp != NULL) {
8529 				/*
8530 				 * Search for the next unresolved
8531 				 * multirt route.
8532 				 */
8533 				copy_mp = NULL;
8534 				ipif_ire = NULL;
8535 				ire = NULL;
8536 				multirt_resolve_next = B_TRUE;
8537 				continue;
8538 			}
8539 			if (sire != NULL)
8540 				ire_refrele(sire);
8541 			ipif_refrele(src_ipif);
8542 			ill_refrele(dst_ill);
8543 			return;
8544 		}
8545 		case IRE_IF_NORESOLVER: {
8546 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8547 			    dst_ill->ill_resolver_mp == NULL) {
8548 				ip1dbg(("ip_newroute: dst_ill %p "
8549 				    "for IRE_IF_NORESOLVER ire %p has "
8550 				    "no ill_resolver_mp\n",
8551 				    (void *)dst_ill, (void *)ire));
8552 				break;
8553 			}
8554 
8555 			/*
8556 			 * TSol note: We are creating the ire cache for the
8557 			 * destination 'dst'. If 'dst' is offlink, going
8558 			 * through the first hop 'gw', the security attributes
8559 			 * of 'dst' must be set to point to the gateway
8560 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8561 			 * is possible that 'dst' is a potential gateway that is
8562 			 * referenced by some route that has some security
8563 			 * attributes. Thus in the former case, we need to do a
8564 			 * gcgrp_lookup of 'gw' while in the latter case we
8565 			 * need to do gcgrp_lookup of 'dst' itself.
8566 			 */
8567 			ga.ga_af = AF_INET;
8568 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8569 			    &ga.ga_addr);
8570 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8571 
8572 			ire = ire_create(
8573 			    (uchar_t *)&dst,		/* dest address */
8574 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8575 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8576 			    (uchar_t *)&gw,		/* gateway address */
8577 			    &save_ire->ire_max_frag,
8578 			    NULL,			/* no src nce */
8579 			    dst_ill->ill_rq,		/* recv-from queue */
8580 			    dst_ill->ill_wq,		/* send-to queue */
8581 			    IRE_CACHE,
8582 			    src_ipif,
8583 			    save_ire->ire_mask,		/* Parent mask */
8584 			    (sire != NULL) ?		/* Parent handle */
8585 			    sire->ire_phandle : 0,
8586 			    save_ire->ire_ihandle,	/* Interface handle */
8587 			    (sire != NULL) ? sire->ire_flags &
8588 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8589 			    &(save_ire->ire_uinfo),
8590 			    NULL,
8591 			    gcgrp,
8592 			    ipst);
8593 
8594 			if (ire == NULL) {
8595 				if (gcgrp != NULL) {
8596 					GCGRP_REFRELE(gcgrp);
8597 					gcgrp = NULL;
8598 				}
8599 				ire_refrele(save_ire);
8600 				break;
8601 			}
8602 
8603 			/* reference now held by IRE */
8604 			gcgrp = NULL;
8605 
8606 			ire->ire_marks |= ire_marks;
8607 
8608 			/* Prevent save_ire from getting deleted */
8609 			IRB_REFHOLD(save_ire->ire_bucket);
8610 			/* Has it been removed already ? */
8611 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8612 				IRB_REFRELE(save_ire->ire_bucket);
8613 				ire_refrele(save_ire);
8614 				break;
8615 			}
8616 
8617 			/*
8618 			 * In the case of multirouting, a copy
8619 			 * of the packet is made before it is sent.
8620 			 * The copy is used in the next
8621 			 * loop to attempt another resolution.
8622 			 */
8623 			xmit_mp = first_mp;
8624 			if ((sire != NULL) &&
8625 			    (sire->ire_flags & RTF_MULTIRT)) {
8626 				copy_mp = copymsg(first_mp);
8627 				if (copy_mp != NULL) {
8628 					xmit_mp = copy_mp;
8629 					MULTIRT_DEBUG_TAG(first_mp);
8630 				}
8631 			}
8632 			ire_add_then_send(q, ire, xmit_mp);
8633 
8634 			/* Assert that it is not deleted yet. */
8635 			ASSERT(save_ire->ire_ptpn != NULL);
8636 			IRB_REFRELE(save_ire->ire_bucket);
8637 			ire_refrele(save_ire);
8638 
8639 			if (copy_mp != NULL) {
8640 				/*
8641 				 * If we found a (no)resolver, we ignore any
8642 				 * trailing top priority IRE_CACHE in further
8643 				 * loops. This ensures that we do not omit any
8644 				 * (no)resolver.
8645 				 * This IRE_CACHE, if any, will be processed
8646 				 * by another thread entering ip_newroute().
8647 				 * IRE_CACHE entries, if any, will be processed
8648 				 * by another thread entering ip_newroute(),
8649 				 * (upon resolver response, for instance).
8650 				 * This aims to force parallel multirt
8651 				 * resolutions as soon as a packet must be sent.
8652 				 * In the best case, after the tx of only one
8653 				 * packet, all reachable routes are resolved.
8654 				 * Otherwise, the resolution of all RTF_MULTIRT
8655 				 * routes would require several emissions.
8656 				 */
8657 				multirt_flags &= ~MULTIRT_CACHEGW;
8658 
8659 				/*
8660 				 * Search for the next unresolved multirt
8661 				 * route.
8662 				 */
8663 				copy_mp = NULL;
8664 				save_ire = NULL;
8665 				ire = NULL;
8666 				multirt_resolve_next = B_TRUE;
8667 				continue;
8668 			}
8669 
8670 			/*
8671 			 * Don't need sire anymore
8672 			 */
8673 			if (sire != NULL)
8674 				ire_refrele(sire);
8675 
8676 			ipif_refrele(src_ipif);
8677 			ill_refrele(dst_ill);
8678 			return;
8679 		}
8680 		case IRE_IF_RESOLVER:
8681 			/*
8682 			 * We can't build an IRE_CACHE yet, but at least we
8683 			 * found a resolver that can help.
8684 			 */
8685 			res_mp = dst_ill->ill_resolver_mp;
8686 			if (!OK_RESOLVER_MP(res_mp))
8687 				break;
8688 
8689 			/*
8690 			 * To be at this point in the code with a non-zero gw
8691 			 * means that dst is reachable through a gateway that
8692 			 * we have never resolved.  By changing dst to the gw
8693 			 * addr we resolve the gateway first.
8694 			 * When ire_add_then_send() tries to put the IP dg
8695 			 * to dst, it will reenter ip_newroute() at which
8696 			 * time we will find the IRE_CACHE for the gw and
8697 			 * create another IRE_CACHE in case IRE_CACHE above.
8698 			 */
8699 			if (gw != INADDR_ANY) {
8700 				/*
8701 				 * The source ipif that was determined above was
8702 				 * relative to the destination address, not the
8703 				 * gateway's. If src_ipif was not taken out of
8704 				 * the IRE_IF_RESOLVER entry, we'll need to call
8705 				 * ipif_select_source() again.
8706 				 */
8707 				if (src_ipif != ire->ire_ipif) {
8708 					ipif_refrele(src_ipif);
8709 					src_ipif = ipif_select_source(dst_ill,
8710 					    gw, zoneid);
8711 					if (src_ipif == NULL) {
8712 						if (ip_debug > 2) {
8713 							pr_addr_dbg(
8714 							    "ip_newroute: no "
8715 							    "src for gw %s ",
8716 							    AF_INET, &gw);
8717 							printf("on "
8718 							    "interface %s\n",
8719 							    dst_ill->ill_name);
8720 						}
8721 						goto icmp_err_ret;
8722 					}
8723 				}
8724 				save_dst = dst;
8725 				dst = gw;
8726 				gw = INADDR_ANY;
8727 			}
8728 
8729 			/*
8730 			 * We obtain a partial IRE_CACHE which we will pass
8731 			 * along with the resolver query.  When the response
8732 			 * comes back it will be there ready for us to add.
8733 			 * The ire_max_frag is atomically set under the
8734 			 * irebucket lock in ire_add_v[46].
8735 			 */
8736 
8737 			ire = ire_create_mp(
8738 			    (uchar_t *)&dst,		/* dest address */
8739 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8740 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8741 			    (uchar_t *)&gw,		/* gateway address */
8742 			    NULL,			/* ire_max_frag */
8743 			    NULL,			/* no src nce */
8744 			    dst_ill->ill_rq,		/* recv-from queue */
8745 			    dst_ill->ill_wq,		/* send-to queue */
8746 			    IRE_CACHE,
8747 			    src_ipif,			/* Interface ipif */
8748 			    save_ire->ire_mask,		/* Parent mask */
8749 			    0,
8750 			    save_ire->ire_ihandle,	/* Interface handle */
8751 			    0,				/* flags if any */
8752 			    &(save_ire->ire_uinfo),
8753 			    NULL,
8754 			    NULL,
8755 			    ipst);
8756 
8757 			if (ire == NULL) {
8758 				ire_refrele(save_ire);
8759 				break;
8760 			}
8761 
8762 			if ((sire != NULL) &&
8763 			    (sire->ire_flags & RTF_MULTIRT)) {
8764 				copy_mp = copymsg(first_mp);
8765 				if (copy_mp != NULL)
8766 					MULTIRT_DEBUG_TAG(copy_mp);
8767 			}
8768 
8769 			ire->ire_marks |= ire_marks;
8770 
8771 			/*
8772 			 * Construct message chain for the resolver
8773 			 * of the form:
8774 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8775 			 * Packet could contain a IPSEC_OUT mp.
8776 			 *
8777 			 * NOTE : ire will be added later when the response
8778 			 * comes back from ARP. If the response does not
8779 			 * come back, ARP frees the packet. For this reason,
8780 			 * we can't REFHOLD the bucket of save_ire to prevent
8781 			 * deletions. We may not be able to REFRELE the bucket
8782 			 * if the response never comes back. Thus, before
8783 			 * adding the ire, ire_add_v4 will make sure that the
8784 			 * interface route does not get deleted. This is the
8785 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8786 			 * where we can always prevent deletions because of
8787 			 * the synchronous nature of adding IRES i.e
8788 			 * ire_add_then_send is called after creating the IRE.
8789 			 */
8790 			ASSERT(ire->ire_mp != NULL);
8791 			ire->ire_mp->b_cont = first_mp;
8792 			/* Have saved_mp handy, for cleanup if canput fails */
8793 			saved_mp = mp;
8794 			mp = copyb(res_mp);
8795 			if (mp == NULL) {
8796 				/* Prepare for cleanup */
8797 				mp = saved_mp; /* pkt */
8798 				ire_delete(ire); /* ire_mp */
8799 				ire = NULL;
8800 				ire_refrele(save_ire);
8801 				if (copy_mp != NULL) {
8802 					MULTIRT_DEBUG_UNTAG(copy_mp);
8803 					freemsg(copy_mp);
8804 					copy_mp = NULL;
8805 				}
8806 				break;
8807 			}
8808 			linkb(mp, ire->ire_mp);
8809 
8810 			/*
8811 			 * Fill in the source and dest addrs for the resolver.
8812 			 * NOTE: this depends on memory layouts imposed by
8813 			 * ill_init().
8814 			 */
8815 			areq = (areq_t *)mp->b_rptr;
8816 			addrp = (ipaddr_t *)((char *)areq +
8817 			    areq->areq_sender_addr_offset);
8818 			*addrp = save_ire->ire_src_addr;
8819 
8820 			ire_refrele(save_ire);
8821 			addrp = (ipaddr_t *)((char *)areq +
8822 			    areq->areq_target_addr_offset);
8823 			*addrp = dst;
8824 			/* Up to the resolver. */
8825 			if (canputnext(dst_ill->ill_rq) &&
8826 			    !(dst_ill->ill_arp_closing)) {
8827 				putnext(dst_ill->ill_rq, mp);
8828 				ire = NULL;
8829 				if (copy_mp != NULL) {
8830 					/*
8831 					 * If we found a resolver, we ignore
8832 					 * any trailing top priority IRE_CACHE
8833 					 * in the further loops. This ensures
8834 					 * that we do not omit any resolver.
8835 					 * IRE_CACHE entries, if any, will be
8836 					 * processed next time we enter
8837 					 * ip_newroute().
8838 					 */
8839 					multirt_flags &= ~MULTIRT_CACHEGW;
8840 					/*
8841 					 * Search for the next unresolved
8842 					 * multirt route.
8843 					 */
8844 					first_mp = copy_mp;
8845 					copy_mp = NULL;
8846 					/* Prepare the next resolution loop. */
8847 					mp = first_mp;
8848 					EXTRACT_PKT_MP(mp, first_mp,
8849 					    mctl_present);
8850 					if (mctl_present)
8851 						io = (ipsec_out_t *)
8852 						    first_mp->b_rptr;
8853 					ipha = (ipha_t *)mp->b_rptr;
8854 
8855 					ASSERT(sire != NULL);
8856 
8857 					dst = save_dst;
8858 					multirt_resolve_next = B_TRUE;
8859 					continue;
8860 				}
8861 
8862 				if (sire != NULL)
8863 					ire_refrele(sire);
8864 
8865 				/*
8866 				 * The response will come back in ip_wput
8867 				 * with db_type IRE_DB_TYPE.
8868 				 */
8869 				ipif_refrele(src_ipif);
8870 				ill_refrele(dst_ill);
8871 				return;
8872 			} else {
8873 				/* Prepare for cleanup */
8874 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8875 				    mp);
8876 				mp->b_cont = NULL;
8877 				freeb(mp); /* areq */
8878 				/*
8879 				 * this is an ire that is not added to the
8880 				 * cache. ire_freemblk will handle the release
8881 				 * of any resources associated with the ire.
8882 				 */
8883 				ire_delete(ire); /* ire_mp */
8884 				mp = saved_mp; /* pkt */
8885 				ire = NULL;
8886 				if (copy_mp != NULL) {
8887 					MULTIRT_DEBUG_UNTAG(copy_mp);
8888 					freemsg(copy_mp);
8889 					copy_mp = NULL;
8890 				}
8891 				break;
8892 			}
8893 		default:
8894 			break;
8895 		}
8896 	} while (multirt_resolve_next);
8897 
8898 	ip1dbg(("ip_newroute: dropped\n"));
8899 	/* Did this packet originate externally? */
8900 	if (mp->b_prev) {
8901 		mp->b_next = NULL;
8902 		mp->b_prev = NULL;
8903 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8904 	} else {
8905 		if (dst_ill != NULL) {
8906 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8907 		} else {
8908 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8909 		}
8910 	}
8911 	ASSERT(copy_mp == NULL);
8912 	MULTIRT_DEBUG_UNTAG(first_mp);
8913 	freemsg(first_mp);
8914 	if (ire != NULL)
8915 		ire_refrele(ire);
8916 	if (sire != NULL)
8917 		ire_refrele(sire);
8918 	if (src_ipif != NULL)
8919 		ipif_refrele(src_ipif);
8920 	if (dst_ill != NULL)
8921 		ill_refrele(dst_ill);
8922 	return;
8923 
8924 icmp_err_ret:
8925 	ip1dbg(("ip_newroute: no route\n"));
8926 	if (src_ipif != NULL)
8927 		ipif_refrele(src_ipif);
8928 	if (dst_ill != NULL)
8929 		ill_refrele(dst_ill);
8930 	if (sire != NULL)
8931 		ire_refrele(sire);
8932 	/* Did this packet originate externally? */
8933 	if (mp->b_prev) {
8934 		mp->b_next = NULL;
8935 		mp->b_prev = NULL;
8936 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8937 		q = WR(q);
8938 	} else {
8939 		/*
8940 		 * There is no outgoing ill, so just increment the
8941 		 * system MIB.
8942 		 */
8943 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8944 		/*
8945 		 * Since ip_wput() isn't close to finished, we fill
8946 		 * in enough of the header for credible error reporting.
8947 		 */
8948 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8949 			/* Failed */
8950 			MULTIRT_DEBUG_UNTAG(first_mp);
8951 			freemsg(first_mp);
8952 			if (ire != NULL)
8953 				ire_refrele(ire);
8954 			return;
8955 		}
8956 	}
8957 
8958 	/*
8959 	 * At this point we will have ire only if RTF_BLACKHOLE
8960 	 * or RTF_REJECT flags are set on the IRE. It will not
8961 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8962 	 */
8963 	if (ire != NULL) {
8964 		if (ire->ire_flags & RTF_BLACKHOLE) {
8965 			ire_refrele(ire);
8966 			MULTIRT_DEBUG_UNTAG(first_mp);
8967 			freemsg(first_mp);
8968 			return;
8969 		}
8970 		ire_refrele(ire);
8971 	}
8972 	if (ip_source_routed(ipha, ipst)) {
8973 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8974 		    zoneid, ipst);
8975 		return;
8976 	}
8977 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8978 }
8979 
8980 ip_opt_info_t zero_info;
8981 
8982 /*
8983  * IPv4 -
8984  * ip_newroute_ipif is called by ip_wput_multicast and
8985  * ip_rput_forward_multicast whenever we need to send
8986  * out a packet to a destination address for which we do not have specific
8987  * routing information. It is used when the packet will be sent out
8988  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8989  * socket option is set or icmp error message wants to go out on a particular
8990  * interface for a unicast packet.
8991  *
8992  * In most cases, the destination address is resolved thanks to the ipif
8993  * intrinsic resolver. However, there are some cases where the call to
8994  * ip_newroute_ipif must take into account the potential presence of
8995  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8996  * that uses the interface. This is specified through flags,
8997  * which can be a combination of:
8998  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8999  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9000  *   and flags. Additionally, the packet source address has to be set to
9001  *   the specified address. The caller is thus expected to set this flag
9002  *   if the packet has no specific source address yet.
9003  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9004  *   flag, the resulting ire will inherit the flag. All unresolved routes
9005  *   to the destination must be explored in the same call to
9006  *   ip_newroute_ipif().
9007  */
9008 static void
9009 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9010     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9011 {
9012 	areq_t	*areq;
9013 	ire_t	*ire = NULL;
9014 	mblk_t	*res_mp;
9015 	ipaddr_t *addrp;
9016 	mblk_t *first_mp;
9017 	ire_t	*save_ire = NULL;
9018 	ipif_t	*src_ipif = NULL;
9019 	ushort_t ire_marks = 0;
9020 	ill_t	*dst_ill = NULL;
9021 	ipha_t *ipha;
9022 	mblk_t	*saved_mp;
9023 	ire_t   *fire = NULL;
9024 	mblk_t  *copy_mp = NULL;
9025 	boolean_t multirt_resolve_next;
9026 	boolean_t unspec_src;
9027 	ipaddr_t ipha_dst;
9028 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9029 
9030 	/*
9031 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9032 	 * here for uniformity
9033 	 */
9034 	ipif_refhold(ipif);
9035 
9036 	/*
9037 	 * This loop is run only once in most cases.
9038 	 * We loop to resolve further routes only when the destination
9039 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9040 	 */
9041 	do {
9042 		if (dst_ill != NULL) {
9043 			ill_refrele(dst_ill);
9044 			dst_ill = NULL;
9045 		}
9046 		if (src_ipif != NULL) {
9047 			ipif_refrele(src_ipif);
9048 			src_ipif = NULL;
9049 		}
9050 		multirt_resolve_next = B_FALSE;
9051 
9052 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9053 		    ipif->ipif_ill->ill_name));
9054 
9055 		first_mp = mp;
9056 		if (DB_TYPE(mp) == M_CTL)
9057 			mp = mp->b_cont;
9058 		ipha = (ipha_t *)mp->b_rptr;
9059 
9060 		/*
9061 		 * Save the packet destination address, we may need it after
9062 		 * the packet has been consumed.
9063 		 */
9064 		ipha_dst = ipha->ipha_dst;
9065 
9066 		/*
9067 		 * If the interface is a pt-pt interface we look for an
9068 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9069 		 * local_address and the pt-pt destination address. Otherwise
9070 		 * we just match the local address.
9071 		 * NOTE: dst could be different than ipha->ipha_dst in case
9072 		 * of sending igmp multicast packets over a point-to-point
9073 		 * connection.
9074 		 * Thus we must be careful enough to check ipha_dst to be a
9075 		 * multicast address, otherwise it will take xmit_if path for
9076 		 * multicast packets resulting into kernel stack overflow by
9077 		 * repeated calls to ip_newroute_ipif from ire_send().
9078 		 */
9079 		if (CLASSD(ipha_dst) &&
9080 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9081 			goto err_ret;
9082 		}
9083 
9084 		/*
9085 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9086 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9087 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9088 		 * propagate its flags to the new ire.
9089 		 */
9090 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9091 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9092 			ip2dbg(("ip_newroute_ipif: "
9093 			    "ipif_lookup_multi_ire("
9094 			    "ipif %p, dst %08x) = fire %p\n",
9095 			    (void *)ipif, ntohl(dst), (void *)fire));
9096 		}
9097 
9098 		/*
9099 		 * Note: While we pick a dst_ill we are really only
9100 		 * interested in the ill for load spreading. The source
9101 		 * ipif is determined by source address selection below.
9102 		 */
9103 		if (IS_IPMP(ipif->ipif_ill)) {
9104 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9105 
9106 			if (CLASSD(ipha_dst))
9107 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9108 			else
9109 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9110 		} else {
9111 			dst_ill = ipif->ipif_ill;
9112 			ill_refhold(dst_ill);
9113 		}
9114 
9115 		if (dst_ill == NULL) {
9116 			if (ip_debug > 2) {
9117 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9118 				    "for dst %s\n", AF_INET, &dst);
9119 			}
9120 			goto err_ret;
9121 		}
9122 
9123 		/*
9124 		 * Pick a source address preferring non-deprecated ones.
9125 		 * Unlike ip_newroute, we don't do any source address
9126 		 * selection here since for multicast it really does not help
9127 		 * in inbound load spreading as in the unicast case.
9128 		 */
9129 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9130 		    (fire->ire_flags & RTF_SETSRC)) {
9131 			/*
9132 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9133 			 * on that interface. This ire has RTF_SETSRC flag, so
9134 			 * the source address of the packet must be changed.
9135 			 * Check that the ipif matching the requested source
9136 			 * address still exists.
9137 			 */
9138 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9139 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9140 		}
9141 
9142 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9143 
9144 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9145 		    (IS_IPMP(ipif->ipif_ill) ||
9146 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9147 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9148 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9149 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9150 		    (src_ipif == NULL) &&
9151 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9152 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9153 			if (src_ipif == NULL) {
9154 				if (ip_debug > 2) {
9155 					/* ip1dbg */
9156 					pr_addr_dbg("ip_newroute_ipif: "
9157 					    "no src for dst %s",
9158 					    AF_INET, &dst);
9159 				}
9160 				ip1dbg((" on interface %s\n",
9161 				    dst_ill->ill_name));
9162 				goto err_ret;
9163 			}
9164 			ipif_refrele(ipif);
9165 			ipif = src_ipif;
9166 			ipif_refhold(ipif);
9167 		}
9168 		if (src_ipif == NULL) {
9169 			src_ipif = ipif;
9170 			ipif_refhold(src_ipif);
9171 		}
9172 
9173 		/*
9174 		 * Assign a source address while we have the conn.
9175 		 * We can't have ip_wput_ire pick a source address when the
9176 		 * packet returns from arp since conn_unspec_src might be set
9177 		 * and we lose the conn when going through arp.
9178 		 */
9179 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9180 			ipha->ipha_src = src_ipif->ipif_src_addr;
9181 
9182 		/*
9183 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9184 		 * that the outgoing interface does not have an interface ire.
9185 		 */
9186 		if (CLASSD(ipha_dst) && (connp == NULL ||
9187 		    connp->conn_outgoing_ill == NULL) &&
9188 		    infop->ip_opt_ill_index == 0) {
9189 			/* ipif_to_ire returns an held ire */
9190 			ire = ipif_to_ire(ipif);
9191 			if (ire == NULL)
9192 				goto err_ret;
9193 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9194 				goto err_ret;
9195 			save_ire = ire;
9196 
9197 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9198 			    "flags %04x\n",
9199 			    (void *)ire, (void *)ipif, flags));
9200 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9201 			    (fire->ire_flags & RTF_MULTIRT)) {
9202 				/*
9203 				 * As requested by flags, an IRE_OFFSUBNET was
9204 				 * looked up on that interface. This ire has
9205 				 * RTF_MULTIRT flag, so the resolution loop will
9206 				 * be re-entered to resolve additional routes on
9207 				 * other interfaces. For that purpose, a copy of
9208 				 * the packet is performed at this point.
9209 				 */
9210 				fire->ire_last_used_time = lbolt;
9211 				copy_mp = copymsg(first_mp);
9212 				if (copy_mp) {
9213 					MULTIRT_DEBUG_TAG(copy_mp);
9214 				}
9215 			}
9216 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9217 			    (fire->ire_flags & RTF_SETSRC)) {
9218 				/*
9219 				 * As requested by flags, an IRE_OFFSUBET was
9220 				 * looked up on that interface. This ire has
9221 				 * RTF_SETSRC flag, so the source address of the
9222 				 * packet must be changed.
9223 				 */
9224 				ipha->ipha_src = fire->ire_src_addr;
9225 			}
9226 		} else {
9227 			/*
9228 			 * The only ways we can come here are:
9229 			 * 1) IP_BOUND_IF socket option is set
9230 			 * 2) SO_DONTROUTE socket option is set
9231 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9232 			 * In all cases, the new ire will not be added
9233 			 * into cache table.
9234 			 */
9235 			ASSERT(connp == NULL || connp->conn_dontroute ||
9236 			    connp->conn_outgoing_ill != NULL ||
9237 			    infop->ip_opt_ill_index != 0);
9238 			ire_marks |= IRE_MARK_NOADD;
9239 		}
9240 
9241 		switch (ipif->ipif_net_type) {
9242 		case IRE_IF_NORESOLVER: {
9243 			/* We have what we need to build an IRE_CACHE. */
9244 
9245 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9246 			    (dst_ill->ill_resolver_mp == NULL)) {
9247 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9248 				    "for IRE_IF_NORESOLVER ire %p has "
9249 				    "no ill_resolver_mp\n",
9250 				    (void *)dst_ill, (void *)ire));
9251 				break;
9252 			}
9253 
9254 			/*
9255 			 * The new ire inherits the IRE_OFFSUBNET flags
9256 			 * and source address, if this was requested.
9257 			 */
9258 			ire = ire_create(
9259 			    (uchar_t *)&dst,		/* dest address */
9260 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9261 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9262 			    NULL,			/* gateway address */
9263 			    &ipif->ipif_mtu,
9264 			    NULL,			/* no src nce */
9265 			    dst_ill->ill_rq,		/* recv-from queue */
9266 			    dst_ill->ill_wq,		/* send-to queue */
9267 			    IRE_CACHE,
9268 			    src_ipif,
9269 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9270 			    (fire != NULL) ?		/* Parent handle */
9271 			    fire->ire_phandle : 0,
9272 			    (save_ire != NULL) ?	/* Interface handle */
9273 			    save_ire->ire_ihandle : 0,
9274 			    (fire != NULL) ?
9275 			    (fire->ire_flags &
9276 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9277 			    (save_ire == NULL ? &ire_uinfo_null :
9278 			    &save_ire->ire_uinfo),
9279 			    NULL,
9280 			    NULL,
9281 			    ipst);
9282 
9283 			if (ire == NULL) {
9284 				if (save_ire != NULL)
9285 					ire_refrele(save_ire);
9286 				break;
9287 			}
9288 
9289 			ire->ire_marks |= ire_marks;
9290 
9291 			/*
9292 			 * If IRE_MARK_NOADD is set then we need to convert
9293 			 * the max_fragp to a useable value now. This is
9294 			 * normally done in ire_add_v[46]. We also need to
9295 			 * associate the ire with an nce (normally would be
9296 			 * done in ip_wput_nondata()).
9297 			 *
9298 			 * Note that IRE_MARK_NOADD packets created here
9299 			 * do not have a non-null ire_mp pointer. The null
9300 			 * value of ire_bucket indicates that they were
9301 			 * never added.
9302 			 */
9303 			if (ire->ire_marks & IRE_MARK_NOADD) {
9304 				uint_t  max_frag;
9305 
9306 				max_frag = *ire->ire_max_fragp;
9307 				ire->ire_max_fragp = NULL;
9308 				ire->ire_max_frag = max_frag;
9309 
9310 				if ((ire->ire_nce = ndp_lookup_v4(
9311 				    ire_to_ill(ire),
9312 				    (ire->ire_gateway_addr != INADDR_ANY ?
9313 				    &ire->ire_gateway_addr : &ire->ire_addr),
9314 				    B_FALSE)) == NULL) {
9315 					if (save_ire != NULL)
9316 						ire_refrele(save_ire);
9317 					break;
9318 				}
9319 				ASSERT(ire->ire_nce->nce_state ==
9320 				    ND_REACHABLE);
9321 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9322 			}
9323 
9324 			/* Prevent save_ire from getting deleted */
9325 			if (save_ire != NULL) {
9326 				IRB_REFHOLD(save_ire->ire_bucket);
9327 				/* Has it been removed already ? */
9328 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9329 					IRB_REFRELE(save_ire->ire_bucket);
9330 					ire_refrele(save_ire);
9331 					break;
9332 				}
9333 			}
9334 
9335 			ire_add_then_send(q, ire, first_mp);
9336 
9337 			/* Assert that save_ire is not deleted yet. */
9338 			if (save_ire != NULL) {
9339 				ASSERT(save_ire->ire_ptpn != NULL);
9340 				IRB_REFRELE(save_ire->ire_bucket);
9341 				ire_refrele(save_ire);
9342 				save_ire = NULL;
9343 			}
9344 			if (fire != NULL) {
9345 				ire_refrele(fire);
9346 				fire = NULL;
9347 			}
9348 
9349 			/*
9350 			 * the resolution loop is re-entered if this
9351 			 * was requested through flags and if we
9352 			 * actually are in a multirouting case.
9353 			 */
9354 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9355 				boolean_t need_resolve =
9356 				    ire_multirt_need_resolve(ipha_dst,
9357 				    msg_getlabel(copy_mp), ipst);
9358 				if (!need_resolve) {
9359 					MULTIRT_DEBUG_UNTAG(copy_mp);
9360 					freemsg(copy_mp);
9361 					copy_mp = NULL;
9362 				} else {
9363 					/*
9364 					 * ipif_lookup_group() calls
9365 					 * ire_lookup_multi() that uses
9366 					 * ire_ftable_lookup() to find
9367 					 * an IRE_INTERFACE for the group.
9368 					 * In the multirt case,
9369 					 * ire_lookup_multi() then invokes
9370 					 * ire_multirt_lookup() to find
9371 					 * the next resolvable ire.
9372 					 * As a result, we obtain an new
9373 					 * interface, derived from the
9374 					 * next ire.
9375 					 */
9376 					ipif_refrele(ipif);
9377 					ipif = ipif_lookup_group(ipha_dst,
9378 					    zoneid, ipst);
9379 					ip2dbg(("ip_newroute_ipif: "
9380 					    "multirt dst %08x, ipif %p\n",
9381 					    htonl(dst), (void *)ipif));
9382 					if (ipif != NULL) {
9383 						mp = copy_mp;
9384 						copy_mp = NULL;
9385 						multirt_resolve_next = B_TRUE;
9386 						continue;
9387 					} else {
9388 						freemsg(copy_mp);
9389 					}
9390 				}
9391 			}
9392 			if (ipif != NULL)
9393 				ipif_refrele(ipif);
9394 			ill_refrele(dst_ill);
9395 			ipif_refrele(src_ipif);
9396 			return;
9397 		}
9398 		case IRE_IF_RESOLVER:
9399 			/*
9400 			 * We can't build an IRE_CACHE yet, but at least
9401 			 * we found a resolver that can help.
9402 			 */
9403 			res_mp = dst_ill->ill_resolver_mp;
9404 			if (!OK_RESOLVER_MP(res_mp))
9405 				break;
9406 
9407 			/*
9408 			 * We obtain a partial IRE_CACHE which we will pass
9409 			 * along with the resolver query.  When the response
9410 			 * comes back it will be there ready for us to add.
9411 			 * The new ire inherits the IRE_OFFSUBNET flags
9412 			 * and source address, if this was requested.
9413 			 * The ire_max_frag is atomically set under the
9414 			 * irebucket lock in ire_add_v[46]. Only in the
9415 			 * case of IRE_MARK_NOADD, we set it here itself.
9416 			 */
9417 			ire = ire_create_mp(
9418 			    (uchar_t *)&dst,		/* dest address */
9419 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9420 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9421 			    NULL,			/* gateway address */
9422 			    (ire_marks & IRE_MARK_NOADD) ?
9423 			    ipif->ipif_mtu : 0,		/* max_frag */
9424 			    NULL,			/* no src nce */
9425 			    dst_ill->ill_rq,		/* recv-from queue */
9426 			    dst_ill->ill_wq,		/* send-to queue */
9427 			    IRE_CACHE,
9428 			    src_ipif,
9429 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9430 			    (fire != NULL) ?		/* Parent handle */
9431 			    fire->ire_phandle : 0,
9432 			    (save_ire != NULL) ?	/* Interface handle */
9433 			    save_ire->ire_ihandle : 0,
9434 			    (fire != NULL) ?		/* flags if any */
9435 			    (fire->ire_flags &
9436 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9437 			    (save_ire == NULL ? &ire_uinfo_null :
9438 			    &save_ire->ire_uinfo),
9439 			    NULL,
9440 			    NULL,
9441 			    ipst);
9442 
9443 			if (save_ire != NULL) {
9444 				ire_refrele(save_ire);
9445 				save_ire = NULL;
9446 			}
9447 			if (ire == NULL)
9448 				break;
9449 
9450 			ire->ire_marks |= ire_marks;
9451 			/*
9452 			 * Construct message chain for the resolver of the
9453 			 * form:
9454 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9455 			 *
9456 			 * NOTE : ire will be added later when the response
9457 			 * comes back from ARP. If the response does not
9458 			 * come back, ARP frees the packet. For this reason,
9459 			 * we can't REFHOLD the bucket of save_ire to prevent
9460 			 * deletions. We may not be able to REFRELE the
9461 			 * bucket if the response never comes back.
9462 			 * Thus, before adding the ire, ire_add_v4 will make
9463 			 * sure that the interface route does not get deleted.
9464 			 * This is the only case unlike ip_newroute_v6,
9465 			 * ip_newroute_ipif_v6 where we can always prevent
9466 			 * deletions because ire_add_then_send is called after
9467 			 * creating the IRE.
9468 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9469 			 * does not add this IRE into the IRE CACHE.
9470 			 */
9471 			ASSERT(ire->ire_mp != NULL);
9472 			ire->ire_mp->b_cont = first_mp;
9473 			/* Have saved_mp handy, for cleanup if canput fails */
9474 			saved_mp = mp;
9475 			mp = copyb(res_mp);
9476 			if (mp == NULL) {
9477 				/* Prepare for cleanup */
9478 				mp = saved_mp; /* pkt */
9479 				ire_delete(ire); /* ire_mp */
9480 				ire = NULL;
9481 				if (copy_mp != NULL) {
9482 					MULTIRT_DEBUG_UNTAG(copy_mp);
9483 					freemsg(copy_mp);
9484 					copy_mp = NULL;
9485 				}
9486 				break;
9487 			}
9488 			linkb(mp, ire->ire_mp);
9489 
9490 			/*
9491 			 * Fill in the source and dest addrs for the resolver.
9492 			 * NOTE: this depends on memory layouts imposed by
9493 			 * ill_init().  There are corner cases above where we
9494 			 * might've created the IRE with an INADDR_ANY source
9495 			 * address (e.g., if the zeroth ipif on an underlying
9496 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9497 			 * on the ill has a usable test address).  If so, tell
9498 			 * ARP to use ipha_src as its sender address.
9499 			 */
9500 			areq = (areq_t *)mp->b_rptr;
9501 			addrp = (ipaddr_t *)((char *)areq +
9502 			    areq->areq_sender_addr_offset);
9503 			if (ire->ire_src_addr != INADDR_ANY)
9504 				*addrp = ire->ire_src_addr;
9505 			else
9506 				*addrp = ipha->ipha_src;
9507 			addrp = (ipaddr_t *)((char *)areq +
9508 			    areq->areq_target_addr_offset);
9509 			*addrp = dst;
9510 			/* Up to the resolver. */
9511 			if (canputnext(dst_ill->ill_rq) &&
9512 			    !(dst_ill->ill_arp_closing)) {
9513 				putnext(dst_ill->ill_rq, mp);
9514 				/*
9515 				 * The response will come back in ip_wput
9516 				 * with db_type IRE_DB_TYPE.
9517 				 */
9518 			} else {
9519 				mp->b_cont = NULL;
9520 				freeb(mp); /* areq */
9521 				ire_delete(ire); /* ire_mp */
9522 				saved_mp->b_next = NULL;
9523 				saved_mp->b_prev = NULL;
9524 				freemsg(first_mp); /* pkt */
9525 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9526 			}
9527 
9528 			if (fire != NULL) {
9529 				ire_refrele(fire);
9530 				fire = NULL;
9531 			}
9532 
9533 			/*
9534 			 * The resolution loop is re-entered if this was
9535 			 * requested through flags and we actually are
9536 			 * in a multirouting case.
9537 			 */
9538 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9539 				boolean_t need_resolve =
9540 				    ire_multirt_need_resolve(ipha_dst,
9541 				    msg_getlabel(copy_mp), ipst);
9542 				if (!need_resolve) {
9543 					MULTIRT_DEBUG_UNTAG(copy_mp);
9544 					freemsg(copy_mp);
9545 					copy_mp = NULL;
9546 				} else {
9547 					/*
9548 					 * ipif_lookup_group() calls
9549 					 * ire_lookup_multi() that uses
9550 					 * ire_ftable_lookup() to find
9551 					 * an IRE_INTERFACE for the group.
9552 					 * In the multirt case,
9553 					 * ire_lookup_multi() then invokes
9554 					 * ire_multirt_lookup() to find
9555 					 * the next resolvable ire.
9556 					 * As a result, we obtain an new
9557 					 * interface, derived from the
9558 					 * next ire.
9559 					 */
9560 					ipif_refrele(ipif);
9561 					ipif = ipif_lookup_group(ipha_dst,
9562 					    zoneid, ipst);
9563 					if (ipif != NULL) {
9564 						mp = copy_mp;
9565 						copy_mp = NULL;
9566 						multirt_resolve_next = B_TRUE;
9567 						continue;
9568 					} else {
9569 						freemsg(copy_mp);
9570 					}
9571 				}
9572 			}
9573 			if (ipif != NULL)
9574 				ipif_refrele(ipif);
9575 			ill_refrele(dst_ill);
9576 			ipif_refrele(src_ipif);
9577 			return;
9578 		default:
9579 			break;
9580 		}
9581 	} while (multirt_resolve_next);
9582 
9583 err_ret:
9584 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9585 	if (fire != NULL)
9586 		ire_refrele(fire);
9587 	ipif_refrele(ipif);
9588 	/* Did this packet originate externally? */
9589 	if (dst_ill != NULL)
9590 		ill_refrele(dst_ill);
9591 	if (src_ipif != NULL)
9592 		ipif_refrele(src_ipif);
9593 	if (mp->b_prev || mp->b_next) {
9594 		mp->b_next = NULL;
9595 		mp->b_prev = NULL;
9596 	} else {
9597 		/*
9598 		 * Since ip_wput() isn't close to finished, we fill
9599 		 * in enough of the header for credible error reporting.
9600 		 */
9601 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9602 			/* Failed */
9603 			freemsg(first_mp);
9604 			if (ire != NULL)
9605 				ire_refrele(ire);
9606 			return;
9607 		}
9608 	}
9609 	/*
9610 	 * At this point we will have ire only if RTF_BLACKHOLE
9611 	 * or RTF_REJECT flags are set on the IRE. It will not
9612 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9613 	 */
9614 	if (ire != NULL) {
9615 		if (ire->ire_flags & RTF_BLACKHOLE) {
9616 			ire_refrele(ire);
9617 			freemsg(first_mp);
9618 			return;
9619 		}
9620 		ire_refrele(ire);
9621 	}
9622 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9623 }
9624 
9625 /* Name/Value Table Lookup Routine */
9626 char *
9627 ip_nv_lookup(nv_t *nv, int value)
9628 {
9629 	if (!nv)
9630 		return (NULL);
9631 	for (; nv->nv_name; nv++) {
9632 		if (nv->nv_value == value)
9633 			return (nv->nv_name);
9634 	}
9635 	return ("unknown");
9636 }
9637 
9638 /*
9639  * This is a module open, i.e. this is a control stream for access
9640  * to a DLPI device.  We allocate an ill_t as the instance data in
9641  * this case.
9642  */
9643 int
9644 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9645 {
9646 	ill_t	*ill;
9647 	int	err;
9648 	zoneid_t zoneid;
9649 	netstack_t *ns;
9650 	ip_stack_t *ipst;
9651 
9652 	/*
9653 	 * Prevent unprivileged processes from pushing IP so that
9654 	 * they can't send raw IP.
9655 	 */
9656 	if (secpolicy_net_rawaccess(credp) != 0)
9657 		return (EPERM);
9658 
9659 	ns = netstack_find_by_cred(credp);
9660 	ASSERT(ns != NULL);
9661 	ipst = ns->netstack_ip;
9662 	ASSERT(ipst != NULL);
9663 
9664 	/*
9665 	 * For exclusive stacks we set the zoneid to zero
9666 	 * to make IP operate as if in the global zone.
9667 	 */
9668 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9669 		zoneid = GLOBAL_ZONEID;
9670 	else
9671 		zoneid = crgetzoneid(credp);
9672 
9673 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9674 	q->q_ptr = WR(q)->q_ptr = ill;
9675 	ill->ill_ipst = ipst;
9676 	ill->ill_zoneid = zoneid;
9677 
9678 	/*
9679 	 * ill_init initializes the ill fields and then sends down
9680 	 * down a DL_INFO_REQ after calling qprocson.
9681 	 */
9682 	err = ill_init(q, ill);
9683 	if (err != 0) {
9684 		mi_free(ill);
9685 		netstack_rele(ipst->ips_netstack);
9686 		q->q_ptr = NULL;
9687 		WR(q)->q_ptr = NULL;
9688 		return (err);
9689 	}
9690 
9691 	/* ill_init initializes the ipsq marking this thread as writer */
9692 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9693 	/* Wait for the DL_INFO_ACK */
9694 	mutex_enter(&ill->ill_lock);
9695 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9696 		/*
9697 		 * Return value of 0 indicates a pending signal.
9698 		 */
9699 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9700 		if (err == 0) {
9701 			mutex_exit(&ill->ill_lock);
9702 			(void) ip_close(q, 0);
9703 			return (EINTR);
9704 		}
9705 	}
9706 	mutex_exit(&ill->ill_lock);
9707 
9708 	/*
9709 	 * ip_rput_other could have set an error  in ill_error on
9710 	 * receipt of M_ERROR.
9711 	 */
9712 
9713 	err = ill->ill_error;
9714 	if (err != 0) {
9715 		(void) ip_close(q, 0);
9716 		return (err);
9717 	}
9718 
9719 	ill->ill_credp = credp;
9720 	crhold(credp);
9721 
9722 	mutex_enter(&ipst->ips_ip_mi_lock);
9723 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9724 	    credp);
9725 	mutex_exit(&ipst->ips_ip_mi_lock);
9726 	if (err) {
9727 		(void) ip_close(q, 0);
9728 		return (err);
9729 	}
9730 	return (0);
9731 }
9732 
9733 /* For /dev/ip aka AF_INET open */
9734 int
9735 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9736 {
9737 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9738 }
9739 
9740 /* For /dev/ip6 aka AF_INET6 open */
9741 int
9742 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9743 {
9744 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9745 }
9746 
9747 /* IP open routine. */
9748 int
9749 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9750     boolean_t isv6)
9751 {
9752 	conn_t 		*connp;
9753 	major_t		maj;
9754 	zoneid_t	zoneid;
9755 	netstack_t	*ns;
9756 	ip_stack_t	*ipst;
9757 
9758 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9759 
9760 	/* Allow reopen. */
9761 	if (q->q_ptr != NULL)
9762 		return (0);
9763 
9764 	if (sflag & MODOPEN) {
9765 		/* This is a module open */
9766 		return (ip_modopen(q, devp, flag, sflag, credp));
9767 	}
9768 
9769 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9770 		/*
9771 		 * Non streams based socket looking for a stream
9772 		 * to access IP
9773 		 */
9774 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9775 		    credp, isv6));
9776 	}
9777 
9778 	ns = netstack_find_by_cred(credp);
9779 	ASSERT(ns != NULL);
9780 	ipst = ns->netstack_ip;
9781 	ASSERT(ipst != NULL);
9782 
9783 	/*
9784 	 * For exclusive stacks we set the zoneid to zero
9785 	 * to make IP operate as if in the global zone.
9786 	 */
9787 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9788 		zoneid = GLOBAL_ZONEID;
9789 	else
9790 		zoneid = crgetzoneid(credp);
9791 
9792 	/*
9793 	 * We are opening as a device. This is an IP client stream, and we
9794 	 * allocate an conn_t as the instance data.
9795 	 */
9796 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9797 
9798 	/*
9799 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9800 	 * done by netstack_find_by_cred()
9801 	 */
9802 	netstack_rele(ipst->ips_netstack);
9803 
9804 	connp->conn_zoneid = zoneid;
9805 	connp->conn_sqp = NULL;
9806 	connp->conn_initial_sqp = NULL;
9807 	connp->conn_final_sqp = NULL;
9808 
9809 	connp->conn_upq = q;
9810 	q->q_ptr = WR(q)->q_ptr = connp;
9811 
9812 	if (flag & SO_SOCKSTR)
9813 		connp->conn_flags |= IPCL_SOCKET;
9814 
9815 	/* Minor tells us which /dev entry was opened */
9816 	if (isv6) {
9817 		connp->conn_flags |= IPCL_ISV6;
9818 		connp->conn_af_isv6 = B_TRUE;
9819 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9820 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9821 	} else {
9822 		connp->conn_af_isv6 = B_FALSE;
9823 		connp->conn_pkt_isv6 = B_FALSE;
9824 	}
9825 
9826 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9827 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9828 		connp->conn_minor_arena = ip_minor_arena_la;
9829 	} else {
9830 		/*
9831 		 * Either minor numbers in the large arena were exhausted
9832 		 * or a non socket application is doing the open.
9833 		 * Try to allocate from the small arena.
9834 		 */
9835 		if ((connp->conn_dev =
9836 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9837 			/* CONN_DEC_REF takes care of netstack_rele() */
9838 			q->q_ptr = WR(q)->q_ptr = NULL;
9839 			CONN_DEC_REF(connp);
9840 			return (EBUSY);
9841 		}
9842 		connp->conn_minor_arena = ip_minor_arena_sa;
9843 	}
9844 
9845 	maj = getemajor(*devp);
9846 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9847 
9848 	/*
9849 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9850 	 */
9851 	connp->conn_cred = credp;
9852 
9853 	/*
9854 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9855 	 */
9856 	connp->conn_recv = ip_conn_input;
9857 
9858 	crhold(connp->conn_cred);
9859 
9860 	/*
9861 	 * If the caller has the process-wide flag set, then default to MAC
9862 	 * exempt mode.  This allows read-down to unlabeled hosts.
9863 	 */
9864 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9865 		connp->conn_mac_exempt = B_TRUE;
9866 
9867 	connp->conn_rq = q;
9868 	connp->conn_wq = WR(q);
9869 
9870 	/* Non-zero default values */
9871 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9872 
9873 	/*
9874 	 * Make the conn globally visible to walkers
9875 	 */
9876 	ASSERT(connp->conn_ref == 1);
9877 	mutex_enter(&connp->conn_lock);
9878 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9879 	mutex_exit(&connp->conn_lock);
9880 
9881 	qprocson(q);
9882 
9883 	return (0);
9884 }
9885 
9886 /*
9887  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9888  * Note that there is no race since either ip_output function works - it
9889  * is just an optimization to enter the best ip_output routine directly.
9890  */
9891 void
9892 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9893     ip_stack_t *ipst)
9894 {
9895 	if (isv6)  {
9896 		if (bump_mib) {
9897 			BUMP_MIB(&ipst->ips_ip6_mib,
9898 			    ipIfStatsOutSwitchIPVersion);
9899 		}
9900 		connp->conn_send = ip_output_v6;
9901 		connp->conn_pkt_isv6 = B_TRUE;
9902 	} else {
9903 		if (bump_mib) {
9904 			BUMP_MIB(&ipst->ips_ip_mib,
9905 			    ipIfStatsOutSwitchIPVersion);
9906 		}
9907 		connp->conn_send = ip_output;
9908 		connp->conn_pkt_isv6 = B_FALSE;
9909 	}
9910 
9911 }
9912 
9913 /*
9914  * See if IPsec needs loading because of the options in mp.
9915  */
9916 static boolean_t
9917 ipsec_opt_present(mblk_t *mp)
9918 {
9919 	uint8_t *optcp, *next_optcp, *opt_endcp;
9920 	struct opthdr *opt;
9921 	struct T_opthdr *topt;
9922 	int opthdr_len;
9923 	t_uscalar_t optname, optlevel;
9924 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9925 	ipsec_req_t *ipsr;
9926 
9927 	/*
9928 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9929 	 * return TRUE.
9930 	 */
9931 
9932 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9933 	opt_endcp = optcp + tor->OPT_length;
9934 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9935 		opthdr_len = sizeof (struct T_opthdr);
9936 	} else {		/* O_OPTMGMT_REQ */
9937 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9938 		opthdr_len = sizeof (struct opthdr);
9939 	}
9940 	for (; optcp < opt_endcp; optcp = next_optcp) {
9941 		if (optcp + opthdr_len > opt_endcp)
9942 			return (B_FALSE);	/* Not enough option header. */
9943 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9944 			topt = (struct T_opthdr *)optcp;
9945 			optlevel = topt->level;
9946 			optname = topt->name;
9947 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9948 		} else {
9949 			opt = (struct opthdr *)optcp;
9950 			optlevel = opt->level;
9951 			optname = opt->name;
9952 			next_optcp = optcp + opthdr_len +
9953 			    _TPI_ALIGN_OPT(opt->len);
9954 		}
9955 		if ((next_optcp < optcp) || /* wraparound pointer space */
9956 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9957 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9958 			return (B_FALSE); /* bad option buffer */
9959 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9960 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9961 			/*
9962 			 * Check to see if it's an all-bypass or all-zeroes
9963 			 * IPsec request.  Don't bother loading IPsec if
9964 			 * the socket doesn't want to use it.  (A good example
9965 			 * is a bypass request.)
9966 			 *
9967 			 * Basically, if any of the non-NEVER bits are set,
9968 			 * load IPsec.
9969 			 */
9970 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9971 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9972 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9973 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9974 			    != 0)
9975 				return (B_TRUE);
9976 		}
9977 	}
9978 	return (B_FALSE);
9979 }
9980 
9981 /*
9982  * If conn is is waiting for ipsec to finish loading, kick it.
9983  */
9984 /* ARGSUSED */
9985 static void
9986 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9987 {
9988 	t_scalar_t	optreq_prim;
9989 	mblk_t		*mp;
9990 	cred_t		*cr;
9991 	int		err = 0;
9992 
9993 	/*
9994 	 * This function is called, after ipsec loading is complete.
9995 	 * Since IP checks exclusively and atomically (i.e it prevents
9996 	 * ipsec load from completing until ip_optcom_req completes)
9997 	 * whether ipsec load is complete, there cannot be a race with IP
9998 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9999 	 */
10000 	mutex_enter(&connp->conn_lock);
10001 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10002 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10003 		mp = connp->conn_ipsec_opt_mp;
10004 		connp->conn_ipsec_opt_mp = NULL;
10005 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10006 		mutex_exit(&connp->conn_lock);
10007 
10008 		/*
10009 		 * All Solaris components should pass a db_credp
10010 		 * for this TPI message, hence we ASSERT.
10011 		 * But in case there is some other M_PROTO that looks
10012 		 * like a TPI message sent by some other kernel
10013 		 * component, we check and return an error.
10014 		 */
10015 		cr = msg_getcred(mp, NULL);
10016 		ASSERT(cr != NULL);
10017 		if (cr == NULL) {
10018 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
10019 			if (mp != NULL)
10020 				qreply(connp->conn_wq, mp);
10021 			return;
10022 		}
10023 
10024 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10025 
10026 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10027 		if (optreq_prim == T_OPTMGMT_REQ) {
10028 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10029 			    &ip_opt_obj, B_FALSE);
10030 		} else {
10031 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10032 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10033 			    &ip_opt_obj, B_FALSE);
10034 		}
10035 		if (err != EINPROGRESS)
10036 			CONN_OPER_PENDING_DONE(connp);
10037 		return;
10038 	}
10039 	mutex_exit(&connp->conn_lock);
10040 }
10041 
10042 /*
10043  * Called from the ipsec_loader thread, outside any perimeter, to tell
10044  * ip qenable any of the queues waiting for the ipsec loader to
10045  * complete.
10046  */
10047 void
10048 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10049 {
10050 	netstack_t *ns = ipss->ipsec_netstack;
10051 
10052 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10053 }
10054 
10055 /*
10056  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10057  * determines the grp on which it has to become exclusive, queues the mp
10058  * and IPSQ draining restarts the optmgmt
10059  */
10060 static boolean_t
10061 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10062 {
10063 	conn_t *connp = Q_TO_CONN(q);
10064 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10065 
10066 	/*
10067 	 * Take IPsec requests and treat them special.
10068 	 */
10069 	if (ipsec_opt_present(mp)) {
10070 		/* First check if IPsec is loaded. */
10071 		mutex_enter(&ipss->ipsec_loader_lock);
10072 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10073 			mutex_exit(&ipss->ipsec_loader_lock);
10074 			return (B_FALSE);
10075 		}
10076 		mutex_enter(&connp->conn_lock);
10077 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10078 
10079 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10080 		connp->conn_ipsec_opt_mp = mp;
10081 		mutex_exit(&connp->conn_lock);
10082 		mutex_exit(&ipss->ipsec_loader_lock);
10083 
10084 		ipsec_loader_loadnow(ipss);
10085 		return (B_TRUE);
10086 	}
10087 	return (B_FALSE);
10088 }
10089 
10090 /*
10091  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10092  * all of them are copied to the conn_t. If the req is "zero", the policy is
10093  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10094  * fields.
10095  * We keep only the latest setting of the policy and thus policy setting
10096  * is not incremental/cumulative.
10097  *
10098  * Requests to set policies with multiple alternative actions will
10099  * go through a different API.
10100  */
10101 int
10102 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10103 {
10104 	uint_t ah_req = 0;
10105 	uint_t esp_req = 0;
10106 	uint_t se_req = 0;
10107 	ipsec_selkey_t sel;
10108 	ipsec_act_t *actp = NULL;
10109 	uint_t nact;
10110 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10111 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10112 	ipsec_policy_root_t *pr;
10113 	ipsec_policy_head_t *ph;
10114 	int fam;
10115 	boolean_t is_pol_reset;
10116 	int error = 0;
10117 	netstack_t	*ns = connp->conn_netstack;
10118 	ip_stack_t	*ipst = ns->netstack_ip;
10119 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10120 
10121 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10122 
10123 	/*
10124 	 * The IP_SEC_OPT option does not allow variable length parameters,
10125 	 * hence a request cannot be NULL.
10126 	 */
10127 	if (req == NULL)
10128 		return (EINVAL);
10129 
10130 	ah_req = req->ipsr_ah_req;
10131 	esp_req = req->ipsr_esp_req;
10132 	se_req = req->ipsr_self_encap_req;
10133 
10134 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10135 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10136 		return (EINVAL);
10137 
10138 	/*
10139 	 * Are we dealing with a request to reset the policy (i.e.
10140 	 * zero requests).
10141 	 */
10142 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10143 	    (esp_req & REQ_MASK) == 0 &&
10144 	    (se_req & REQ_MASK) == 0);
10145 
10146 	if (!is_pol_reset) {
10147 		/*
10148 		 * If we couldn't load IPsec, fail with "protocol
10149 		 * not supported".
10150 		 * IPsec may not have been loaded for a request with zero
10151 		 * policies, so we don't fail in this case.
10152 		 */
10153 		mutex_enter(&ipss->ipsec_loader_lock);
10154 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10155 			mutex_exit(&ipss->ipsec_loader_lock);
10156 			return (EPROTONOSUPPORT);
10157 		}
10158 		mutex_exit(&ipss->ipsec_loader_lock);
10159 
10160 		/*
10161 		 * Test for valid requests. Invalid algorithms
10162 		 * need to be tested by IPsec code because new
10163 		 * algorithms can be added dynamically.
10164 		 */
10165 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10166 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10167 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10168 			return (EINVAL);
10169 		}
10170 
10171 		/*
10172 		 * Only privileged users can issue these
10173 		 * requests.
10174 		 */
10175 		if (((ah_req & IPSEC_PREF_NEVER) ||
10176 		    (esp_req & IPSEC_PREF_NEVER) ||
10177 		    (se_req & IPSEC_PREF_NEVER)) &&
10178 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10179 			return (EPERM);
10180 		}
10181 
10182 		/*
10183 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10184 		 * are mutually exclusive.
10185 		 */
10186 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10187 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10188 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10189 			/* Both of them are set */
10190 			return (EINVAL);
10191 		}
10192 	}
10193 
10194 	mutex_enter(&connp->conn_lock);
10195 
10196 	/*
10197 	 * If we have already cached policies in ip_bind_connected*(), don't
10198 	 * let them change now. We cache policies for connections
10199 	 * whose src,dst [addr, port] is known.
10200 	 */
10201 	if (connp->conn_policy_cached) {
10202 		mutex_exit(&connp->conn_lock);
10203 		return (EINVAL);
10204 	}
10205 
10206 	/*
10207 	 * We have a zero policies, reset the connection policy if already
10208 	 * set. This will cause the connection to inherit the
10209 	 * global policy, if any.
10210 	 */
10211 	if (is_pol_reset) {
10212 		if (connp->conn_policy != NULL) {
10213 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10214 			connp->conn_policy = NULL;
10215 		}
10216 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10217 		connp->conn_in_enforce_policy = B_FALSE;
10218 		connp->conn_out_enforce_policy = B_FALSE;
10219 		mutex_exit(&connp->conn_lock);
10220 		return (0);
10221 	}
10222 
10223 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10224 	    ipst->ips_netstack);
10225 	if (ph == NULL)
10226 		goto enomem;
10227 
10228 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10229 	if (actp == NULL)
10230 		goto enomem;
10231 
10232 	/*
10233 	 * Always allocate IPv4 policy entries, since they can also
10234 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10235 	 */
10236 	bzero(&sel, sizeof (sel));
10237 	sel.ipsl_valid = IPSL_IPV4;
10238 
10239 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10240 	    ipst->ips_netstack);
10241 	if (pin4 == NULL)
10242 		goto enomem;
10243 
10244 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10245 	    ipst->ips_netstack);
10246 	if (pout4 == NULL)
10247 		goto enomem;
10248 
10249 	if (connp->conn_af_isv6) {
10250 		/*
10251 		 * We're looking at a v6 socket, also allocate the
10252 		 * v6-specific entries...
10253 		 */
10254 		sel.ipsl_valid = IPSL_IPV6;
10255 		pin6 = ipsec_policy_create(&sel, actp, nact,
10256 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10257 		if (pin6 == NULL)
10258 			goto enomem;
10259 
10260 		pout6 = ipsec_policy_create(&sel, actp, nact,
10261 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10262 		if (pout6 == NULL)
10263 			goto enomem;
10264 
10265 		/*
10266 		 * .. and file them away in the right place.
10267 		 */
10268 		fam = IPSEC_AF_V6;
10269 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10270 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10271 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10272 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10273 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10274 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10275 	}
10276 
10277 	ipsec_actvec_free(actp, nact);
10278 
10279 	/*
10280 	 * File the v4 policies.
10281 	 */
10282 	fam = IPSEC_AF_V4;
10283 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10284 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10285 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10286 
10287 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10288 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10289 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10290 
10291 	/*
10292 	 * If the requests need security, set enforce_policy.
10293 	 * If the requests are IPSEC_PREF_NEVER, one should
10294 	 * still set conn_out_enforce_policy so that an ipsec_out
10295 	 * gets attached in ip_wput. This is needed so that
10296 	 * for connections that we don't cache policy in ip_bind,
10297 	 * if global policy matches in ip_wput_attach_policy, we
10298 	 * don't wrongly inherit global policy. Similarly, we need
10299 	 * to set conn_in_enforce_policy also so that we don't verify
10300 	 * policy wrongly.
10301 	 */
10302 	if ((ah_req & REQ_MASK) != 0 ||
10303 	    (esp_req & REQ_MASK) != 0 ||
10304 	    (se_req & REQ_MASK) != 0) {
10305 		connp->conn_in_enforce_policy = B_TRUE;
10306 		connp->conn_out_enforce_policy = B_TRUE;
10307 		connp->conn_flags |= IPCL_CHECK_POLICY;
10308 	}
10309 
10310 	mutex_exit(&connp->conn_lock);
10311 	return (error);
10312 #undef REQ_MASK
10313 
10314 	/*
10315 	 * Common memory-allocation-failure exit path.
10316 	 */
10317 enomem:
10318 	mutex_exit(&connp->conn_lock);
10319 	if (actp != NULL)
10320 		ipsec_actvec_free(actp, nact);
10321 	if (pin4 != NULL)
10322 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10323 	if (pout4 != NULL)
10324 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10325 	if (pin6 != NULL)
10326 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10327 	if (pout6 != NULL)
10328 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10329 	return (ENOMEM);
10330 }
10331 
10332 /*
10333  * Only for options that pass in an IP addr. Currently only V4 options
10334  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10335  * So this function assumes level is IPPROTO_IP
10336  */
10337 int
10338 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10339     mblk_t *first_mp)
10340 {
10341 	ipif_t *ipif = NULL;
10342 	int error;
10343 	ill_t *ill;
10344 	int zoneid;
10345 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10346 
10347 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10348 
10349 	if (addr != INADDR_ANY || checkonly) {
10350 		ASSERT(connp != NULL);
10351 		zoneid = IPCL_ZONEID(connp);
10352 		if (option == IP_NEXTHOP) {
10353 			ipif = ipif_lookup_onlink_addr(addr,
10354 			    connp->conn_zoneid, ipst);
10355 		} else {
10356 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10357 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10358 			    &error, ipst);
10359 		}
10360 		if (ipif == NULL) {
10361 			if (error == EINPROGRESS)
10362 				return (error);
10363 			if ((option == IP_MULTICAST_IF) ||
10364 			    (option == IP_NEXTHOP))
10365 				return (EHOSTUNREACH);
10366 			else
10367 				return (EINVAL);
10368 		} else if (checkonly) {
10369 			if (option == IP_MULTICAST_IF) {
10370 				ill = ipif->ipif_ill;
10371 				/* not supported by the virtual network iface */
10372 				if (IS_VNI(ill)) {
10373 					ipif_refrele(ipif);
10374 					return (EINVAL);
10375 				}
10376 			}
10377 			ipif_refrele(ipif);
10378 			return (0);
10379 		}
10380 		ill = ipif->ipif_ill;
10381 		mutex_enter(&connp->conn_lock);
10382 		mutex_enter(&ill->ill_lock);
10383 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10384 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10385 			mutex_exit(&ill->ill_lock);
10386 			mutex_exit(&connp->conn_lock);
10387 			ipif_refrele(ipif);
10388 			return (option == IP_MULTICAST_IF ?
10389 			    EHOSTUNREACH : EINVAL);
10390 		}
10391 	} else {
10392 		mutex_enter(&connp->conn_lock);
10393 	}
10394 
10395 	/* None of the options below are supported on the VNI */
10396 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10397 		mutex_exit(&ill->ill_lock);
10398 		mutex_exit(&connp->conn_lock);
10399 		ipif_refrele(ipif);
10400 		return (EINVAL);
10401 	}
10402 
10403 	switch (option) {
10404 	case IP_MULTICAST_IF:
10405 		connp->conn_multicast_ipif = ipif;
10406 		break;
10407 	case IP_NEXTHOP:
10408 		connp->conn_nexthop_v4 = addr;
10409 		connp->conn_nexthop_set = B_TRUE;
10410 		break;
10411 	}
10412 
10413 	if (ipif != NULL) {
10414 		mutex_exit(&ill->ill_lock);
10415 		mutex_exit(&connp->conn_lock);
10416 		ipif_refrele(ipif);
10417 		return (0);
10418 	}
10419 	mutex_exit(&connp->conn_lock);
10420 	/* We succeded in cleared the option */
10421 	return (0);
10422 }
10423 
10424 /*
10425  * For options that pass in an ifindex specifying the ill. V6 options always
10426  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10427  */
10428 int
10429 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10430     int level, int option, mblk_t *first_mp)
10431 {
10432 	ill_t *ill = NULL;
10433 	int error = 0;
10434 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10435 
10436 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10437 	if (ifindex != 0) {
10438 		ASSERT(connp != NULL);
10439 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10440 		    first_mp, ip_restart_optmgmt, &error, ipst);
10441 		if (ill != NULL) {
10442 			if (checkonly) {
10443 				/* not supported by the virtual network iface */
10444 				if (IS_VNI(ill)) {
10445 					ill_refrele(ill);
10446 					return (EINVAL);
10447 				}
10448 				ill_refrele(ill);
10449 				return (0);
10450 			}
10451 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10452 			    0, NULL)) {
10453 				ill_refrele(ill);
10454 				ill = NULL;
10455 				mutex_enter(&connp->conn_lock);
10456 				goto setit;
10457 			}
10458 			mutex_enter(&connp->conn_lock);
10459 			mutex_enter(&ill->ill_lock);
10460 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10461 				mutex_exit(&ill->ill_lock);
10462 				mutex_exit(&connp->conn_lock);
10463 				ill_refrele(ill);
10464 				ill = NULL;
10465 				mutex_enter(&connp->conn_lock);
10466 			}
10467 			goto setit;
10468 		} else if (error == EINPROGRESS) {
10469 			return (error);
10470 		} else {
10471 			error = 0;
10472 		}
10473 	}
10474 	mutex_enter(&connp->conn_lock);
10475 setit:
10476 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10477 
10478 	/*
10479 	 * The options below assume that the ILL (if any) transmits and/or
10480 	 * receives traffic. Neither of which is true for the virtual network
10481 	 * interface, so fail setting these on a VNI.
10482 	 */
10483 	if (IS_VNI(ill)) {
10484 		ASSERT(ill != NULL);
10485 		mutex_exit(&ill->ill_lock);
10486 		mutex_exit(&connp->conn_lock);
10487 		ill_refrele(ill);
10488 		return (EINVAL);
10489 	}
10490 
10491 	if (level == IPPROTO_IP) {
10492 		switch (option) {
10493 		case IP_BOUND_IF:
10494 			connp->conn_incoming_ill = ill;
10495 			connp->conn_outgoing_ill = ill;
10496 			break;
10497 
10498 		case IP_MULTICAST_IF:
10499 			/*
10500 			 * This option is an internal special. The socket
10501 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10502 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10503 			 * specifies an ifindex and we try first on V6 ill's.
10504 			 * If we don't find one, we they try using on v4 ill's
10505 			 * intenally and we come here.
10506 			 */
10507 			if (!checkonly && ill != NULL) {
10508 				ipif_t	*ipif;
10509 				ipif = ill->ill_ipif;
10510 
10511 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10512 					mutex_exit(&ill->ill_lock);
10513 					mutex_exit(&connp->conn_lock);
10514 					ill_refrele(ill);
10515 					ill = NULL;
10516 					mutex_enter(&connp->conn_lock);
10517 				} else {
10518 					connp->conn_multicast_ipif = ipif;
10519 				}
10520 			}
10521 			break;
10522 
10523 		case IP_DHCPINIT_IF:
10524 			if (connp->conn_dhcpinit_ill != NULL) {
10525 				/*
10526 				 * We've locked the conn so conn_cleanup_ill()
10527 				 * cannot clear conn_dhcpinit_ill -- so it's
10528 				 * safe to access the ill.
10529 				 */
10530 				ill_t *oill = connp->conn_dhcpinit_ill;
10531 
10532 				ASSERT(oill->ill_dhcpinit != 0);
10533 				atomic_dec_32(&oill->ill_dhcpinit);
10534 				connp->conn_dhcpinit_ill = NULL;
10535 			}
10536 
10537 			if (ill != NULL) {
10538 				connp->conn_dhcpinit_ill = ill;
10539 				atomic_inc_32(&ill->ill_dhcpinit);
10540 			}
10541 			break;
10542 		}
10543 	} else {
10544 		switch (option) {
10545 		case IPV6_BOUND_IF:
10546 			connp->conn_incoming_ill = ill;
10547 			connp->conn_outgoing_ill = ill;
10548 			break;
10549 
10550 		case IPV6_MULTICAST_IF:
10551 			/*
10552 			 * Set conn_multicast_ill to be the IPv6 ill.
10553 			 * Set conn_multicast_ipif to be an IPv4 ipif
10554 			 * for ifindex to make IPv4 mapped addresses
10555 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10556 			 * Even if no IPv6 ill exists for the ifindex
10557 			 * we need to check for an IPv4 ifindex in order
10558 			 * for this to work with mapped addresses. In that
10559 			 * case only set conn_multicast_ipif.
10560 			 */
10561 			if (!checkonly) {
10562 				if (ifindex == 0) {
10563 					connp->conn_multicast_ill = NULL;
10564 					connp->conn_multicast_ipif = NULL;
10565 				} else if (ill != NULL) {
10566 					connp->conn_multicast_ill = ill;
10567 				}
10568 			}
10569 			break;
10570 		}
10571 	}
10572 
10573 	if (ill != NULL) {
10574 		mutex_exit(&ill->ill_lock);
10575 		mutex_exit(&connp->conn_lock);
10576 		ill_refrele(ill);
10577 		return (0);
10578 	}
10579 	mutex_exit(&connp->conn_lock);
10580 	/*
10581 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10582 	 * locate the ill and could not set the option (ifindex != 0)
10583 	 */
10584 	return (ifindex == 0 ? 0 : EINVAL);
10585 }
10586 
10587 /* This routine sets socket options. */
10588 /* ARGSUSED */
10589 int
10590 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10591     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10592     void *dummy, cred_t *cr, mblk_t *first_mp)
10593 {
10594 	int		*i1 = (int *)invalp;
10595 	conn_t		*connp = Q_TO_CONN(q);
10596 	int		error = 0;
10597 	boolean_t	checkonly;
10598 	ire_t		*ire;
10599 	boolean_t	found;
10600 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10601 
10602 	switch (optset_context) {
10603 
10604 	case SETFN_OPTCOM_CHECKONLY:
10605 		checkonly = B_TRUE;
10606 		/*
10607 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10608 		 * inlen != 0 implies value supplied and
10609 		 * 	we have to "pretend" to set it.
10610 		 * inlen == 0 implies that there is no
10611 		 * 	value part in T_CHECK request and just validation
10612 		 * done elsewhere should be enough, we just return here.
10613 		 */
10614 		if (inlen == 0) {
10615 			*outlenp = 0;
10616 			return (0);
10617 		}
10618 		break;
10619 	case SETFN_OPTCOM_NEGOTIATE:
10620 	case SETFN_UD_NEGOTIATE:
10621 	case SETFN_CONN_NEGOTIATE:
10622 		checkonly = B_FALSE;
10623 		break;
10624 	default:
10625 		/*
10626 		 * We should never get here
10627 		 */
10628 		*outlenp = 0;
10629 		return (EINVAL);
10630 	}
10631 
10632 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10633 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10634 
10635 	/*
10636 	 * For fixed length options, no sanity check
10637 	 * of passed in length is done. It is assumed *_optcom_req()
10638 	 * routines do the right thing.
10639 	 */
10640 
10641 	switch (level) {
10642 	case SOL_SOCKET:
10643 		/*
10644 		 * conn_lock protects the bitfields, and is used to
10645 		 * set the fields atomically.
10646 		 */
10647 		switch (name) {
10648 		case SO_BROADCAST:
10649 			if (!checkonly) {
10650 				/* TODO: use value someplace? */
10651 				mutex_enter(&connp->conn_lock);
10652 				connp->conn_broadcast = *i1 ? 1 : 0;
10653 				mutex_exit(&connp->conn_lock);
10654 			}
10655 			break;	/* goto sizeof (int) option return */
10656 		case SO_USELOOPBACK:
10657 			if (!checkonly) {
10658 				/* TODO: use value someplace? */
10659 				mutex_enter(&connp->conn_lock);
10660 				connp->conn_loopback = *i1 ? 1 : 0;
10661 				mutex_exit(&connp->conn_lock);
10662 			}
10663 			break;	/* goto sizeof (int) option return */
10664 		case SO_DONTROUTE:
10665 			if (!checkonly) {
10666 				mutex_enter(&connp->conn_lock);
10667 				connp->conn_dontroute = *i1 ? 1 : 0;
10668 				mutex_exit(&connp->conn_lock);
10669 			}
10670 			break;	/* goto sizeof (int) option return */
10671 		case SO_REUSEADDR:
10672 			if (!checkonly) {
10673 				mutex_enter(&connp->conn_lock);
10674 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10675 				mutex_exit(&connp->conn_lock);
10676 			}
10677 			break;	/* goto sizeof (int) option return */
10678 		case SO_PROTOTYPE:
10679 			if (!checkonly) {
10680 				mutex_enter(&connp->conn_lock);
10681 				connp->conn_proto = *i1;
10682 				mutex_exit(&connp->conn_lock);
10683 			}
10684 			break;	/* goto sizeof (int) option return */
10685 		case SO_ALLZONES:
10686 			if (!checkonly) {
10687 				mutex_enter(&connp->conn_lock);
10688 				if (IPCL_IS_BOUND(connp)) {
10689 					mutex_exit(&connp->conn_lock);
10690 					return (EINVAL);
10691 				}
10692 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10693 				mutex_exit(&connp->conn_lock);
10694 			}
10695 			break;	/* goto sizeof (int) option return */
10696 		case SO_ANON_MLP:
10697 			if (!checkonly) {
10698 				mutex_enter(&connp->conn_lock);
10699 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10700 				mutex_exit(&connp->conn_lock);
10701 			}
10702 			break;	/* goto sizeof (int) option return */
10703 		case SO_MAC_EXEMPT:
10704 			if (secpolicy_net_mac_aware(cr) != 0 ||
10705 			    IPCL_IS_BOUND(connp))
10706 				return (EACCES);
10707 			if (!checkonly) {
10708 				mutex_enter(&connp->conn_lock);
10709 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10710 				mutex_exit(&connp->conn_lock);
10711 			}
10712 			break;	/* goto sizeof (int) option return */
10713 		default:
10714 			/*
10715 			 * "soft" error (negative)
10716 			 * option not handled at this level
10717 			 * Note: Do not modify *outlenp
10718 			 */
10719 			return (-EINVAL);
10720 		}
10721 		break;
10722 	case IPPROTO_IP:
10723 		switch (name) {
10724 		case IP_NEXTHOP:
10725 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10726 				return (EPERM);
10727 			/* FALLTHRU */
10728 		case IP_MULTICAST_IF: {
10729 			ipaddr_t addr = *i1;
10730 
10731 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10732 			    first_mp);
10733 			if (error != 0)
10734 				return (error);
10735 			break;	/* goto sizeof (int) option return */
10736 		}
10737 
10738 		case IP_MULTICAST_TTL:
10739 			/* Recorded in transport above IP */
10740 			*outvalp = *invalp;
10741 			*outlenp = sizeof (uchar_t);
10742 			return (0);
10743 		case IP_MULTICAST_LOOP:
10744 			if (!checkonly) {
10745 				mutex_enter(&connp->conn_lock);
10746 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10747 				mutex_exit(&connp->conn_lock);
10748 			}
10749 			*outvalp = *invalp;
10750 			*outlenp = sizeof (uchar_t);
10751 			return (0);
10752 		case IP_ADD_MEMBERSHIP:
10753 		case MCAST_JOIN_GROUP:
10754 		case IP_DROP_MEMBERSHIP:
10755 		case MCAST_LEAVE_GROUP: {
10756 			struct ip_mreq *mreqp;
10757 			struct group_req *greqp;
10758 			ire_t *ire;
10759 			boolean_t done = B_FALSE;
10760 			ipaddr_t group, ifaddr;
10761 			struct sockaddr_in *sin;
10762 			uint32_t *ifindexp;
10763 			boolean_t mcast_opt = B_TRUE;
10764 			mcast_record_t fmode;
10765 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10766 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10767 
10768 			switch (name) {
10769 			case IP_ADD_MEMBERSHIP:
10770 				mcast_opt = B_FALSE;
10771 				/* FALLTHRU */
10772 			case MCAST_JOIN_GROUP:
10773 				fmode = MODE_IS_EXCLUDE;
10774 				optfn = ip_opt_add_group;
10775 				break;
10776 
10777 			case IP_DROP_MEMBERSHIP:
10778 				mcast_opt = B_FALSE;
10779 				/* FALLTHRU */
10780 			case MCAST_LEAVE_GROUP:
10781 				fmode = MODE_IS_INCLUDE;
10782 				optfn = ip_opt_delete_group;
10783 				break;
10784 			}
10785 
10786 			if (mcast_opt) {
10787 				greqp = (struct group_req *)i1;
10788 				sin = (struct sockaddr_in *)&greqp->gr_group;
10789 				if (sin->sin_family != AF_INET) {
10790 					*outlenp = 0;
10791 					return (ENOPROTOOPT);
10792 				}
10793 				group = (ipaddr_t)sin->sin_addr.s_addr;
10794 				ifaddr = INADDR_ANY;
10795 				ifindexp = &greqp->gr_interface;
10796 			} else {
10797 				mreqp = (struct ip_mreq *)i1;
10798 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10799 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10800 				ifindexp = NULL;
10801 			}
10802 
10803 			/*
10804 			 * In the multirouting case, we need to replicate
10805 			 * the request on all interfaces that will take part
10806 			 * in replication.  We do so because multirouting is
10807 			 * reflective, thus we will probably receive multi-
10808 			 * casts on those interfaces.
10809 			 * The ip_multirt_apply_membership() succeeds if the
10810 			 * operation succeeds on at least one interface.
10811 			 */
10812 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10813 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10814 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10815 			if (ire != NULL) {
10816 				if (ire->ire_flags & RTF_MULTIRT) {
10817 					error = ip_multirt_apply_membership(
10818 					    optfn, ire, connp, checkonly, group,
10819 					    fmode, INADDR_ANY, first_mp);
10820 					done = B_TRUE;
10821 				}
10822 				ire_refrele(ire);
10823 			}
10824 			if (!done) {
10825 				error = optfn(connp, checkonly, group, ifaddr,
10826 				    ifindexp, fmode, INADDR_ANY, first_mp);
10827 			}
10828 			if (error) {
10829 				/*
10830 				 * EINPROGRESS is a soft error, needs retry
10831 				 * so don't make *outlenp zero.
10832 				 */
10833 				if (error != EINPROGRESS)
10834 					*outlenp = 0;
10835 				return (error);
10836 			}
10837 			/* OK return - copy input buffer into output buffer */
10838 			if (invalp != outvalp) {
10839 				/* don't trust bcopy for identical src/dst */
10840 				bcopy(invalp, outvalp, inlen);
10841 			}
10842 			*outlenp = inlen;
10843 			return (0);
10844 		}
10845 		case IP_BLOCK_SOURCE:
10846 		case IP_UNBLOCK_SOURCE:
10847 		case IP_ADD_SOURCE_MEMBERSHIP:
10848 		case IP_DROP_SOURCE_MEMBERSHIP:
10849 		case MCAST_BLOCK_SOURCE:
10850 		case MCAST_UNBLOCK_SOURCE:
10851 		case MCAST_JOIN_SOURCE_GROUP:
10852 		case MCAST_LEAVE_SOURCE_GROUP: {
10853 			struct ip_mreq_source *imreqp;
10854 			struct group_source_req *gsreqp;
10855 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10856 			uint32_t ifindex = 0;
10857 			mcast_record_t fmode;
10858 			struct sockaddr_in *sin;
10859 			ire_t *ire;
10860 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10861 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10862 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10863 
10864 			switch (name) {
10865 			case IP_BLOCK_SOURCE:
10866 				mcast_opt = B_FALSE;
10867 				/* FALLTHRU */
10868 			case MCAST_BLOCK_SOURCE:
10869 				fmode = MODE_IS_EXCLUDE;
10870 				optfn = ip_opt_add_group;
10871 				break;
10872 
10873 			case IP_UNBLOCK_SOURCE:
10874 				mcast_opt = B_FALSE;
10875 				/* FALLTHRU */
10876 			case MCAST_UNBLOCK_SOURCE:
10877 				fmode = MODE_IS_EXCLUDE;
10878 				optfn = ip_opt_delete_group;
10879 				break;
10880 
10881 			case IP_ADD_SOURCE_MEMBERSHIP:
10882 				mcast_opt = B_FALSE;
10883 				/* FALLTHRU */
10884 			case MCAST_JOIN_SOURCE_GROUP:
10885 				fmode = MODE_IS_INCLUDE;
10886 				optfn = ip_opt_add_group;
10887 				break;
10888 
10889 			case IP_DROP_SOURCE_MEMBERSHIP:
10890 				mcast_opt = B_FALSE;
10891 				/* FALLTHRU */
10892 			case MCAST_LEAVE_SOURCE_GROUP:
10893 				fmode = MODE_IS_INCLUDE;
10894 				optfn = ip_opt_delete_group;
10895 				break;
10896 			}
10897 
10898 			if (mcast_opt) {
10899 				gsreqp = (struct group_source_req *)i1;
10900 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10901 					*outlenp = 0;
10902 					return (ENOPROTOOPT);
10903 				}
10904 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10905 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10906 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10907 				src = (ipaddr_t)sin->sin_addr.s_addr;
10908 				ifindex = gsreqp->gsr_interface;
10909 			} else {
10910 				imreqp = (struct ip_mreq_source *)i1;
10911 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10912 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10913 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10914 			}
10915 
10916 			/*
10917 			 * In the multirouting case, we need to replicate
10918 			 * the request as noted in the mcast cases above.
10919 			 */
10920 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10921 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10922 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10923 			if (ire != NULL) {
10924 				if (ire->ire_flags & RTF_MULTIRT) {
10925 					error = ip_multirt_apply_membership(
10926 					    optfn, ire, connp, checkonly, grp,
10927 					    fmode, src, first_mp);
10928 					done = B_TRUE;
10929 				}
10930 				ire_refrele(ire);
10931 			}
10932 			if (!done) {
10933 				error = optfn(connp, checkonly, grp, ifaddr,
10934 				    &ifindex, fmode, src, first_mp);
10935 			}
10936 			if (error != 0) {
10937 				/*
10938 				 * EINPROGRESS is a soft error, needs retry
10939 				 * so don't make *outlenp zero.
10940 				 */
10941 				if (error != EINPROGRESS)
10942 					*outlenp = 0;
10943 				return (error);
10944 			}
10945 			/* OK return - copy input buffer into output buffer */
10946 			if (invalp != outvalp) {
10947 				bcopy(invalp, outvalp, inlen);
10948 			}
10949 			*outlenp = inlen;
10950 			return (0);
10951 		}
10952 		case IP_SEC_OPT:
10953 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10954 			if (error != 0) {
10955 				*outlenp = 0;
10956 				return (error);
10957 			}
10958 			break;
10959 		case IP_HDRINCL:
10960 		case IP_OPTIONS:
10961 		case T_IP_OPTIONS:
10962 		case IP_TOS:
10963 		case T_IP_TOS:
10964 		case IP_TTL:
10965 		case IP_RECVDSTADDR:
10966 		case IP_RECVOPTS:
10967 			/* OK return - copy input buffer into output buffer */
10968 			if (invalp != outvalp) {
10969 				/* don't trust bcopy for identical src/dst */
10970 				bcopy(invalp, outvalp, inlen);
10971 			}
10972 			*outlenp = inlen;
10973 			return (0);
10974 		case IP_RECVIF:
10975 			/* Retrieve the inbound interface index */
10976 			if (!checkonly) {
10977 				mutex_enter(&connp->conn_lock);
10978 				connp->conn_recvif = *i1 ? 1 : 0;
10979 				mutex_exit(&connp->conn_lock);
10980 			}
10981 			break;	/* goto sizeof (int) option return */
10982 		case IP_RECVPKTINFO:
10983 			if (!checkonly) {
10984 				mutex_enter(&connp->conn_lock);
10985 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10986 				mutex_exit(&connp->conn_lock);
10987 			}
10988 			break;	/* goto sizeof (int) option return */
10989 		case IP_RECVSLLA:
10990 			/* Retrieve the source link layer address */
10991 			if (!checkonly) {
10992 				mutex_enter(&connp->conn_lock);
10993 				connp->conn_recvslla = *i1 ? 1 : 0;
10994 				mutex_exit(&connp->conn_lock);
10995 			}
10996 			break;	/* goto sizeof (int) option return */
10997 		case MRT_INIT:
10998 		case MRT_DONE:
10999 		case MRT_ADD_VIF:
11000 		case MRT_DEL_VIF:
11001 		case MRT_ADD_MFC:
11002 		case MRT_DEL_MFC:
11003 		case MRT_ASSERT:
11004 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11005 				*outlenp = 0;
11006 				return (error);
11007 			}
11008 			error = ip_mrouter_set((int)name, q, checkonly,
11009 			    (uchar_t *)invalp, inlen, first_mp);
11010 			if (error) {
11011 				*outlenp = 0;
11012 				return (error);
11013 			}
11014 			/* OK return - copy input buffer into output buffer */
11015 			if (invalp != outvalp) {
11016 				/* don't trust bcopy for identical src/dst */
11017 				bcopy(invalp, outvalp, inlen);
11018 			}
11019 			*outlenp = inlen;
11020 			return (0);
11021 		case IP_BOUND_IF:
11022 		case IP_DHCPINIT_IF:
11023 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11024 			    level, name, first_mp);
11025 			if (error != 0)
11026 				return (error);
11027 			break; 		/* goto sizeof (int) option return */
11028 
11029 		case IP_UNSPEC_SRC:
11030 			/* Allow sending with a zero source address */
11031 			if (!checkonly) {
11032 				mutex_enter(&connp->conn_lock);
11033 				connp->conn_unspec_src = *i1 ? 1 : 0;
11034 				mutex_exit(&connp->conn_lock);
11035 			}
11036 			break;	/* goto sizeof (int) option return */
11037 		default:
11038 			/*
11039 			 * "soft" error (negative)
11040 			 * option not handled at this level
11041 			 * Note: Do not modify *outlenp
11042 			 */
11043 			return (-EINVAL);
11044 		}
11045 		break;
11046 	case IPPROTO_IPV6:
11047 		switch (name) {
11048 		case IPV6_BOUND_IF:
11049 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11050 			    level, name, first_mp);
11051 			if (error != 0)
11052 				return (error);
11053 			break; 		/* goto sizeof (int) option return */
11054 
11055 		case IPV6_MULTICAST_IF:
11056 			/*
11057 			 * The only possible errors are EINPROGRESS and
11058 			 * EINVAL. EINPROGRESS will be restarted and is not
11059 			 * a hard error. We call this option on both V4 and V6
11060 			 * If both return EINVAL, then this call returns
11061 			 * EINVAL. If at least one of them succeeds we
11062 			 * return success.
11063 			 */
11064 			found = B_FALSE;
11065 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11066 			    level, name, first_mp);
11067 			if (error == EINPROGRESS)
11068 				return (error);
11069 			if (error == 0)
11070 				found = B_TRUE;
11071 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11072 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11073 			if (error == 0)
11074 				found = B_TRUE;
11075 			if (!found)
11076 				return (error);
11077 			break; 		/* goto sizeof (int) option return */
11078 
11079 		case IPV6_MULTICAST_HOPS:
11080 			/* Recorded in transport above IP */
11081 			break;	/* goto sizeof (int) option return */
11082 		case IPV6_MULTICAST_LOOP:
11083 			if (!checkonly) {
11084 				mutex_enter(&connp->conn_lock);
11085 				connp->conn_multicast_loop = *i1;
11086 				mutex_exit(&connp->conn_lock);
11087 			}
11088 			break;	/* goto sizeof (int) option return */
11089 		case IPV6_JOIN_GROUP:
11090 		case MCAST_JOIN_GROUP:
11091 		case IPV6_LEAVE_GROUP:
11092 		case MCAST_LEAVE_GROUP: {
11093 			struct ipv6_mreq *ip_mreqp;
11094 			struct group_req *greqp;
11095 			ire_t *ire;
11096 			boolean_t done = B_FALSE;
11097 			in6_addr_t groupv6;
11098 			uint32_t ifindex;
11099 			boolean_t mcast_opt = B_TRUE;
11100 			mcast_record_t fmode;
11101 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11102 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11103 
11104 			switch (name) {
11105 			case IPV6_JOIN_GROUP:
11106 				mcast_opt = B_FALSE;
11107 				/* FALLTHRU */
11108 			case MCAST_JOIN_GROUP:
11109 				fmode = MODE_IS_EXCLUDE;
11110 				optfn = ip_opt_add_group_v6;
11111 				break;
11112 
11113 			case IPV6_LEAVE_GROUP:
11114 				mcast_opt = B_FALSE;
11115 				/* FALLTHRU */
11116 			case MCAST_LEAVE_GROUP:
11117 				fmode = MODE_IS_INCLUDE;
11118 				optfn = ip_opt_delete_group_v6;
11119 				break;
11120 			}
11121 
11122 			if (mcast_opt) {
11123 				struct sockaddr_in *sin;
11124 				struct sockaddr_in6 *sin6;
11125 				greqp = (struct group_req *)i1;
11126 				if (greqp->gr_group.ss_family == AF_INET) {
11127 					sin = (struct sockaddr_in *)
11128 					    &(greqp->gr_group);
11129 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11130 					    &groupv6);
11131 				} else {
11132 					sin6 = (struct sockaddr_in6 *)
11133 					    &(greqp->gr_group);
11134 					groupv6 = sin6->sin6_addr;
11135 				}
11136 				ifindex = greqp->gr_interface;
11137 			} else {
11138 				ip_mreqp = (struct ipv6_mreq *)i1;
11139 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11140 				ifindex = ip_mreqp->ipv6mr_interface;
11141 			}
11142 			/*
11143 			 * In the multirouting case, we need to replicate
11144 			 * the request on all interfaces that will take part
11145 			 * in replication.  We do so because multirouting is
11146 			 * reflective, thus we will probably receive multi-
11147 			 * casts on those interfaces.
11148 			 * The ip_multirt_apply_membership_v6() succeeds if
11149 			 * the operation succeeds on at least one interface.
11150 			 */
11151 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11152 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11153 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11154 			if (ire != NULL) {
11155 				if (ire->ire_flags & RTF_MULTIRT) {
11156 					error = ip_multirt_apply_membership_v6(
11157 					    optfn, ire, connp, checkonly,
11158 					    &groupv6, fmode, &ipv6_all_zeros,
11159 					    first_mp);
11160 					done = B_TRUE;
11161 				}
11162 				ire_refrele(ire);
11163 			}
11164 			if (!done) {
11165 				error = optfn(connp, checkonly, &groupv6,
11166 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11167 			}
11168 			if (error) {
11169 				/*
11170 				 * EINPROGRESS is a soft error, needs retry
11171 				 * so don't make *outlenp zero.
11172 				 */
11173 				if (error != EINPROGRESS)
11174 					*outlenp = 0;
11175 				return (error);
11176 			}
11177 			/* OK return - copy input buffer into output buffer */
11178 			if (invalp != outvalp) {
11179 				/* don't trust bcopy for identical src/dst */
11180 				bcopy(invalp, outvalp, inlen);
11181 			}
11182 			*outlenp = inlen;
11183 			return (0);
11184 		}
11185 		case MCAST_BLOCK_SOURCE:
11186 		case MCAST_UNBLOCK_SOURCE:
11187 		case MCAST_JOIN_SOURCE_GROUP:
11188 		case MCAST_LEAVE_SOURCE_GROUP: {
11189 			struct group_source_req *gsreqp;
11190 			in6_addr_t v6grp, v6src;
11191 			uint32_t ifindex;
11192 			mcast_record_t fmode;
11193 			ire_t *ire;
11194 			boolean_t done = B_FALSE;
11195 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11196 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11197 
11198 			switch (name) {
11199 			case MCAST_BLOCK_SOURCE:
11200 				fmode = MODE_IS_EXCLUDE;
11201 				optfn = ip_opt_add_group_v6;
11202 				break;
11203 			case MCAST_UNBLOCK_SOURCE:
11204 				fmode = MODE_IS_EXCLUDE;
11205 				optfn = ip_opt_delete_group_v6;
11206 				break;
11207 			case MCAST_JOIN_SOURCE_GROUP:
11208 				fmode = MODE_IS_INCLUDE;
11209 				optfn = ip_opt_add_group_v6;
11210 				break;
11211 			case MCAST_LEAVE_SOURCE_GROUP:
11212 				fmode = MODE_IS_INCLUDE;
11213 				optfn = ip_opt_delete_group_v6;
11214 				break;
11215 			}
11216 
11217 			gsreqp = (struct group_source_req *)i1;
11218 			ifindex = gsreqp->gsr_interface;
11219 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11220 				struct sockaddr_in *s;
11221 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11222 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11223 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11224 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11225 			} else {
11226 				struct sockaddr_in6 *s6;
11227 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11228 				v6grp = s6->sin6_addr;
11229 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11230 				v6src = s6->sin6_addr;
11231 			}
11232 
11233 			/*
11234 			 * In the multirouting case, we need to replicate
11235 			 * the request as noted in the mcast cases above.
11236 			 */
11237 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11238 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11239 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11240 			if (ire != NULL) {
11241 				if (ire->ire_flags & RTF_MULTIRT) {
11242 					error = ip_multirt_apply_membership_v6(
11243 					    optfn, ire, connp, checkonly,
11244 					    &v6grp, fmode, &v6src, first_mp);
11245 					done = B_TRUE;
11246 				}
11247 				ire_refrele(ire);
11248 			}
11249 			if (!done) {
11250 				error = optfn(connp, checkonly, &v6grp,
11251 				    ifindex, fmode, &v6src, first_mp);
11252 			}
11253 			if (error != 0) {
11254 				/*
11255 				 * EINPROGRESS is a soft error, needs retry
11256 				 * so don't make *outlenp zero.
11257 				 */
11258 				if (error != EINPROGRESS)
11259 					*outlenp = 0;
11260 				return (error);
11261 			}
11262 			/* OK return - copy input buffer into output buffer */
11263 			if (invalp != outvalp) {
11264 				bcopy(invalp, outvalp, inlen);
11265 			}
11266 			*outlenp = inlen;
11267 			return (0);
11268 		}
11269 		case IPV6_UNICAST_HOPS:
11270 			/* Recorded in transport above IP */
11271 			break;	/* goto sizeof (int) option return */
11272 		case IPV6_UNSPEC_SRC:
11273 			/* Allow sending with a zero source address */
11274 			if (!checkonly) {
11275 				mutex_enter(&connp->conn_lock);
11276 				connp->conn_unspec_src = *i1 ? 1 : 0;
11277 				mutex_exit(&connp->conn_lock);
11278 			}
11279 			break;	/* goto sizeof (int) option return */
11280 		case IPV6_RECVPKTINFO:
11281 			if (!checkonly) {
11282 				mutex_enter(&connp->conn_lock);
11283 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11284 				mutex_exit(&connp->conn_lock);
11285 			}
11286 			break;	/* goto sizeof (int) option return */
11287 		case IPV6_RECVTCLASS:
11288 			if (!checkonly) {
11289 				if (*i1 < 0 || *i1 > 1) {
11290 					return (EINVAL);
11291 				}
11292 				mutex_enter(&connp->conn_lock);
11293 				connp->conn_ipv6_recvtclass = *i1;
11294 				mutex_exit(&connp->conn_lock);
11295 			}
11296 			break;
11297 		case IPV6_RECVPATHMTU:
11298 			if (!checkonly) {
11299 				if (*i1 < 0 || *i1 > 1) {
11300 					return (EINVAL);
11301 				}
11302 				mutex_enter(&connp->conn_lock);
11303 				connp->conn_ipv6_recvpathmtu = *i1;
11304 				mutex_exit(&connp->conn_lock);
11305 			}
11306 			break;
11307 		case IPV6_RECVHOPLIMIT:
11308 			if (!checkonly) {
11309 				mutex_enter(&connp->conn_lock);
11310 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11311 				mutex_exit(&connp->conn_lock);
11312 			}
11313 			break;	/* goto sizeof (int) option return */
11314 		case IPV6_RECVHOPOPTS:
11315 			if (!checkonly) {
11316 				mutex_enter(&connp->conn_lock);
11317 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11318 				mutex_exit(&connp->conn_lock);
11319 			}
11320 			break;	/* goto sizeof (int) option return */
11321 		case IPV6_RECVDSTOPTS:
11322 			if (!checkonly) {
11323 				mutex_enter(&connp->conn_lock);
11324 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11325 				mutex_exit(&connp->conn_lock);
11326 			}
11327 			break;	/* goto sizeof (int) option return */
11328 		case IPV6_RECVRTHDR:
11329 			if (!checkonly) {
11330 				mutex_enter(&connp->conn_lock);
11331 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11332 				mutex_exit(&connp->conn_lock);
11333 			}
11334 			break;	/* goto sizeof (int) option return */
11335 		case IPV6_RECVRTHDRDSTOPTS:
11336 			if (!checkonly) {
11337 				mutex_enter(&connp->conn_lock);
11338 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11339 				mutex_exit(&connp->conn_lock);
11340 			}
11341 			break;	/* goto sizeof (int) option return */
11342 		case IPV6_PKTINFO:
11343 			if (inlen == 0)
11344 				return (-EINVAL);	/* clearing option */
11345 			error = ip6_set_pktinfo(cr, connp,
11346 			    (struct in6_pktinfo *)invalp);
11347 			if (error != 0)
11348 				*outlenp = 0;
11349 			else
11350 				*outlenp = inlen;
11351 			return (error);
11352 		case IPV6_NEXTHOP: {
11353 			struct sockaddr_in6 *sin6;
11354 
11355 			/* Verify that the nexthop is reachable */
11356 			if (inlen == 0)
11357 				return (-EINVAL);	/* clearing option */
11358 
11359 			sin6 = (struct sockaddr_in6 *)invalp;
11360 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11361 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11362 			    NULL, MATCH_IRE_DEFAULT, ipst);
11363 
11364 			if (ire == NULL) {
11365 				*outlenp = 0;
11366 				return (EHOSTUNREACH);
11367 			}
11368 			ire_refrele(ire);
11369 			return (-EINVAL);
11370 		}
11371 		case IPV6_SEC_OPT:
11372 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11373 			if (error != 0) {
11374 				*outlenp = 0;
11375 				return (error);
11376 			}
11377 			break;
11378 		case IPV6_SRC_PREFERENCES: {
11379 			/*
11380 			 * This is implemented strictly in the ip module
11381 			 * (here and in tcp_opt_*() to accomodate tcp
11382 			 * sockets).  Modules above ip pass this option
11383 			 * down here since ip is the only one that needs to
11384 			 * be aware of source address preferences.
11385 			 *
11386 			 * This socket option only affects connected
11387 			 * sockets that haven't already bound to a specific
11388 			 * IPv6 address.  In other words, sockets that
11389 			 * don't call bind() with an address other than the
11390 			 * unspecified address and that call connect().
11391 			 * ip_bind_connected_v6() passes these preferences
11392 			 * to the ipif_select_source_v6() function.
11393 			 */
11394 			if (inlen != sizeof (uint32_t))
11395 				return (EINVAL);
11396 			error = ip6_set_src_preferences(connp,
11397 			    *(uint32_t *)invalp);
11398 			if (error != 0) {
11399 				*outlenp = 0;
11400 				return (error);
11401 			} else {
11402 				*outlenp = sizeof (uint32_t);
11403 			}
11404 			break;
11405 		}
11406 		case IPV6_V6ONLY:
11407 			if (*i1 < 0 || *i1 > 1) {
11408 				return (EINVAL);
11409 			}
11410 			mutex_enter(&connp->conn_lock);
11411 			connp->conn_ipv6_v6only = *i1;
11412 			mutex_exit(&connp->conn_lock);
11413 			break;
11414 		default:
11415 			return (-EINVAL);
11416 		}
11417 		break;
11418 	default:
11419 		/*
11420 		 * "soft" error (negative)
11421 		 * option not handled at this level
11422 		 * Note: Do not modify *outlenp
11423 		 */
11424 		return (-EINVAL);
11425 	}
11426 	/*
11427 	 * Common case of return from an option that is sizeof (int)
11428 	 */
11429 	*(int *)outvalp = *i1;
11430 	*outlenp = sizeof (int);
11431 	return (0);
11432 }
11433 
11434 /*
11435  * This routine gets default values of certain options whose default
11436  * values are maintained by protocol specific code
11437  */
11438 /* ARGSUSED */
11439 int
11440 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11441 {
11442 	int *i1 = (int *)ptr;
11443 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11444 
11445 	switch (level) {
11446 	case IPPROTO_IP:
11447 		switch (name) {
11448 		case IP_MULTICAST_TTL:
11449 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11450 			return (sizeof (uchar_t));
11451 		case IP_MULTICAST_LOOP:
11452 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11453 			return (sizeof (uchar_t));
11454 		default:
11455 			return (-1);
11456 		}
11457 	case IPPROTO_IPV6:
11458 		switch (name) {
11459 		case IPV6_UNICAST_HOPS:
11460 			*i1 = ipst->ips_ipv6_def_hops;
11461 			return (sizeof (int));
11462 		case IPV6_MULTICAST_HOPS:
11463 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11464 			return (sizeof (int));
11465 		case IPV6_MULTICAST_LOOP:
11466 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11467 			return (sizeof (int));
11468 		case IPV6_V6ONLY:
11469 			*i1 = 1;
11470 			return (sizeof (int));
11471 		default:
11472 			return (-1);
11473 		}
11474 	default:
11475 		return (-1);
11476 	}
11477 	/* NOTREACHED */
11478 }
11479 
11480 /*
11481  * Given a destination address and a pointer to where to put the information
11482  * this routine fills in the mtuinfo.
11483  */
11484 int
11485 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11486     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11487 {
11488 	ire_t *ire;
11489 	ip_stack_t	*ipst = ns->netstack_ip;
11490 
11491 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11492 		return (-1);
11493 
11494 	bzero(mtuinfo, sizeof (*mtuinfo));
11495 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11496 	mtuinfo->ip6m_addr.sin6_port = port;
11497 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11498 
11499 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11500 	if (ire != NULL) {
11501 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11502 		ire_refrele(ire);
11503 	} else {
11504 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11505 	}
11506 	return (sizeof (struct ip6_mtuinfo));
11507 }
11508 
11509 /*
11510  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11511  * checking of cred and that ip_g_mrouter is set should be done and
11512  * isn't.  This doesn't matter as the error checking is done properly for the
11513  * other MRT options coming in through ip_opt_set.
11514  */
11515 int
11516 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11517 {
11518 	conn_t		*connp = Q_TO_CONN(q);
11519 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11520 
11521 	switch (level) {
11522 	case IPPROTO_IP:
11523 		switch (name) {
11524 		case MRT_VERSION:
11525 		case MRT_ASSERT:
11526 			(void) ip_mrouter_get(name, q, ptr);
11527 			return (sizeof (int));
11528 		case IP_SEC_OPT:
11529 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11530 		case IP_NEXTHOP:
11531 			if (connp->conn_nexthop_set) {
11532 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11533 				return (sizeof (ipaddr_t));
11534 			} else
11535 				return (0);
11536 		case IP_RECVPKTINFO:
11537 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11538 			return (sizeof (int));
11539 		default:
11540 			break;
11541 		}
11542 		break;
11543 	case IPPROTO_IPV6:
11544 		switch (name) {
11545 		case IPV6_SEC_OPT:
11546 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11547 		case IPV6_SRC_PREFERENCES: {
11548 			return (ip6_get_src_preferences(connp,
11549 			    (uint32_t *)ptr));
11550 		}
11551 		case IPV6_V6ONLY:
11552 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11553 			return (sizeof (int));
11554 		case IPV6_PATHMTU:
11555 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11556 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11557 		default:
11558 			break;
11559 		}
11560 		break;
11561 	default:
11562 		break;
11563 	}
11564 	return (-1);
11565 }
11566 /* Named Dispatch routine to get a current value out of our parameter table. */
11567 /* ARGSUSED */
11568 static int
11569 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11570 {
11571 	ipparam_t *ippa = (ipparam_t *)cp;
11572 
11573 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11574 	return (0);
11575 }
11576 
11577 /* ARGSUSED */
11578 static int
11579 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11580 {
11581 
11582 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11583 	return (0);
11584 }
11585 
11586 /*
11587  * Set ip{,6}_forwarding values.  This means walking through all of the
11588  * ill's and toggling their forwarding values.
11589  */
11590 /* ARGSUSED */
11591 static int
11592 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11593 {
11594 	long new_value;
11595 	int *forwarding_value = (int *)cp;
11596 	ill_t *ill;
11597 	boolean_t isv6;
11598 	ill_walk_context_t ctx;
11599 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11600 
11601 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11602 
11603 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11604 	    new_value < 0 || new_value > 1) {
11605 		return (EINVAL);
11606 	}
11607 
11608 	*forwarding_value = new_value;
11609 
11610 	/*
11611 	 * Regardless of the current value of ip_forwarding, set all per-ill
11612 	 * values of ip_forwarding to the value being set.
11613 	 *
11614 	 * Bring all the ill's up to date with the new global value.
11615 	 */
11616 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11617 
11618 	if (isv6)
11619 		ill = ILL_START_WALK_V6(&ctx, ipst);
11620 	else
11621 		ill = ILL_START_WALK_V4(&ctx, ipst);
11622 
11623 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11624 		(void) ill_forward_set(ill, new_value != 0);
11625 
11626 	rw_exit(&ipst->ips_ill_g_lock);
11627 	return (0);
11628 }
11629 
11630 /*
11631  * Walk through the param array specified registering each element with the
11632  * Named Dispatch handler. This is called only during init. So it is ok
11633  * not to acquire any locks
11634  */
11635 static boolean_t
11636 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11637     ipndp_t *ipnd, size_t ipnd_cnt)
11638 {
11639 	for (; ippa_cnt-- > 0; ippa++) {
11640 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11641 			if (!nd_load(ndp, ippa->ip_param_name,
11642 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11643 				nd_free(ndp);
11644 				return (B_FALSE);
11645 			}
11646 		}
11647 	}
11648 
11649 	for (; ipnd_cnt-- > 0; ipnd++) {
11650 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11651 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11652 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11653 			    ipnd->ip_ndp_data)) {
11654 				nd_free(ndp);
11655 				return (B_FALSE);
11656 			}
11657 		}
11658 	}
11659 
11660 	return (B_TRUE);
11661 }
11662 
11663 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11664 /* ARGSUSED */
11665 static int
11666 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11667 {
11668 	long		new_value;
11669 	ipparam_t	*ippa = (ipparam_t *)cp;
11670 
11671 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11672 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11673 		return (EINVAL);
11674 	}
11675 	ippa->ip_param_value = new_value;
11676 	return (0);
11677 }
11678 
11679 /*
11680  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11681  * When an ipf is passed here for the first time, if
11682  * we already have in-order fragments on the queue, we convert from the fast-
11683  * path reassembly scheme to the hard-case scheme.  From then on, additional
11684  * fragments are reassembled here.  We keep track of the start and end offsets
11685  * of each piece, and the number of holes in the chain.  When the hole count
11686  * goes to zero, we are done!
11687  *
11688  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11689  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11690  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11691  * after the call to ip_reassemble().
11692  */
11693 int
11694 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11695     size_t msg_len)
11696 {
11697 	uint_t	end;
11698 	mblk_t	*next_mp;
11699 	mblk_t	*mp1;
11700 	uint_t	offset;
11701 	boolean_t incr_dups = B_TRUE;
11702 	boolean_t offset_zero_seen = B_FALSE;
11703 	boolean_t pkt_boundary_checked = B_FALSE;
11704 
11705 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11706 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11707 
11708 	/* Add in byte count */
11709 	ipf->ipf_count += msg_len;
11710 	if (ipf->ipf_end) {
11711 		/*
11712 		 * We were part way through in-order reassembly, but now there
11713 		 * is a hole.  We walk through messages already queued, and
11714 		 * mark them for hard case reassembly.  We know that up till
11715 		 * now they were in order starting from offset zero.
11716 		 */
11717 		offset = 0;
11718 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11719 			IP_REASS_SET_START(mp1, offset);
11720 			if (offset == 0) {
11721 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11722 				offset = -ipf->ipf_nf_hdr_len;
11723 			}
11724 			offset += mp1->b_wptr - mp1->b_rptr;
11725 			IP_REASS_SET_END(mp1, offset);
11726 		}
11727 		/* One hole at the end. */
11728 		ipf->ipf_hole_cnt = 1;
11729 		/* Brand it as a hard case, forever. */
11730 		ipf->ipf_end = 0;
11731 	}
11732 	/* Walk through all the new pieces. */
11733 	do {
11734 		end = start + (mp->b_wptr - mp->b_rptr);
11735 		/*
11736 		 * If start is 0, decrease 'end' only for the first mblk of
11737 		 * the fragment. Otherwise 'end' can get wrong value in the
11738 		 * second pass of the loop if first mblk is exactly the
11739 		 * size of ipf_nf_hdr_len.
11740 		 */
11741 		if (start == 0 && !offset_zero_seen) {
11742 			/* First segment */
11743 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11744 			end -= ipf->ipf_nf_hdr_len;
11745 			offset_zero_seen = B_TRUE;
11746 		}
11747 		next_mp = mp->b_cont;
11748 		/*
11749 		 * We are checking to see if there is any interesing data
11750 		 * to process.  If there isn't and the mblk isn't the
11751 		 * one which carries the unfragmentable header then we
11752 		 * drop it.  It's possible to have just the unfragmentable
11753 		 * header come through without any data.  That needs to be
11754 		 * saved.
11755 		 *
11756 		 * If the assert at the top of this function holds then the
11757 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11758 		 * is infrequently traveled enough that the test is left in
11759 		 * to protect against future code changes which break that
11760 		 * invariant.
11761 		 */
11762 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11763 			/* Empty.  Blast it. */
11764 			IP_REASS_SET_START(mp, 0);
11765 			IP_REASS_SET_END(mp, 0);
11766 			/*
11767 			 * If the ipf points to the mblk we are about to free,
11768 			 * update ipf to point to the next mblk (or NULL
11769 			 * if none).
11770 			 */
11771 			if (ipf->ipf_mp->b_cont == mp)
11772 				ipf->ipf_mp->b_cont = next_mp;
11773 			freeb(mp);
11774 			continue;
11775 		}
11776 		mp->b_cont = NULL;
11777 		IP_REASS_SET_START(mp, start);
11778 		IP_REASS_SET_END(mp, end);
11779 		if (!ipf->ipf_tail_mp) {
11780 			ipf->ipf_tail_mp = mp;
11781 			ipf->ipf_mp->b_cont = mp;
11782 			if (start == 0 || !more) {
11783 				ipf->ipf_hole_cnt = 1;
11784 				/*
11785 				 * if the first fragment comes in more than one
11786 				 * mblk, this loop will be executed for each
11787 				 * mblk. Need to adjust hole count so exiting
11788 				 * this routine will leave hole count at 1.
11789 				 */
11790 				if (next_mp)
11791 					ipf->ipf_hole_cnt++;
11792 			} else
11793 				ipf->ipf_hole_cnt = 2;
11794 			continue;
11795 		} else if (ipf->ipf_last_frag_seen && !more &&
11796 		    !pkt_boundary_checked) {
11797 			/*
11798 			 * We check datagram boundary only if this fragment
11799 			 * claims to be the last fragment and we have seen a
11800 			 * last fragment in the past too. We do this only
11801 			 * once for a given fragment.
11802 			 *
11803 			 * start cannot be 0 here as fragments with start=0
11804 			 * and MF=0 gets handled as a complete packet. These
11805 			 * fragments should not reach here.
11806 			 */
11807 
11808 			if (start + msgdsize(mp) !=
11809 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11810 				/*
11811 				 * We have two fragments both of which claim
11812 				 * to be the last fragment but gives conflicting
11813 				 * information about the whole datagram size.
11814 				 * Something fishy is going on. Drop the
11815 				 * fragment and free up the reassembly list.
11816 				 */
11817 				return (IP_REASS_FAILED);
11818 			}
11819 
11820 			/*
11821 			 * We shouldn't come to this code block again for this
11822 			 * particular fragment.
11823 			 */
11824 			pkt_boundary_checked = B_TRUE;
11825 		}
11826 
11827 		/* New stuff at or beyond tail? */
11828 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11829 		if (start >= offset) {
11830 			if (ipf->ipf_last_frag_seen) {
11831 				/* current fragment is beyond last fragment */
11832 				return (IP_REASS_FAILED);
11833 			}
11834 			/* Link it on end. */
11835 			ipf->ipf_tail_mp->b_cont = mp;
11836 			ipf->ipf_tail_mp = mp;
11837 			if (more) {
11838 				if (start != offset)
11839 					ipf->ipf_hole_cnt++;
11840 			} else if (start == offset && next_mp == NULL)
11841 					ipf->ipf_hole_cnt--;
11842 			continue;
11843 		}
11844 		mp1 = ipf->ipf_mp->b_cont;
11845 		offset = IP_REASS_START(mp1);
11846 		/* New stuff at the front? */
11847 		if (start < offset) {
11848 			if (start == 0) {
11849 				if (end >= offset) {
11850 					/* Nailed the hole at the begining. */
11851 					ipf->ipf_hole_cnt--;
11852 				}
11853 			} else if (end < offset) {
11854 				/*
11855 				 * A hole, stuff, and a hole where there used
11856 				 * to be just a hole.
11857 				 */
11858 				ipf->ipf_hole_cnt++;
11859 			}
11860 			mp->b_cont = mp1;
11861 			/* Check for overlap. */
11862 			while (end > offset) {
11863 				if (end < IP_REASS_END(mp1)) {
11864 					mp->b_wptr -= end - offset;
11865 					IP_REASS_SET_END(mp, offset);
11866 					BUMP_MIB(ill->ill_ip_mib,
11867 					    ipIfStatsReasmPartDups);
11868 					break;
11869 				}
11870 				/* Did we cover another hole? */
11871 				if ((mp1->b_cont &&
11872 				    IP_REASS_END(mp1) !=
11873 				    IP_REASS_START(mp1->b_cont) &&
11874 				    end >= IP_REASS_START(mp1->b_cont)) ||
11875 				    (!ipf->ipf_last_frag_seen && !more)) {
11876 					ipf->ipf_hole_cnt--;
11877 				}
11878 				/* Clip out mp1. */
11879 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11880 					/*
11881 					 * After clipping out mp1, this guy
11882 					 * is now hanging off the end.
11883 					 */
11884 					ipf->ipf_tail_mp = mp;
11885 				}
11886 				IP_REASS_SET_START(mp1, 0);
11887 				IP_REASS_SET_END(mp1, 0);
11888 				/* Subtract byte count */
11889 				ipf->ipf_count -= mp1->b_datap->db_lim -
11890 				    mp1->b_datap->db_base;
11891 				freeb(mp1);
11892 				BUMP_MIB(ill->ill_ip_mib,
11893 				    ipIfStatsReasmPartDups);
11894 				mp1 = mp->b_cont;
11895 				if (!mp1)
11896 					break;
11897 				offset = IP_REASS_START(mp1);
11898 			}
11899 			ipf->ipf_mp->b_cont = mp;
11900 			continue;
11901 		}
11902 		/*
11903 		 * The new piece starts somewhere between the start of the head
11904 		 * and before the end of the tail.
11905 		 */
11906 		for (; mp1; mp1 = mp1->b_cont) {
11907 			offset = IP_REASS_END(mp1);
11908 			if (start < offset) {
11909 				if (end <= offset) {
11910 					/* Nothing new. */
11911 					IP_REASS_SET_START(mp, 0);
11912 					IP_REASS_SET_END(mp, 0);
11913 					/* Subtract byte count */
11914 					ipf->ipf_count -= mp->b_datap->db_lim -
11915 					    mp->b_datap->db_base;
11916 					if (incr_dups) {
11917 						ipf->ipf_num_dups++;
11918 						incr_dups = B_FALSE;
11919 					}
11920 					freeb(mp);
11921 					BUMP_MIB(ill->ill_ip_mib,
11922 					    ipIfStatsReasmDuplicates);
11923 					break;
11924 				}
11925 				/*
11926 				 * Trim redundant stuff off beginning of new
11927 				 * piece.
11928 				 */
11929 				IP_REASS_SET_START(mp, offset);
11930 				mp->b_rptr += offset - start;
11931 				BUMP_MIB(ill->ill_ip_mib,
11932 				    ipIfStatsReasmPartDups);
11933 				start = offset;
11934 				if (!mp1->b_cont) {
11935 					/*
11936 					 * After trimming, this guy is now
11937 					 * hanging off the end.
11938 					 */
11939 					mp1->b_cont = mp;
11940 					ipf->ipf_tail_mp = mp;
11941 					if (!more) {
11942 						ipf->ipf_hole_cnt--;
11943 					}
11944 					break;
11945 				}
11946 			}
11947 			if (start >= IP_REASS_START(mp1->b_cont))
11948 				continue;
11949 			/* Fill a hole */
11950 			if (start > offset)
11951 				ipf->ipf_hole_cnt++;
11952 			mp->b_cont = mp1->b_cont;
11953 			mp1->b_cont = mp;
11954 			mp1 = mp->b_cont;
11955 			offset = IP_REASS_START(mp1);
11956 			if (end >= offset) {
11957 				ipf->ipf_hole_cnt--;
11958 				/* Check for overlap. */
11959 				while (end > offset) {
11960 					if (end < IP_REASS_END(mp1)) {
11961 						mp->b_wptr -= end - offset;
11962 						IP_REASS_SET_END(mp, offset);
11963 						/*
11964 						 * TODO we might bump
11965 						 * this up twice if there is
11966 						 * overlap at both ends.
11967 						 */
11968 						BUMP_MIB(ill->ill_ip_mib,
11969 						    ipIfStatsReasmPartDups);
11970 						break;
11971 					}
11972 					/* Did we cover another hole? */
11973 					if ((mp1->b_cont &&
11974 					    IP_REASS_END(mp1)
11975 					    != IP_REASS_START(mp1->b_cont) &&
11976 					    end >=
11977 					    IP_REASS_START(mp1->b_cont)) ||
11978 					    (!ipf->ipf_last_frag_seen &&
11979 					    !more)) {
11980 						ipf->ipf_hole_cnt--;
11981 					}
11982 					/* Clip out mp1. */
11983 					if ((mp->b_cont = mp1->b_cont) ==
11984 					    NULL) {
11985 						/*
11986 						 * After clipping out mp1,
11987 						 * this guy is now hanging
11988 						 * off the end.
11989 						 */
11990 						ipf->ipf_tail_mp = mp;
11991 					}
11992 					IP_REASS_SET_START(mp1, 0);
11993 					IP_REASS_SET_END(mp1, 0);
11994 					/* Subtract byte count */
11995 					ipf->ipf_count -=
11996 					    mp1->b_datap->db_lim -
11997 					    mp1->b_datap->db_base;
11998 					freeb(mp1);
11999 					BUMP_MIB(ill->ill_ip_mib,
12000 					    ipIfStatsReasmPartDups);
12001 					mp1 = mp->b_cont;
12002 					if (!mp1)
12003 						break;
12004 					offset = IP_REASS_START(mp1);
12005 				}
12006 			}
12007 			break;
12008 		}
12009 	} while (start = end, mp = next_mp);
12010 
12011 	/* Fragment just processed could be the last one. Remember this fact */
12012 	if (!more)
12013 		ipf->ipf_last_frag_seen = B_TRUE;
12014 
12015 	/* Still got holes? */
12016 	if (ipf->ipf_hole_cnt)
12017 		return (IP_REASS_PARTIAL);
12018 	/* Clean up overloaded fields to avoid upstream disasters. */
12019 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12020 		IP_REASS_SET_START(mp1, 0);
12021 		IP_REASS_SET_END(mp1, 0);
12022 	}
12023 	return (IP_REASS_COMPLETE);
12024 }
12025 
12026 /*
12027  * ipsec processing for the fast path, used for input UDP Packets
12028  * Returns true if ready for passup to UDP.
12029  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12030  * was an ESP-in-UDP packet, etc.).
12031  */
12032 static boolean_t
12033 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12034     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12035 {
12036 	uint32_t	ill_index;
12037 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12038 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12039 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12040 	udp_t		*udp = connp->conn_udp;
12041 
12042 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12043 	/* The ill_index of the incoming ILL */
12044 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12045 
12046 	/* pass packet up to the transport */
12047 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12048 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12049 		    NULL, mctl_present);
12050 		if (*first_mpp == NULL) {
12051 			return (B_FALSE);
12052 		}
12053 	}
12054 
12055 	/* Initiate IPPF processing for fastpath UDP */
12056 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12057 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12058 		if (*mpp == NULL) {
12059 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12060 			    "deferred/dropped during IPPF processing\n"));
12061 			return (B_FALSE);
12062 		}
12063 	}
12064 	/*
12065 	 * Remove 0-spi if it's 0, or move everything behind
12066 	 * the UDP header over it and forward to ESP via
12067 	 * ip_proto_input().
12068 	 */
12069 	if (udp->udp_nat_t_endpoint) {
12070 		if (mctl_present) {
12071 			/* mctl_present *shouldn't* happen. */
12072 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12073 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12074 			    &ipss->ipsec_dropper);
12075 			*first_mpp = NULL;
12076 			return (B_FALSE);
12077 		}
12078 
12079 		/* "ill" is "recv_ill" in actuality. */
12080 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12081 			return (B_FALSE);
12082 
12083 		/* Else continue like a normal UDP packet. */
12084 	}
12085 
12086 	/*
12087 	 * We make the checks as below since we are in the fast path
12088 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12089 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12090 	 */
12091 	if (connp->conn_recvif || connp->conn_recvslla ||
12092 	    connp->conn_ip_recvpktinfo) {
12093 		if (connp->conn_recvif) {
12094 			in_flags = IPF_RECVIF;
12095 		}
12096 		/*
12097 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12098 		 * so the flag passed to ip_add_info is based on IP version
12099 		 * of connp.
12100 		 */
12101 		if (connp->conn_ip_recvpktinfo) {
12102 			if (connp->conn_af_isv6) {
12103 				/*
12104 				 * V6 only needs index
12105 				 */
12106 				in_flags |= IPF_RECVIF;
12107 			} else {
12108 				/*
12109 				 * V4 needs index + matching address.
12110 				 */
12111 				in_flags |= IPF_RECVADDR;
12112 			}
12113 		}
12114 		if (connp->conn_recvslla) {
12115 			in_flags |= IPF_RECVSLLA;
12116 		}
12117 		/*
12118 		 * since in_flags are being set ill will be
12119 		 * referenced in ip_add_info, so it better not
12120 		 * be NULL.
12121 		 */
12122 		/*
12123 		 * the actual data will be contained in b_cont
12124 		 * upon successful return of the following call.
12125 		 * If the call fails then the original mblk is
12126 		 * returned.
12127 		 */
12128 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12129 		    ipst);
12130 	}
12131 
12132 	return (B_TRUE);
12133 }
12134 
12135 /*
12136  * Fragmentation reassembly.  Each ILL has a hash table for
12137  * queuing packets undergoing reassembly for all IPIFs
12138  * associated with the ILL.  The hash is based on the packet
12139  * IP ident field.  The ILL frag hash table was allocated
12140  * as a timer block at the time the ILL was created.  Whenever
12141  * there is anything on the reassembly queue, the timer will
12142  * be running.  Returns B_TRUE if successful else B_FALSE;
12143  * frees mp on failure.
12144  */
12145 static boolean_t
12146 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12147     uint32_t *cksum_val, uint16_t *cksum_flags)
12148 {
12149 	uint32_t	frag_offset_flags;
12150 	mblk_t		*mp = *mpp;
12151 	mblk_t		*t_mp;
12152 	ipaddr_t	dst;
12153 	uint8_t		proto = ipha->ipha_protocol;
12154 	uint32_t	sum_val;
12155 	uint16_t	sum_flags;
12156 	ipf_t		*ipf;
12157 	ipf_t		**ipfp;
12158 	ipfb_t		*ipfb;
12159 	uint16_t	ident;
12160 	uint32_t	offset;
12161 	ipaddr_t	src;
12162 	uint_t		hdr_length;
12163 	uint32_t	end;
12164 	mblk_t		*mp1;
12165 	mblk_t		*tail_mp;
12166 	size_t		count;
12167 	size_t		msg_len;
12168 	uint8_t		ecn_info = 0;
12169 	uint32_t	packet_size;
12170 	boolean_t	pruned = B_FALSE;
12171 	ip_stack_t *ipst = ill->ill_ipst;
12172 
12173 	if (cksum_val != NULL)
12174 		*cksum_val = 0;
12175 	if (cksum_flags != NULL)
12176 		*cksum_flags = 0;
12177 
12178 	/*
12179 	 * Drop the fragmented as early as possible, if
12180 	 * we don't have resource(s) to re-assemble.
12181 	 */
12182 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12183 		freemsg(mp);
12184 		return (B_FALSE);
12185 	}
12186 
12187 	/* Check for fragmentation offset; return if there's none */
12188 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12189 	    (IPH_MF | IPH_OFFSET)) == 0)
12190 		return (B_TRUE);
12191 
12192 	/*
12193 	 * We utilize hardware computed checksum info only for UDP since
12194 	 * IP fragmentation is a normal occurrence for the protocol.  In
12195 	 * addition, checksum offload support for IP fragments carrying
12196 	 * UDP payload is commonly implemented across network adapters.
12197 	 */
12198 	ASSERT(recv_ill != NULL);
12199 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12200 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12201 		mblk_t *mp1 = mp->b_cont;
12202 		int32_t len;
12203 
12204 		/* Record checksum information from the packet */
12205 		sum_val = (uint32_t)DB_CKSUM16(mp);
12206 		sum_flags = DB_CKSUMFLAGS(mp);
12207 
12208 		/* IP payload offset from beginning of mblk */
12209 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12210 
12211 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12212 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12213 		    offset >= DB_CKSUMSTART(mp) &&
12214 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12215 			uint32_t adj;
12216 			/*
12217 			 * Partial checksum has been calculated by hardware
12218 			 * and attached to the packet; in addition, any
12219 			 * prepended extraneous data is even byte aligned.
12220 			 * If any such data exists, we adjust the checksum;
12221 			 * this would also handle any postpended data.
12222 			 */
12223 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12224 			    mp, mp1, len, adj);
12225 
12226 			/* One's complement subtract extraneous checksum */
12227 			if (adj >= sum_val)
12228 				sum_val = ~(adj - sum_val) & 0xFFFF;
12229 			else
12230 				sum_val -= adj;
12231 		}
12232 	} else {
12233 		sum_val = 0;
12234 		sum_flags = 0;
12235 	}
12236 
12237 	/* Clear hardware checksumming flag */
12238 	DB_CKSUMFLAGS(mp) = 0;
12239 
12240 	ident = ipha->ipha_ident;
12241 	offset = (frag_offset_flags << 3) & 0xFFFF;
12242 	src = ipha->ipha_src;
12243 	dst = ipha->ipha_dst;
12244 	hdr_length = IPH_HDR_LENGTH(ipha);
12245 	end = ntohs(ipha->ipha_length) - hdr_length;
12246 
12247 	/* If end == 0 then we have a packet with no data, so just free it */
12248 	if (end == 0) {
12249 		freemsg(mp);
12250 		return (B_FALSE);
12251 	}
12252 
12253 	/* Record the ECN field info. */
12254 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12255 	if (offset != 0) {
12256 		/*
12257 		 * If this isn't the first piece, strip the header, and
12258 		 * add the offset to the end value.
12259 		 */
12260 		mp->b_rptr += hdr_length;
12261 		end += offset;
12262 	}
12263 
12264 	msg_len = MBLKSIZE(mp);
12265 	tail_mp = mp;
12266 	while (tail_mp->b_cont != NULL) {
12267 		tail_mp = tail_mp->b_cont;
12268 		msg_len += MBLKSIZE(tail_mp);
12269 	}
12270 
12271 	/* If the reassembly list for this ILL will get too big, prune it */
12272 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12273 	    ipst->ips_ip_reass_queue_bytes) {
12274 		ill_frag_prune(ill,
12275 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12276 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12277 		pruned = B_TRUE;
12278 	}
12279 
12280 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12281 	mutex_enter(&ipfb->ipfb_lock);
12282 
12283 	ipfp = &ipfb->ipfb_ipf;
12284 	/* Try to find an existing fragment queue for this packet. */
12285 	for (;;) {
12286 		ipf = ipfp[0];
12287 		if (ipf != NULL) {
12288 			/*
12289 			 * It has to match on ident and src/dst address.
12290 			 */
12291 			if (ipf->ipf_ident == ident &&
12292 			    ipf->ipf_src == src &&
12293 			    ipf->ipf_dst == dst &&
12294 			    ipf->ipf_protocol == proto) {
12295 				/*
12296 				 * If we have received too many
12297 				 * duplicate fragments for this packet
12298 				 * free it.
12299 				 */
12300 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12301 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12302 					freemsg(mp);
12303 					mutex_exit(&ipfb->ipfb_lock);
12304 					return (B_FALSE);
12305 				}
12306 				/* Found it. */
12307 				break;
12308 			}
12309 			ipfp = &ipf->ipf_hash_next;
12310 			continue;
12311 		}
12312 
12313 		/*
12314 		 * If we pruned the list, do we want to store this new
12315 		 * fragment?. We apply an optimization here based on the
12316 		 * fact that most fragments will be received in order.
12317 		 * So if the offset of this incoming fragment is zero,
12318 		 * it is the first fragment of a new packet. We will
12319 		 * keep it.  Otherwise drop the fragment, as we have
12320 		 * probably pruned the packet already (since the
12321 		 * packet cannot be found).
12322 		 */
12323 		if (pruned && offset != 0) {
12324 			mutex_exit(&ipfb->ipfb_lock);
12325 			freemsg(mp);
12326 			return (B_FALSE);
12327 		}
12328 
12329 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12330 			/*
12331 			 * Too many fragmented packets in this hash
12332 			 * bucket. Free the oldest.
12333 			 */
12334 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12335 		}
12336 
12337 		/* New guy.  Allocate a frag message. */
12338 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12339 		if (mp1 == NULL) {
12340 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12341 			freemsg(mp);
12342 reass_done:
12343 			mutex_exit(&ipfb->ipfb_lock);
12344 			return (B_FALSE);
12345 		}
12346 
12347 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12348 		mp1->b_cont = mp;
12349 
12350 		/* Initialize the fragment header. */
12351 		ipf = (ipf_t *)mp1->b_rptr;
12352 		ipf->ipf_mp = mp1;
12353 		ipf->ipf_ptphn = ipfp;
12354 		ipfp[0] = ipf;
12355 		ipf->ipf_hash_next = NULL;
12356 		ipf->ipf_ident = ident;
12357 		ipf->ipf_protocol = proto;
12358 		ipf->ipf_src = src;
12359 		ipf->ipf_dst = dst;
12360 		ipf->ipf_nf_hdr_len = 0;
12361 		/* Record reassembly start time. */
12362 		ipf->ipf_timestamp = gethrestime_sec();
12363 		/* Record ipf generation and account for frag header */
12364 		ipf->ipf_gen = ill->ill_ipf_gen++;
12365 		ipf->ipf_count = MBLKSIZE(mp1);
12366 		ipf->ipf_last_frag_seen = B_FALSE;
12367 		ipf->ipf_ecn = ecn_info;
12368 		ipf->ipf_num_dups = 0;
12369 		ipfb->ipfb_frag_pkts++;
12370 		ipf->ipf_checksum = 0;
12371 		ipf->ipf_checksum_flags = 0;
12372 
12373 		/* Store checksum value in fragment header */
12374 		if (sum_flags != 0) {
12375 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12376 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12377 			ipf->ipf_checksum = sum_val;
12378 			ipf->ipf_checksum_flags = sum_flags;
12379 		}
12380 
12381 		/*
12382 		 * We handle reassembly two ways.  In the easy case,
12383 		 * where all the fragments show up in order, we do
12384 		 * minimal bookkeeping, and just clip new pieces on
12385 		 * the end.  If we ever see a hole, then we go off
12386 		 * to ip_reassemble which has to mark the pieces and
12387 		 * keep track of the number of holes, etc.  Obviously,
12388 		 * the point of having both mechanisms is so we can
12389 		 * handle the easy case as efficiently as possible.
12390 		 */
12391 		if (offset == 0) {
12392 			/* Easy case, in-order reassembly so far. */
12393 			ipf->ipf_count += msg_len;
12394 			ipf->ipf_tail_mp = tail_mp;
12395 			/*
12396 			 * Keep track of next expected offset in
12397 			 * ipf_end.
12398 			 */
12399 			ipf->ipf_end = end;
12400 			ipf->ipf_nf_hdr_len = hdr_length;
12401 		} else {
12402 			/* Hard case, hole at the beginning. */
12403 			ipf->ipf_tail_mp = NULL;
12404 			/*
12405 			 * ipf_end == 0 means that we have given up
12406 			 * on easy reassembly.
12407 			 */
12408 			ipf->ipf_end = 0;
12409 
12410 			/* Forget checksum offload from now on */
12411 			ipf->ipf_checksum_flags = 0;
12412 
12413 			/*
12414 			 * ipf_hole_cnt is set by ip_reassemble.
12415 			 * ipf_count is updated by ip_reassemble.
12416 			 * No need to check for return value here
12417 			 * as we don't expect reassembly to complete
12418 			 * or fail for the first fragment itself.
12419 			 */
12420 			(void) ip_reassemble(mp, ipf,
12421 			    (frag_offset_flags & IPH_OFFSET) << 3,
12422 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12423 		}
12424 		/* Update per ipfb and ill byte counts */
12425 		ipfb->ipfb_count += ipf->ipf_count;
12426 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12427 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12428 		/* If the frag timer wasn't already going, start it. */
12429 		mutex_enter(&ill->ill_lock);
12430 		ill_frag_timer_start(ill);
12431 		mutex_exit(&ill->ill_lock);
12432 		goto reass_done;
12433 	}
12434 
12435 	/*
12436 	 * If the packet's flag has changed (it could be coming up
12437 	 * from an interface different than the previous, therefore
12438 	 * possibly different checksum capability), then forget about
12439 	 * any stored checksum states.  Otherwise add the value to
12440 	 * the existing one stored in the fragment header.
12441 	 */
12442 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12443 		sum_val += ipf->ipf_checksum;
12444 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12445 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12446 		ipf->ipf_checksum = sum_val;
12447 	} else if (ipf->ipf_checksum_flags != 0) {
12448 		/* Forget checksum offload from now on */
12449 		ipf->ipf_checksum_flags = 0;
12450 	}
12451 
12452 	/*
12453 	 * We have a new piece of a datagram which is already being
12454 	 * reassembled.  Update the ECN info if all IP fragments
12455 	 * are ECN capable.  If there is one which is not, clear
12456 	 * all the info.  If there is at least one which has CE
12457 	 * code point, IP needs to report that up to transport.
12458 	 */
12459 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12460 		if (ecn_info == IPH_ECN_CE)
12461 			ipf->ipf_ecn = IPH_ECN_CE;
12462 	} else {
12463 		ipf->ipf_ecn = IPH_ECN_NECT;
12464 	}
12465 	if (offset && ipf->ipf_end == offset) {
12466 		/* The new fragment fits at the end */
12467 		ipf->ipf_tail_mp->b_cont = mp;
12468 		/* Update the byte count */
12469 		ipf->ipf_count += msg_len;
12470 		/* Update per ipfb and ill byte counts */
12471 		ipfb->ipfb_count += msg_len;
12472 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12473 		atomic_add_32(&ill->ill_frag_count, msg_len);
12474 		if (frag_offset_flags & IPH_MF) {
12475 			/* More to come. */
12476 			ipf->ipf_end = end;
12477 			ipf->ipf_tail_mp = tail_mp;
12478 			goto reass_done;
12479 		}
12480 	} else {
12481 		/* Go do the hard cases. */
12482 		int ret;
12483 
12484 		if (offset == 0)
12485 			ipf->ipf_nf_hdr_len = hdr_length;
12486 
12487 		/* Save current byte count */
12488 		count = ipf->ipf_count;
12489 		ret = ip_reassemble(mp, ipf,
12490 		    (frag_offset_flags & IPH_OFFSET) << 3,
12491 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12492 		/* Count of bytes added and subtracted (freeb()ed) */
12493 		count = ipf->ipf_count - count;
12494 		if (count) {
12495 			/* Update per ipfb and ill byte counts */
12496 			ipfb->ipfb_count += count;
12497 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12498 			atomic_add_32(&ill->ill_frag_count, count);
12499 		}
12500 		if (ret == IP_REASS_PARTIAL) {
12501 			goto reass_done;
12502 		} else if (ret == IP_REASS_FAILED) {
12503 			/* Reassembly failed. Free up all resources */
12504 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12505 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12506 				IP_REASS_SET_START(t_mp, 0);
12507 				IP_REASS_SET_END(t_mp, 0);
12508 			}
12509 			freemsg(mp);
12510 			goto reass_done;
12511 		}
12512 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12513 	}
12514 	/*
12515 	 * We have completed reassembly.  Unhook the frag header from
12516 	 * the reassembly list.
12517 	 *
12518 	 * Before we free the frag header, record the ECN info
12519 	 * to report back to the transport.
12520 	 */
12521 	ecn_info = ipf->ipf_ecn;
12522 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12523 	ipfp = ipf->ipf_ptphn;
12524 
12525 	/* We need to supply these to caller */
12526 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12527 		sum_val = ipf->ipf_checksum;
12528 	else
12529 		sum_val = 0;
12530 
12531 	mp1 = ipf->ipf_mp;
12532 	count = ipf->ipf_count;
12533 	ipf = ipf->ipf_hash_next;
12534 	if (ipf != NULL)
12535 		ipf->ipf_ptphn = ipfp;
12536 	ipfp[0] = ipf;
12537 	atomic_add_32(&ill->ill_frag_count, -count);
12538 	ASSERT(ipfb->ipfb_count >= count);
12539 	ipfb->ipfb_count -= count;
12540 	ipfb->ipfb_frag_pkts--;
12541 	mutex_exit(&ipfb->ipfb_lock);
12542 	/* Ditch the frag header. */
12543 	mp = mp1->b_cont;
12544 
12545 	freeb(mp1);
12546 
12547 	/* Restore original IP length in header. */
12548 	packet_size = (uint32_t)msgdsize(mp);
12549 	if (packet_size > IP_MAXPACKET) {
12550 		freemsg(mp);
12551 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12552 		return (B_FALSE);
12553 	}
12554 
12555 	if (DB_REF(mp) > 1) {
12556 		mblk_t *mp2 = copymsg(mp);
12557 
12558 		freemsg(mp);
12559 		if (mp2 == NULL) {
12560 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12561 			return (B_FALSE);
12562 		}
12563 		mp = mp2;
12564 	}
12565 	ipha = (ipha_t *)mp->b_rptr;
12566 
12567 	ipha->ipha_length = htons((uint16_t)packet_size);
12568 	/* We're now complete, zip the frag state */
12569 	ipha->ipha_fragment_offset_and_flags = 0;
12570 	/* Record the ECN info. */
12571 	ipha->ipha_type_of_service &= 0xFC;
12572 	ipha->ipha_type_of_service |= ecn_info;
12573 	*mpp = mp;
12574 
12575 	/* Reassembly is successful; return checksum information if needed */
12576 	if (cksum_val != NULL)
12577 		*cksum_val = sum_val;
12578 	if (cksum_flags != NULL)
12579 		*cksum_flags = sum_flags;
12580 
12581 	return (B_TRUE);
12582 }
12583 
12584 /*
12585  * Perform ip header check sum update local options.
12586  * return B_TRUE if all is well, else return B_FALSE and release
12587  * the mp. caller is responsible for decrementing ire ref cnt.
12588  */
12589 static boolean_t
12590 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12591     ip_stack_t *ipst)
12592 {
12593 	mblk_t		*first_mp;
12594 	boolean_t	mctl_present;
12595 	uint16_t	sum;
12596 
12597 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12598 	/*
12599 	 * Don't do the checksum if it has gone through AH/ESP
12600 	 * processing.
12601 	 */
12602 	if (!mctl_present) {
12603 		sum = ip_csum_hdr(ipha);
12604 		if (sum != 0) {
12605 			if (ill != NULL) {
12606 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12607 			} else {
12608 				BUMP_MIB(&ipst->ips_ip_mib,
12609 				    ipIfStatsInCksumErrs);
12610 			}
12611 			freemsg(first_mp);
12612 			return (B_FALSE);
12613 		}
12614 	}
12615 
12616 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12617 		if (mctl_present)
12618 			freeb(first_mp);
12619 		return (B_FALSE);
12620 	}
12621 
12622 	return (B_TRUE);
12623 }
12624 
12625 /*
12626  * All udp packet are delivered to the local host via this routine.
12627  */
12628 void
12629 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12630     ill_t *recv_ill)
12631 {
12632 	uint32_t	sum;
12633 	uint32_t	u1;
12634 	boolean_t	mctl_present;
12635 	conn_t		*connp;
12636 	mblk_t		*first_mp;
12637 	uint16_t	*up;
12638 	ill_t		*ill = (ill_t *)q->q_ptr;
12639 	uint16_t	reass_hck_flags = 0;
12640 	ip_stack_t	*ipst;
12641 
12642 	ASSERT(recv_ill != NULL);
12643 	ipst = recv_ill->ill_ipst;
12644 
12645 #define	rptr    ((uchar_t *)ipha)
12646 
12647 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12648 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12649 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12650 	ASSERT(ill != NULL);
12651 
12652 	/*
12653 	 * FAST PATH for udp packets
12654 	 */
12655 
12656 	/* u1 is # words of IP options */
12657 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12658 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12659 
12660 	/* IP options present */
12661 	if (u1 != 0)
12662 		goto ipoptions;
12663 
12664 	/* Check the IP header checksum.  */
12665 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12666 		/* Clear the IP header h/w cksum flag */
12667 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12668 	} else if (!mctl_present) {
12669 		/*
12670 		 * Don't verify header checksum if this packet is coming
12671 		 * back from AH/ESP as we already did it.
12672 		 */
12673 #define	uph	((uint16_t *)ipha)
12674 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12675 		    uph[6] + uph[7] + uph[8] + uph[9];
12676 #undef	uph
12677 		/* finish doing IP checksum */
12678 		sum = (sum & 0xFFFF) + (sum >> 16);
12679 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12680 		if (sum != 0 && sum != 0xFFFF) {
12681 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12682 			freemsg(first_mp);
12683 			return;
12684 		}
12685 	}
12686 
12687 	/*
12688 	 * Count for SNMP of inbound packets for ire.
12689 	 * if mctl is present this might be a secure packet and
12690 	 * has already been counted for in ip_proto_input().
12691 	 */
12692 	if (!mctl_present) {
12693 		UPDATE_IB_PKT_COUNT(ire);
12694 		ire->ire_last_used_time = lbolt;
12695 	}
12696 
12697 	/* packet part of fragmented IP packet? */
12698 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12699 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12700 		goto fragmented;
12701 	}
12702 
12703 	/* u1 = IP header length (20 bytes) */
12704 	u1 = IP_SIMPLE_HDR_LENGTH;
12705 
12706 	/* packet does not contain complete IP & UDP headers */
12707 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12708 		goto udppullup;
12709 
12710 	/* up points to UDP header */
12711 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12712 #define	iphs    ((uint16_t *)ipha)
12713 
12714 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12715 	if (up[3] != 0) {
12716 		mblk_t *mp1 = mp->b_cont;
12717 		boolean_t cksum_err;
12718 		uint16_t hck_flags = 0;
12719 
12720 		/* Pseudo-header checksum */
12721 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12722 		    iphs[9] + up[2];
12723 
12724 		/*
12725 		 * Revert to software checksum calculation if the interface
12726 		 * isn't capable of checksum offload or if IPsec is present.
12727 		 */
12728 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12729 			hck_flags = DB_CKSUMFLAGS(mp);
12730 
12731 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12732 			IP_STAT(ipst, ip_in_sw_cksum);
12733 
12734 		IP_CKSUM_RECV(hck_flags, u1,
12735 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12736 		    (int32_t)((uchar_t *)up - rptr),
12737 		    mp, mp1, cksum_err);
12738 
12739 		if (cksum_err) {
12740 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12741 			if (hck_flags & HCK_FULLCKSUM)
12742 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12743 			else if (hck_flags & HCK_PARTIALCKSUM)
12744 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12745 			else
12746 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12747 
12748 			freemsg(first_mp);
12749 			return;
12750 		}
12751 	}
12752 
12753 	/* Non-fragmented broadcast or multicast packet? */
12754 	if (ire->ire_type == IRE_BROADCAST)
12755 		goto udpslowpath;
12756 
12757 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12758 	    ire->ire_zoneid, ipst)) != NULL) {
12759 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12760 		IP_STAT(ipst, ip_udp_fast_path);
12761 
12762 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12763 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12764 			freemsg(mp);
12765 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12766 		} else {
12767 			if (!mctl_present) {
12768 				BUMP_MIB(ill->ill_ip_mib,
12769 				    ipIfStatsHCInDelivers);
12770 			}
12771 			/*
12772 			 * mp and first_mp can change.
12773 			 */
12774 			if (ip_udp_check(q, connp, recv_ill,
12775 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12776 				/* Send it upstream */
12777 				(connp->conn_recv)(connp, mp, NULL);
12778 			}
12779 		}
12780 		/*
12781 		 * freeb() cannot deal with null mblk being passed
12782 		 * in and first_mp can be set to null in the call
12783 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12784 		 */
12785 		if (mctl_present && first_mp != NULL) {
12786 			freeb(first_mp);
12787 		}
12788 		CONN_DEC_REF(connp);
12789 		return;
12790 	}
12791 
12792 	/*
12793 	 * if we got here we know the packet is not fragmented and
12794 	 * has no options. The classifier could not find a conn_t and
12795 	 * most likely its an icmp packet so send it through slow path.
12796 	 */
12797 
12798 	goto udpslowpath;
12799 
12800 ipoptions:
12801 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12802 		goto slow_done;
12803 	}
12804 
12805 	UPDATE_IB_PKT_COUNT(ire);
12806 	ire->ire_last_used_time = lbolt;
12807 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12808 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12809 fragmented:
12810 		/*
12811 		 * "sum" and "reass_hck_flags" are non-zero if the
12812 		 * reassembled packet has a valid hardware computed
12813 		 * checksum information associated with it.
12814 		 */
12815 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12816 		    &reass_hck_flags)) {
12817 			goto slow_done;
12818 		}
12819 
12820 		/*
12821 		 * Make sure that first_mp points back to mp as
12822 		 * the mp we came in with could have changed in
12823 		 * ip_rput_fragment().
12824 		 */
12825 		ASSERT(!mctl_present);
12826 		ipha = (ipha_t *)mp->b_rptr;
12827 		first_mp = mp;
12828 	}
12829 
12830 	/* Now we have a complete datagram, destined for this machine. */
12831 	u1 = IPH_HDR_LENGTH(ipha);
12832 	/* Pull up the UDP header, if necessary. */
12833 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12834 udppullup:
12835 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12836 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12837 			freemsg(first_mp);
12838 			goto slow_done;
12839 		}
12840 		ipha = (ipha_t *)mp->b_rptr;
12841 	}
12842 
12843 	/*
12844 	 * Validate the checksum for the reassembled packet; for the
12845 	 * pullup case we calculate the payload checksum in software.
12846 	 */
12847 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12848 	if (up[3] != 0) {
12849 		boolean_t cksum_err;
12850 
12851 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12852 			IP_STAT(ipst, ip_in_sw_cksum);
12853 
12854 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12855 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12856 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12857 		    iphs[9] + up[2], sum, cksum_err);
12858 
12859 		if (cksum_err) {
12860 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12861 
12862 			if (reass_hck_flags & HCK_FULLCKSUM)
12863 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12864 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12865 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12866 			else
12867 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12868 
12869 			freemsg(first_mp);
12870 			goto slow_done;
12871 		}
12872 	}
12873 udpslowpath:
12874 
12875 	/* Clear hardware checksum flag to be safe */
12876 	DB_CKSUMFLAGS(mp) = 0;
12877 
12878 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12879 	    (ire->ire_type == IRE_BROADCAST),
12880 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12881 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12882 
12883 slow_done:
12884 	IP_STAT(ipst, ip_udp_slow_path);
12885 	return;
12886 
12887 #undef  iphs
12888 #undef  rptr
12889 }
12890 
12891 /* ARGSUSED */
12892 static mblk_t *
12893 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12894     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12895     ill_rx_ring_t *ill_ring)
12896 {
12897 	conn_t		*connp;
12898 	uint32_t	sum;
12899 	uint32_t	u1;
12900 	uint16_t	*up;
12901 	int		offset;
12902 	ssize_t		len;
12903 	mblk_t		*mp1;
12904 	boolean_t	syn_present = B_FALSE;
12905 	tcph_t		*tcph;
12906 	uint_t		tcph_flags;
12907 	uint_t		ip_hdr_len;
12908 	ill_t		*ill = (ill_t *)q->q_ptr;
12909 	zoneid_t	zoneid = ire->ire_zoneid;
12910 	boolean_t	cksum_err;
12911 	uint16_t	hck_flags = 0;
12912 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12913 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12914 
12915 #define	rptr	((uchar_t *)ipha)
12916 
12917 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12918 	ASSERT(ill != NULL);
12919 
12920 	/*
12921 	 * FAST PATH for tcp packets
12922 	 */
12923 
12924 	/* u1 is # words of IP options */
12925 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12926 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12927 
12928 	/* IP options present */
12929 	if (u1) {
12930 		goto ipoptions;
12931 	} else if (!mctl_present) {
12932 		/* Check the IP header checksum.  */
12933 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12934 			/* Clear the IP header h/w cksum flag */
12935 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12936 		} else if (!mctl_present) {
12937 			/*
12938 			 * Don't verify header checksum if this packet
12939 			 * is coming back from AH/ESP as we already did it.
12940 			 */
12941 #define	uph	((uint16_t *)ipha)
12942 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12943 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12944 #undef	uph
12945 			/* finish doing IP checksum */
12946 			sum = (sum & 0xFFFF) + (sum >> 16);
12947 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12948 			if (sum != 0 && sum != 0xFFFF) {
12949 				BUMP_MIB(ill->ill_ip_mib,
12950 				    ipIfStatsInCksumErrs);
12951 				goto error;
12952 			}
12953 		}
12954 	}
12955 
12956 	if (!mctl_present) {
12957 		UPDATE_IB_PKT_COUNT(ire);
12958 		ire->ire_last_used_time = lbolt;
12959 	}
12960 
12961 	/* packet part of fragmented IP packet? */
12962 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12963 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12964 		goto fragmented;
12965 	}
12966 
12967 	/* u1 = IP header length (20 bytes) */
12968 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12969 
12970 	/* does packet contain IP+TCP headers? */
12971 	len = mp->b_wptr - rptr;
12972 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12973 		IP_STAT(ipst, ip_tcppullup);
12974 		goto tcppullup;
12975 	}
12976 
12977 	/* TCP options present? */
12978 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12979 
12980 	/*
12981 	 * If options need to be pulled up, then goto tcpoptions.
12982 	 * otherwise we are still in the fast path
12983 	 */
12984 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12985 		IP_STAT(ipst, ip_tcpoptions);
12986 		goto tcpoptions;
12987 	}
12988 
12989 	/* multiple mblks of tcp data? */
12990 	if ((mp1 = mp->b_cont) != NULL) {
12991 		IP_STAT(ipst, ip_multipkttcp);
12992 		len += msgdsize(mp1);
12993 	}
12994 
12995 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12996 
12997 	/* part of pseudo checksum */
12998 
12999 	/* TCP datagram length */
13000 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13001 
13002 #define	iphs    ((uint16_t *)ipha)
13003 
13004 #ifdef	_BIG_ENDIAN
13005 	u1 += IPPROTO_TCP;
13006 #else
13007 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13008 #endif
13009 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13010 
13011 	/*
13012 	 * Revert to software checksum calculation if the interface
13013 	 * isn't capable of checksum offload or if IPsec is present.
13014 	 */
13015 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
13016 		hck_flags = DB_CKSUMFLAGS(mp);
13017 
13018 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13019 		IP_STAT(ipst, ip_in_sw_cksum);
13020 
13021 	IP_CKSUM_RECV(hck_flags, u1,
13022 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13023 	    (int32_t)((uchar_t *)up - rptr),
13024 	    mp, mp1, cksum_err);
13025 
13026 	if (cksum_err) {
13027 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13028 
13029 		if (hck_flags & HCK_FULLCKSUM)
13030 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13031 		else if (hck_flags & HCK_PARTIALCKSUM)
13032 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13033 		else
13034 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13035 
13036 		goto error;
13037 	}
13038 
13039 try_again:
13040 
13041 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13042 	    zoneid, ipst)) == NULL) {
13043 		/* Send the TH_RST */
13044 		goto no_conn;
13045 	}
13046 
13047 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13048 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13049 
13050 	/*
13051 	 * TCP FAST PATH for AF_INET socket.
13052 	 *
13053 	 * TCP fast path to avoid extra work. An AF_INET socket type
13054 	 * does not have facility to receive extra information via
13055 	 * ip_process or ip_add_info. Also, when the connection was
13056 	 * established, we made a check if this connection is impacted
13057 	 * by any global IPsec policy or per connection policy (a
13058 	 * policy that comes in effect later will not apply to this
13059 	 * connection). Since all this can be determined at the
13060 	 * connection establishment time, a quick check of flags
13061 	 * can avoid extra work.
13062 	 */
13063 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13064 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13065 		ASSERT(first_mp == mp);
13066 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13067 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13068 			SET_SQUEUE(mp, tcp_rput_data, connp);
13069 			return (mp);
13070 		}
13071 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13072 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13073 		SET_SQUEUE(mp, tcp_input, connp);
13074 		return (mp);
13075 	}
13076 
13077 	if (tcph_flags == TH_SYN) {
13078 		if (IPCL_IS_TCP(connp)) {
13079 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13080 			DB_CKSUMSTART(mp) =
13081 			    (intptr_t)ip_squeue_get(ill_ring);
13082 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13083 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13084 				BUMP_MIB(ill->ill_ip_mib,
13085 				    ipIfStatsHCInDelivers);
13086 				SET_SQUEUE(mp, connp->conn_recv, connp);
13087 				return (mp);
13088 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13089 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13090 				BUMP_MIB(ill->ill_ip_mib,
13091 				    ipIfStatsHCInDelivers);
13092 				ip_squeue_enter_unbound++;
13093 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13094 				    connp);
13095 				return (mp);
13096 			}
13097 			syn_present = B_TRUE;
13098 		}
13099 	}
13100 
13101 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13102 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13103 
13104 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13105 		/* No need to send this packet to TCP */
13106 		if ((flags & TH_RST) || (flags & TH_URG)) {
13107 			CONN_DEC_REF(connp);
13108 			freemsg(first_mp);
13109 			return (NULL);
13110 		}
13111 		if (flags & TH_ACK) {
13112 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13113 			    ipst->ips_netstack->netstack_tcp, connp);
13114 			CONN_DEC_REF(connp);
13115 			return (NULL);
13116 		}
13117 
13118 		CONN_DEC_REF(connp);
13119 		freemsg(first_mp);
13120 		return (NULL);
13121 	}
13122 
13123 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13124 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13125 		    ipha, NULL, mctl_present);
13126 		if (first_mp == NULL) {
13127 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13128 			CONN_DEC_REF(connp);
13129 			return (NULL);
13130 		}
13131 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13132 			ASSERT(syn_present);
13133 			if (mctl_present) {
13134 				ASSERT(first_mp != mp);
13135 				first_mp->b_datap->db_struioflag |=
13136 				    STRUIO_POLICY;
13137 			} else {
13138 				ASSERT(first_mp == mp);
13139 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13140 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13141 			}
13142 		} else {
13143 			/*
13144 			 * Discard first_mp early since we're dealing with a
13145 			 * fully-connected conn_t and tcp doesn't do policy in
13146 			 * this case.
13147 			 */
13148 			if (mctl_present) {
13149 				freeb(first_mp);
13150 				mctl_present = B_FALSE;
13151 			}
13152 			first_mp = mp;
13153 		}
13154 	}
13155 
13156 	/* Initiate IPPF processing for fastpath */
13157 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13158 		uint32_t	ill_index;
13159 
13160 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13161 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13162 		if (mp == NULL) {
13163 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13164 			    "deferred/dropped during IPPF processing\n"));
13165 			CONN_DEC_REF(connp);
13166 			if (mctl_present)
13167 				freeb(first_mp);
13168 			return (NULL);
13169 		} else if (mctl_present) {
13170 			/*
13171 			 * ip_process might return a new mp.
13172 			 */
13173 			ASSERT(first_mp != mp);
13174 			first_mp->b_cont = mp;
13175 		} else {
13176 			first_mp = mp;
13177 		}
13178 
13179 	}
13180 
13181 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13182 		/*
13183 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13184 		 * make sure IPF_RECVIF is passed to ip_add_info.
13185 		 */
13186 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13187 		    IPCL_ZONEID(connp), ipst);
13188 		if (mp == NULL) {
13189 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13190 			CONN_DEC_REF(connp);
13191 			if (mctl_present)
13192 				freeb(first_mp);
13193 			return (NULL);
13194 		} else if (mctl_present) {
13195 			/*
13196 			 * ip_add_info might return a new mp.
13197 			 */
13198 			ASSERT(first_mp != mp);
13199 			first_mp->b_cont = mp;
13200 		} else {
13201 			first_mp = mp;
13202 		}
13203 	}
13204 
13205 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13206 	if (IPCL_IS_TCP(connp)) {
13207 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13208 		return (first_mp);
13209 	} else {
13210 		/* SOCK_RAW, IPPROTO_TCP case */
13211 		(connp->conn_recv)(connp, first_mp, NULL);
13212 		CONN_DEC_REF(connp);
13213 		return (NULL);
13214 	}
13215 
13216 no_conn:
13217 	/* Initiate IPPf processing, if needed. */
13218 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13219 		uint32_t ill_index;
13220 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13221 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13222 		if (first_mp == NULL) {
13223 			return (NULL);
13224 		}
13225 	}
13226 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13227 
13228 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13229 	    ipst->ips_netstack->netstack_tcp, NULL);
13230 	return (NULL);
13231 ipoptions:
13232 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13233 		goto slow_done;
13234 	}
13235 
13236 	UPDATE_IB_PKT_COUNT(ire);
13237 	ire->ire_last_used_time = lbolt;
13238 
13239 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13240 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13241 fragmented:
13242 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13243 			if (mctl_present)
13244 				freeb(first_mp);
13245 			goto slow_done;
13246 		}
13247 		/*
13248 		 * Make sure that first_mp points back to mp as
13249 		 * the mp we came in with could have changed in
13250 		 * ip_rput_fragment().
13251 		 */
13252 		ASSERT(!mctl_present);
13253 		ipha = (ipha_t *)mp->b_rptr;
13254 		first_mp = mp;
13255 	}
13256 
13257 	/* Now we have a complete datagram, destined for this machine. */
13258 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13259 
13260 	len = mp->b_wptr - mp->b_rptr;
13261 	/* Pull up a minimal TCP header, if necessary. */
13262 	if (len < (u1 + 20)) {
13263 tcppullup:
13264 		if (!pullupmsg(mp, u1 + 20)) {
13265 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13266 			goto error;
13267 		}
13268 		ipha = (ipha_t *)mp->b_rptr;
13269 		len = mp->b_wptr - mp->b_rptr;
13270 	}
13271 
13272 	/*
13273 	 * Extract the offset field from the TCP header.  As usual, we
13274 	 * try to help the compiler more than the reader.
13275 	 */
13276 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13277 	if (offset != 5) {
13278 tcpoptions:
13279 		if (offset < 5) {
13280 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13281 			goto error;
13282 		}
13283 		/*
13284 		 * There must be TCP options.
13285 		 * Make sure we can grab them.
13286 		 */
13287 		offset <<= 2;
13288 		offset += u1;
13289 		if (len < offset) {
13290 			if (!pullupmsg(mp, offset)) {
13291 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13292 				goto error;
13293 			}
13294 			ipha = (ipha_t *)mp->b_rptr;
13295 			len = mp->b_wptr - rptr;
13296 		}
13297 	}
13298 
13299 	/* Get the total packet length in len, including headers. */
13300 	if (mp->b_cont)
13301 		len = msgdsize(mp);
13302 
13303 	/*
13304 	 * Check the TCP checksum by pulling together the pseudo-
13305 	 * header checksum, and passing it to ip_csum to be added in
13306 	 * with the TCP datagram.
13307 	 *
13308 	 * Since we are not using the hwcksum if available we must
13309 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13310 	 * If either of these fails along the way the mblk is freed.
13311 	 * If this logic ever changes and mblk is reused to say send
13312 	 * ICMP's back, then this flag may need to be cleared in
13313 	 * other places as well.
13314 	 */
13315 	DB_CKSUMFLAGS(mp) = 0;
13316 
13317 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13318 
13319 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13320 #ifdef	_BIG_ENDIAN
13321 	u1 += IPPROTO_TCP;
13322 #else
13323 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13324 #endif
13325 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13326 	/*
13327 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13328 	 */
13329 	IP_STAT(ipst, ip_in_sw_cksum);
13330 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13331 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13332 		goto error;
13333 	}
13334 
13335 	IP_STAT(ipst, ip_tcp_slow_path);
13336 	goto try_again;
13337 #undef  iphs
13338 #undef  rptr
13339 
13340 error:
13341 	freemsg(first_mp);
13342 slow_done:
13343 	return (NULL);
13344 }
13345 
13346 /* ARGSUSED */
13347 static void
13348 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13349     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13350 {
13351 	conn_t		*connp;
13352 	uint32_t	sum;
13353 	uint32_t	u1;
13354 	ssize_t		len;
13355 	sctp_hdr_t	*sctph;
13356 	zoneid_t	zoneid = ire->ire_zoneid;
13357 	uint32_t	pktsum;
13358 	uint32_t	calcsum;
13359 	uint32_t	ports;
13360 	in6_addr_t	map_src, map_dst;
13361 	ill_t		*ill = (ill_t *)q->q_ptr;
13362 	ip_stack_t	*ipst;
13363 	sctp_stack_t	*sctps;
13364 	boolean_t	sctp_csum_err = B_FALSE;
13365 
13366 	ASSERT(recv_ill != NULL);
13367 	ipst = recv_ill->ill_ipst;
13368 	sctps = ipst->ips_netstack->netstack_sctp;
13369 
13370 #define	rptr	((uchar_t *)ipha)
13371 
13372 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13373 	ASSERT(ill != NULL);
13374 
13375 	/* u1 is # words of IP options */
13376 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13377 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13378 
13379 	/* IP options present */
13380 	if (u1 > 0) {
13381 		goto ipoptions;
13382 	} else {
13383 		/* Check the IP header checksum.  */
13384 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13385 		    !mctl_present) {
13386 #define	uph	((uint16_t *)ipha)
13387 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13388 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13389 #undef	uph
13390 			/* finish doing IP checksum */
13391 			sum = (sum & 0xFFFF) + (sum >> 16);
13392 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13393 			/*
13394 			 * Don't verify header checksum if this packet
13395 			 * is coming back from AH/ESP as we already did it.
13396 			 */
13397 			if (sum != 0 && sum != 0xFFFF) {
13398 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13399 				goto error;
13400 			}
13401 		}
13402 		/*
13403 		 * Since there is no SCTP h/w cksum support yet, just
13404 		 * clear the flag.
13405 		 */
13406 		DB_CKSUMFLAGS(mp) = 0;
13407 	}
13408 
13409 	/*
13410 	 * Don't verify header checksum if this packet is coming
13411 	 * back from AH/ESP as we already did it.
13412 	 */
13413 	if (!mctl_present) {
13414 		UPDATE_IB_PKT_COUNT(ire);
13415 		ire->ire_last_used_time = lbolt;
13416 	}
13417 
13418 	/* packet part of fragmented IP packet? */
13419 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13420 	if (u1 & (IPH_MF | IPH_OFFSET))
13421 		goto fragmented;
13422 
13423 	/* u1 = IP header length (20 bytes) */
13424 	u1 = IP_SIMPLE_HDR_LENGTH;
13425 
13426 find_sctp_client:
13427 	/* Pullup if we don't have the sctp common header. */
13428 	len = MBLKL(mp);
13429 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13430 		if (mp->b_cont == NULL ||
13431 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13432 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13433 			goto error;
13434 		}
13435 		ipha = (ipha_t *)mp->b_rptr;
13436 		len = MBLKL(mp);
13437 	}
13438 
13439 	sctph = (sctp_hdr_t *)(rptr + u1);
13440 #ifdef	DEBUG
13441 	if (!skip_sctp_cksum) {
13442 #endif
13443 		pktsum = sctph->sh_chksum;
13444 		sctph->sh_chksum = 0;
13445 		calcsum = sctp_cksum(mp, u1);
13446 		sctph->sh_chksum = pktsum;
13447 		if (calcsum != pktsum)
13448 			sctp_csum_err = B_TRUE;
13449 #ifdef	DEBUG	/* skip_sctp_cksum */
13450 	}
13451 #endif
13452 	/* get the ports */
13453 	ports = *(uint32_t *)&sctph->sh_sport;
13454 
13455 	IRE_REFRELE(ire);
13456 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13457 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13458 	if (sctp_csum_err) {
13459 		/*
13460 		 * No potential sctp checksum errors go to the Sun
13461 		 * sctp stack however they might be Adler-32 summed
13462 		 * packets a userland stack bound to a raw IP socket
13463 		 * could reasonably use. Note though that Adler-32 is
13464 		 * a long deprecated algorithm and customer sctp
13465 		 * networks should eventually migrate to CRC-32 at
13466 		 * which time this facility should be removed.
13467 		 */
13468 		flags |= IP_FF_SCTP_CSUM_ERR;
13469 		goto no_conn;
13470 	}
13471 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13472 	    sctps)) == NULL) {
13473 		/* Check for raw socket or OOTB handling */
13474 		goto no_conn;
13475 	}
13476 
13477 	/* Found a client; up it goes */
13478 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13479 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13480 	return;
13481 
13482 no_conn:
13483 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13484 	    ports, mctl_present, flags, B_TRUE, zoneid);
13485 	return;
13486 
13487 ipoptions:
13488 	DB_CKSUMFLAGS(mp) = 0;
13489 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13490 		goto slow_done;
13491 
13492 	UPDATE_IB_PKT_COUNT(ire);
13493 	ire->ire_last_used_time = lbolt;
13494 
13495 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13496 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13497 fragmented:
13498 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13499 			goto slow_done;
13500 		/*
13501 		 * Make sure that first_mp points back to mp as
13502 		 * the mp we came in with could have changed in
13503 		 * ip_rput_fragment().
13504 		 */
13505 		ASSERT(!mctl_present);
13506 		ipha = (ipha_t *)mp->b_rptr;
13507 		first_mp = mp;
13508 	}
13509 
13510 	/* Now we have a complete datagram, destined for this machine. */
13511 	u1 = IPH_HDR_LENGTH(ipha);
13512 	goto find_sctp_client;
13513 #undef  iphs
13514 #undef  rptr
13515 
13516 error:
13517 	freemsg(first_mp);
13518 slow_done:
13519 	IRE_REFRELE(ire);
13520 }
13521 
13522 #define	VER_BITS	0xF0
13523 #define	VERSION_6	0x60
13524 
13525 static boolean_t
13526 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13527     ipaddr_t *dstp, ip_stack_t *ipst)
13528 {
13529 	uint_t	opt_len;
13530 	ipha_t *ipha;
13531 	ssize_t len;
13532 	uint_t	pkt_len;
13533 
13534 	ASSERT(ill != NULL);
13535 	IP_STAT(ipst, ip_ipoptions);
13536 	ipha = *iphapp;
13537 
13538 #define	rptr    ((uchar_t *)ipha)
13539 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13540 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13541 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13542 		freemsg(mp);
13543 		return (B_FALSE);
13544 	}
13545 
13546 	/* multiple mblk or too short */
13547 	pkt_len = ntohs(ipha->ipha_length);
13548 
13549 	/* Get the number of words of IP options in the IP header. */
13550 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13551 	if (opt_len) {
13552 		/* IP Options present!  Validate and process. */
13553 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13554 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13555 			goto done;
13556 		}
13557 		/*
13558 		 * Recompute complete header length and make sure we
13559 		 * have access to all of it.
13560 		 */
13561 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13562 		if (len > (mp->b_wptr - rptr)) {
13563 			if (len > pkt_len) {
13564 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13565 				goto done;
13566 			}
13567 			if (!pullupmsg(mp, len)) {
13568 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13569 				goto done;
13570 			}
13571 			ipha = (ipha_t *)mp->b_rptr;
13572 		}
13573 		/*
13574 		 * Go off to ip_rput_options which returns the next hop
13575 		 * destination address, which may have been affected
13576 		 * by source routing.
13577 		 */
13578 		IP_STAT(ipst, ip_opt);
13579 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13580 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13581 			return (B_FALSE);
13582 		}
13583 	}
13584 	*iphapp = ipha;
13585 	return (B_TRUE);
13586 done:
13587 	/* clear b_prev - used by ip_mroute_decap */
13588 	mp->b_prev = NULL;
13589 	freemsg(mp);
13590 	return (B_FALSE);
13591 #undef  rptr
13592 }
13593 
13594 /*
13595  * Deal with the fact that there is no ire for the destination.
13596  */
13597 static ire_t *
13598 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13599 {
13600 	ipha_t	*ipha;
13601 	ill_t	*ill;
13602 	ire_t	*ire;
13603 	ip_stack_t *ipst;
13604 	enum	ire_forward_action ret_action;
13605 
13606 	ipha = (ipha_t *)mp->b_rptr;
13607 	ill = (ill_t *)q->q_ptr;
13608 
13609 	ASSERT(ill != NULL);
13610 	ipst = ill->ill_ipst;
13611 
13612 	/*
13613 	 * No IRE for this destination, so it can't be for us.
13614 	 * Unless we are forwarding, drop the packet.
13615 	 * We have to let source routed packets through
13616 	 * since we don't yet know if they are 'ping -l'
13617 	 * packets i.e. if they will go out over the
13618 	 * same interface as they came in on.
13619 	 */
13620 	if (ll_multicast) {
13621 		freemsg(mp);
13622 		return (NULL);
13623 	}
13624 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13625 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13626 		freemsg(mp);
13627 		return (NULL);
13628 	}
13629 
13630 	/*
13631 	 * Mark this packet as having originated externally.
13632 	 *
13633 	 * For non-forwarding code path, ire_send later double
13634 	 * checks this interface to see if it is still exists
13635 	 * post-ARP resolution.
13636 	 *
13637 	 * Also, IPQOS uses this to differentiate between
13638 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13639 	 * QOS packet processing in ip_wput_attach_llhdr().
13640 	 * The QoS module can mark the b_band for a fastpath message
13641 	 * or the dl_priority field in a unitdata_req header for
13642 	 * CoS marking. This info can only be found in
13643 	 * ip_wput_attach_llhdr().
13644 	 */
13645 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13646 	/*
13647 	 * Clear the indication that this may have a hardware checksum
13648 	 * as we are not using it
13649 	 */
13650 	DB_CKSUMFLAGS(mp) = 0;
13651 
13652 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13653 	    msg_getlabel(mp), ipst);
13654 
13655 	if (ire == NULL && ret_action == Forward_check_multirt) {
13656 		/* Let ip_newroute handle CGTP  */
13657 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13658 		return (NULL);
13659 	}
13660 
13661 	if (ire != NULL)
13662 		return (ire);
13663 
13664 	mp->b_prev = mp->b_next = 0;
13665 
13666 	if (ret_action == Forward_blackhole) {
13667 		freemsg(mp);
13668 		return (NULL);
13669 	}
13670 	/* send icmp unreachable */
13671 	q = WR(q);
13672 	/* Sent by forwarding path, and router is global zone */
13673 	if (ip_source_routed(ipha, ipst)) {
13674 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13675 		    GLOBAL_ZONEID, ipst);
13676 	} else {
13677 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13678 		    ipst);
13679 	}
13680 
13681 	return (NULL);
13682 
13683 }
13684 
13685 /*
13686  * check ip header length and align it.
13687  */
13688 static boolean_t
13689 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13690 {
13691 	ssize_t len;
13692 	ill_t *ill;
13693 	ipha_t	*ipha;
13694 
13695 	len = MBLKL(mp);
13696 
13697 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13698 		ill = (ill_t *)q->q_ptr;
13699 
13700 		if (!OK_32PTR(mp->b_rptr))
13701 			IP_STAT(ipst, ip_notaligned1);
13702 		else
13703 			IP_STAT(ipst, ip_notaligned2);
13704 		/* Guard against bogus device drivers */
13705 		if (len < 0) {
13706 			/* clear b_prev - used by ip_mroute_decap */
13707 			mp->b_prev = NULL;
13708 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13709 			freemsg(mp);
13710 			return (B_FALSE);
13711 		}
13712 
13713 		if (ip_rput_pullups++ == 0) {
13714 			ipha = (ipha_t *)mp->b_rptr;
13715 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13716 			    "ip_check_and_align_header: %s forced us to "
13717 			    " pullup pkt, hdr len %ld, hdr addr %p",
13718 			    ill->ill_name, len, (void *)ipha);
13719 		}
13720 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13721 			/* clear b_prev - used by ip_mroute_decap */
13722 			mp->b_prev = NULL;
13723 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13724 			freemsg(mp);
13725 			return (B_FALSE);
13726 		}
13727 	}
13728 	return (B_TRUE);
13729 }
13730 
13731 /*
13732  * Handle the situation where a packet came in on `ill' but matched an IRE
13733  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13734  * for interface statistics.
13735  */
13736 ire_t *
13737 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13738 {
13739 	ire_t		*new_ire;
13740 	ill_t		*ire_ill;
13741 	uint_t		ifindex;
13742 	ip_stack_t	*ipst = ill->ill_ipst;
13743 	boolean_t	strict_check = B_FALSE;
13744 
13745 	/*
13746 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13747 	 * issue (e.g. packet received on an underlying interface matched an
13748 	 * IRE_LOCAL on its associated group interface).
13749 	 */
13750 	if (ire->ire_rfq != NULL &&
13751 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13752 		return (ire);
13753 	}
13754 
13755 	/*
13756 	 * Do another ire lookup here, using the ingress ill, to see if the
13757 	 * interface is in a usesrc group.
13758 	 * As long as the ills belong to the same group, we don't consider
13759 	 * them to be arriving on the wrong interface. Thus, if the switch
13760 	 * is doing inbound load spreading, we won't drop packets when the
13761 	 * ip*_strict_dst_multihoming switch is on.
13762 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13763 	 * where the local address may not be unique. In this case we were
13764 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13765 	 * actually returned. The new lookup, which is more specific, should
13766 	 * only find the IRE_LOCAL associated with the ingress ill if one
13767 	 * exists.
13768 	 */
13769 
13770 	if (ire->ire_ipversion == IPV4_VERSION) {
13771 		if (ipst->ips_ip_strict_dst_multihoming)
13772 			strict_check = B_TRUE;
13773 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13774 		    ill->ill_ipif, ALL_ZONES, NULL,
13775 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13776 	} else {
13777 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13778 		if (ipst->ips_ipv6_strict_dst_multihoming)
13779 			strict_check = B_TRUE;
13780 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13781 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13782 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13783 	}
13784 	/*
13785 	 * If the same ire that was returned in ip_input() is found then this
13786 	 * is an indication that usesrc groups are in use. The packet
13787 	 * arrived on a different ill in the group than the one associated with
13788 	 * the destination address.  If a different ire was found then the same
13789 	 * IP address must be hosted on multiple ills. This is possible with
13790 	 * unnumbered point2point interfaces. We switch to use this new ire in
13791 	 * order to have accurate interface statistics.
13792 	 */
13793 	if (new_ire != NULL) {
13794 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13795 			ire_refrele(ire);
13796 			ire = new_ire;
13797 		} else {
13798 			ire_refrele(new_ire);
13799 		}
13800 		return (ire);
13801 	} else if ((ire->ire_rfq == NULL) &&
13802 	    (ire->ire_ipversion == IPV4_VERSION)) {
13803 		/*
13804 		 * The best match could have been the original ire which
13805 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13806 		 * the strict multihoming checks are irrelevant as we consider
13807 		 * local addresses hosted on lo0 to be interface agnostic. We
13808 		 * only expect a null ire_rfq on IREs which are associated with
13809 		 * lo0 hence we can return now.
13810 		 */
13811 		return (ire);
13812 	}
13813 
13814 	/*
13815 	 * Chase pointers once and store locally.
13816 	 */
13817 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13818 	    (ill_t *)(ire->ire_rfq->q_ptr);
13819 	ifindex = ill->ill_usesrc_ifindex;
13820 
13821 	/*
13822 	 * Check if it's a legal address on the 'usesrc' interface.
13823 	 */
13824 	if ((ifindex != 0) && (ire_ill != NULL) &&
13825 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13826 		return (ire);
13827 	}
13828 
13829 	/*
13830 	 * If the ip*_strict_dst_multihoming switch is on then we can
13831 	 * only accept this packet if the interface is marked as routing.
13832 	 */
13833 	if (!(strict_check))
13834 		return (ire);
13835 
13836 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13837 	    ILLF_ROUTER) != 0) {
13838 		return (ire);
13839 	}
13840 
13841 	ire_refrele(ire);
13842 	return (NULL);
13843 }
13844 
13845 /*
13846  *
13847  * This is the fast forward path. If we are here, we dont need to
13848  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13849  * needed to find the nexthop in this case is much simpler
13850  */
13851 ire_t *
13852 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13853 {
13854 	ipha_t	*ipha;
13855 	ire_t	*src_ire;
13856 	ill_t	*stq_ill;
13857 	uint_t	hlen;
13858 	uint_t	pkt_len;
13859 	uint32_t sum;
13860 	queue_t	*dev_q;
13861 	ip_stack_t *ipst = ill->ill_ipst;
13862 	mblk_t *fpmp;
13863 	enum	ire_forward_action ret_action;
13864 
13865 	ipha = (ipha_t *)mp->b_rptr;
13866 
13867 	if (ire != NULL &&
13868 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13869 	    ire->ire_zoneid != ALL_ZONES) {
13870 		/*
13871 		 * Should only use IREs that are visible to the global
13872 		 * zone for forwarding.
13873 		 */
13874 		ire_refrele(ire);
13875 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13876 		/*
13877 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13878 		 * transient cases. In such case, just drop the packet
13879 		 */
13880 		if (ire->ire_type != IRE_CACHE)
13881 			goto drop;
13882 	}
13883 
13884 	/*
13885 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13886 	 * The loopback address check for both src and dst has already
13887 	 * been checked in ip_input
13888 	 */
13889 
13890 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13891 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13892 		goto drop;
13893 	}
13894 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13895 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13896 
13897 	if (src_ire != NULL) {
13898 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13899 		ire_refrele(src_ire);
13900 		goto drop;
13901 	}
13902 
13903 	/* No ire cache of nexthop. So first create one  */
13904 	if (ire == NULL) {
13905 
13906 		ire = ire_forward_simple(dst, &ret_action, ipst);
13907 
13908 		/*
13909 		 * We only come to ip_fast_forward if ip_cgtp_filter
13910 		 * is not set. So ire_forward() should not return with
13911 		 * Forward_check_multirt as the next action.
13912 		 */
13913 		ASSERT(ret_action != Forward_check_multirt);
13914 		if (ire == NULL) {
13915 			/* An attempt was made to forward the packet */
13916 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13917 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13918 			mp->b_prev = mp->b_next = 0;
13919 			/* send icmp unreachable */
13920 			/* Sent by forwarding path, and router is global zone */
13921 			if (ret_action == Forward_ret_icmp_err) {
13922 				if (ip_source_routed(ipha, ipst)) {
13923 					icmp_unreachable(ill->ill_wq, mp,
13924 					    ICMP_SOURCE_ROUTE_FAILED,
13925 					    GLOBAL_ZONEID, ipst);
13926 				} else {
13927 					icmp_unreachable(ill->ill_wq, mp,
13928 					    ICMP_HOST_UNREACHABLE,
13929 					    GLOBAL_ZONEID, ipst);
13930 				}
13931 			} else {
13932 				freemsg(mp);
13933 			}
13934 			return (NULL);
13935 		}
13936 	}
13937 
13938 	/*
13939 	 * Forwarding fastpath exception case:
13940 	 * If any of the following are true, we take the slowpath:
13941 	 *	o forwarding is not enabled
13942 	 *	o incoming and outgoing interface are the same, or in the same
13943 	 *	  IPMP group.
13944 	 *	o corresponding ire is in incomplete state
13945 	 *	o packet needs fragmentation
13946 	 *	o ARP cache is not resolved
13947 	 *
13948 	 * The codeflow from here on is thus:
13949 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13950 	 */
13951 	pkt_len = ntohs(ipha->ipha_length);
13952 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13953 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13954 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13955 	    (ire->ire_nce == NULL) ||
13956 	    (pkt_len > ire->ire_max_frag) ||
13957 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13958 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13959 	    ipha->ipha_ttl <= 1) {
13960 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13961 		    ipha, ill, B_FALSE, B_TRUE);
13962 		return (ire);
13963 	}
13964 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13965 
13966 	DTRACE_PROBE4(ip4__forwarding__start,
13967 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13968 
13969 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13970 	    ipst->ips_ipv4firewall_forwarding,
13971 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13972 
13973 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13974 
13975 	if (mp == NULL)
13976 		goto drop;
13977 
13978 	mp->b_datap->db_struioun.cksum.flags = 0;
13979 	/* Adjust the checksum to reflect the ttl decrement. */
13980 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13981 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13982 	ipha->ipha_ttl--;
13983 
13984 	/*
13985 	 * Write the link layer header.  We can do this safely here,
13986 	 * because we have already tested to make sure that the IP
13987 	 * policy is not set, and that we have a fast path destination
13988 	 * header.
13989 	 */
13990 	mp->b_rptr -= hlen;
13991 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13992 
13993 	UPDATE_IB_PKT_COUNT(ire);
13994 	ire->ire_last_used_time = lbolt;
13995 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13996 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13997 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13998 
13999 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14000 		dev_q = ire->ire_stq->q_next;
14001 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14002 			goto indiscard;
14003 	}
14004 
14005 	DTRACE_PROBE4(ip4__physical__out__start,
14006 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14007 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14008 	    ipst->ips_ipv4firewall_physical_out,
14009 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14010 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14011 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14012 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14013 	    ip6_t *, NULL, int, 0);
14014 
14015 	if (mp != NULL) {
14016 		if (ipst->ips_ipobs_enabled) {
14017 			zoneid_t szone;
14018 
14019 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14020 			    ipst, ALL_ZONES);
14021 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14022 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14023 		}
14024 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
14025 	}
14026 	return (ire);
14027 
14028 indiscard:
14029 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14030 drop:
14031 	if (mp != NULL)
14032 		freemsg(mp);
14033 	return (ire);
14034 
14035 }
14036 
14037 /*
14038  * This function is called in the forwarding slowpath, when
14039  * either the ire lacks the link-layer address, or the packet needs
14040  * further processing(eg. fragmentation), before transmission.
14041  */
14042 
14043 static void
14044 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14045     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14046 {
14047 	queue_t		*dev_q;
14048 	ire_t		*src_ire;
14049 	ip_stack_t	*ipst = ill->ill_ipst;
14050 	boolean_t	same_illgrp = B_FALSE;
14051 
14052 	ASSERT(ire->ire_stq != NULL);
14053 
14054 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14055 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14056 
14057 	/*
14058 	 * If the caller of this function is ip_fast_forward() skip the
14059 	 * next three checks as it does not apply.
14060 	 */
14061 	if (from_ip_fast_forward)
14062 		goto skip;
14063 
14064 	if (ll_multicast != 0) {
14065 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14066 		goto drop_pkt;
14067 	}
14068 
14069 	/*
14070 	 * check if ipha_src is a broadcast address. Note that this
14071 	 * check is redundant when we get here from ip_fast_forward()
14072 	 * which has already done this check. However, since we can
14073 	 * also get here from ip_rput_process_broadcast() or, for
14074 	 * for the slow path through ip_fast_forward(), we perform
14075 	 * the check again for code-reusability
14076 	 */
14077 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14078 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14079 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14080 		if (src_ire != NULL)
14081 			ire_refrele(src_ire);
14082 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14083 		ip2dbg(("ip_rput_process_forward: Received packet with"
14084 		    " bad src/dst address on %s\n", ill->ill_name));
14085 		goto drop_pkt;
14086 	}
14087 
14088 	/*
14089 	 * Check if we want to forward this one at this time.
14090 	 * We allow source routed packets on a host provided that
14091 	 * they go out the same ill or illgrp as they came in on.
14092 	 *
14093 	 * XXX To be quicker, we may wish to not chase pointers to
14094 	 * get the ILLF_ROUTER flag and instead store the
14095 	 * forwarding policy in the ire.  An unfortunate
14096 	 * side-effect of that would be requiring an ire flush
14097 	 * whenever the ILLF_ROUTER flag changes.
14098 	 */
14099 skip:
14100 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14101 
14102 	if (((ill->ill_flags &
14103 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14104 	    !(ip_source_routed(ipha, ipst) &&
14105 	    (ire->ire_rfq == q || same_illgrp))) {
14106 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14107 		if (ip_source_routed(ipha, ipst)) {
14108 			q = WR(q);
14109 			/*
14110 			 * Clear the indication that this may have
14111 			 * hardware checksum as we are not using it.
14112 			 */
14113 			DB_CKSUMFLAGS(mp) = 0;
14114 			/* Sent by forwarding path, and router is global zone */
14115 			icmp_unreachable(q, mp,
14116 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14117 			return;
14118 		}
14119 		goto drop_pkt;
14120 	}
14121 
14122 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14123 
14124 	/* Packet is being forwarded. Turning off hwcksum flag. */
14125 	DB_CKSUMFLAGS(mp) = 0;
14126 	if (ipst->ips_ip_g_send_redirects) {
14127 		/*
14128 		 * Check whether the incoming interface and outgoing
14129 		 * interface is part of the same group. If so,
14130 		 * send redirects.
14131 		 *
14132 		 * Check the source address to see if it originated
14133 		 * on the same logical subnet it is going back out on.
14134 		 * If so, we should be able to send it a redirect.
14135 		 * Avoid sending a redirect if the destination
14136 		 * is directly connected (i.e., ipha_dst is the same
14137 		 * as ire_gateway_addr or the ire_addr of the
14138 		 * nexthop IRE_CACHE ), or if the packet was source
14139 		 * routed out this interface.
14140 		 */
14141 		ipaddr_t src, nhop;
14142 		mblk_t	*mp1;
14143 		ire_t	*nhop_ire = NULL;
14144 
14145 		/*
14146 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14147 		 * If so, send redirects.
14148 		 */
14149 		if ((ire->ire_rfq == q || same_illgrp) &&
14150 		    !ip_source_routed(ipha, ipst)) {
14151 
14152 			nhop = (ire->ire_gateway_addr != 0 ?
14153 			    ire->ire_gateway_addr : ire->ire_addr);
14154 
14155 			if (ipha->ipha_dst == nhop) {
14156 				/*
14157 				 * We avoid sending a redirect if the
14158 				 * destination is directly connected
14159 				 * because it is possible that multiple
14160 				 * IP subnets may have been configured on
14161 				 * the link, and the source may not
14162 				 * be on the same subnet as ip destination,
14163 				 * even though they are on the same
14164 				 * physical link.
14165 				 */
14166 				goto sendit;
14167 			}
14168 
14169 			src = ipha->ipha_src;
14170 
14171 			/*
14172 			 * We look up the interface ire for the nexthop,
14173 			 * to see if ipha_src is in the same subnet
14174 			 * as the nexthop.
14175 			 *
14176 			 * Note that, if, in the future, IRE_CACHE entries
14177 			 * are obsoleted,  this lookup will not be needed,
14178 			 * as the ire passed to this function will be the
14179 			 * same as the nhop_ire computed below.
14180 			 */
14181 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14182 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14183 			    0, NULL, MATCH_IRE_TYPE, ipst);
14184 
14185 			if (nhop_ire != NULL) {
14186 				if ((src & nhop_ire->ire_mask) ==
14187 				    (nhop & nhop_ire->ire_mask)) {
14188 					/*
14189 					 * The source is directly connected.
14190 					 * Just copy the ip header (which is
14191 					 * in the first mblk)
14192 					 */
14193 					mp1 = copyb(mp);
14194 					if (mp1 != NULL) {
14195 						icmp_send_redirect(WR(q), mp1,
14196 						    nhop, ipst);
14197 					}
14198 				}
14199 				ire_refrele(nhop_ire);
14200 			}
14201 		}
14202 	}
14203 sendit:
14204 	dev_q = ire->ire_stq->q_next;
14205 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14206 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14207 		freemsg(mp);
14208 		return;
14209 	}
14210 
14211 	ip_rput_forward(ire, ipha, mp, ill);
14212 	return;
14213 
14214 drop_pkt:
14215 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14216 	freemsg(mp);
14217 }
14218 
14219 ire_t *
14220 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14221     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14222 {
14223 	queue_t		*q;
14224 	uint16_t	hcksumflags;
14225 	ip_stack_t	*ipst = ill->ill_ipst;
14226 
14227 	q = *qp;
14228 
14229 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14230 
14231 	/*
14232 	 * Clear the indication that this may have hardware
14233 	 * checksum as we are not using it for forwarding.
14234 	 */
14235 	hcksumflags = DB_CKSUMFLAGS(mp);
14236 	DB_CKSUMFLAGS(mp) = 0;
14237 
14238 	/*
14239 	 * Directed broadcast forwarding: if the packet came in over a
14240 	 * different interface then it is routed out over we can forward it.
14241 	 */
14242 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14243 		ire_refrele(ire);
14244 		freemsg(mp);
14245 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14246 		return (NULL);
14247 	}
14248 	/*
14249 	 * For multicast we have set dst to be INADDR_BROADCAST
14250 	 * for delivering to all STREAMS.
14251 	 */
14252 	if (!CLASSD(ipha->ipha_dst)) {
14253 		ire_t *new_ire;
14254 		ipif_t *ipif;
14255 
14256 		ipif = ipif_get_next_ipif(NULL, ill);
14257 		if (ipif == NULL) {
14258 discard:		ire_refrele(ire);
14259 			freemsg(mp);
14260 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14261 			return (NULL);
14262 		}
14263 		new_ire = ire_ctable_lookup(dst, 0, 0,
14264 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14265 		ipif_refrele(ipif);
14266 
14267 		if (new_ire != NULL) {
14268 			/*
14269 			 * If the matching IRE_BROADCAST is part of an IPMP
14270 			 * group, then drop the packet unless our ill has been
14271 			 * nominated to receive for the group.
14272 			 */
14273 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14274 			    new_ire->ire_rfq != q) {
14275 				ire_refrele(new_ire);
14276 				goto discard;
14277 			}
14278 
14279 			/*
14280 			 * In the special case of multirouted broadcast
14281 			 * packets, we unconditionally need to "gateway"
14282 			 * them to the appropriate interface here.
14283 			 * In the normal case, this cannot happen, because
14284 			 * there is no broadcast IRE tagged with the
14285 			 * RTF_MULTIRT flag.
14286 			 */
14287 			if (new_ire->ire_flags & RTF_MULTIRT) {
14288 				ire_refrele(new_ire);
14289 				if (ire->ire_rfq != NULL) {
14290 					q = ire->ire_rfq;
14291 					*qp = q;
14292 				}
14293 			} else {
14294 				ire_refrele(ire);
14295 				ire = new_ire;
14296 			}
14297 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14298 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14299 				/*
14300 				 * Free the message if
14301 				 * ip_g_forward_directed_bcast is turned
14302 				 * off for non-local broadcast.
14303 				 */
14304 				ire_refrele(ire);
14305 				freemsg(mp);
14306 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14307 				return (NULL);
14308 			}
14309 		} else {
14310 			/*
14311 			 * This CGTP packet successfully passed the
14312 			 * CGTP filter, but the related CGTP
14313 			 * broadcast IRE has not been found,
14314 			 * meaning that the redundant ipif is
14315 			 * probably down. However, if we discarded
14316 			 * this packet, its duplicate would be
14317 			 * filtered out by the CGTP filter so none
14318 			 * of them would get through. So we keep
14319 			 * going with this one.
14320 			 */
14321 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14322 			if (ire->ire_rfq != NULL) {
14323 				q = ire->ire_rfq;
14324 				*qp = q;
14325 			}
14326 		}
14327 	}
14328 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14329 		/*
14330 		 * Verify that there are not more then one
14331 		 * IRE_BROADCAST with this broadcast address which
14332 		 * has ire_stq set.
14333 		 * TODO: simplify, loop over all IRE's
14334 		 */
14335 		ire_t	*ire1;
14336 		int	num_stq = 0;
14337 		mblk_t	*mp1;
14338 
14339 		/* Find the first one with ire_stq set */
14340 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14341 		for (ire1 = ire; ire1 &&
14342 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14343 		    ire1 = ire1->ire_next)
14344 			;
14345 		if (ire1) {
14346 			ire_refrele(ire);
14347 			ire = ire1;
14348 			IRE_REFHOLD(ire);
14349 		}
14350 
14351 		/* Check if there are additional ones with stq set */
14352 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14353 			if (ire->ire_addr != ire1->ire_addr)
14354 				break;
14355 			if (ire1->ire_stq) {
14356 				num_stq++;
14357 				break;
14358 			}
14359 		}
14360 		rw_exit(&ire->ire_bucket->irb_lock);
14361 		if (num_stq == 1 && ire->ire_stq != NULL) {
14362 			ip1dbg(("ip_rput_process_broadcast: directed "
14363 			    "broadcast to 0x%x\n",
14364 			    ntohl(ire->ire_addr)));
14365 			mp1 = copymsg(mp);
14366 			if (mp1) {
14367 				switch (ipha->ipha_protocol) {
14368 				case IPPROTO_UDP:
14369 					ip_udp_input(q, mp1, ipha, ire, ill);
14370 					break;
14371 				default:
14372 					ip_proto_input(q, mp1, ipha, ire, ill,
14373 					    0);
14374 					break;
14375 				}
14376 			}
14377 			/*
14378 			 * Adjust ttl to 2 (1+1 - the forward engine
14379 			 * will decrement it by one.
14380 			 */
14381 			if (ip_csum_hdr(ipha)) {
14382 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14383 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14384 				freemsg(mp);
14385 				ire_refrele(ire);
14386 				return (NULL);
14387 			}
14388 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14389 			ipha->ipha_hdr_checksum = 0;
14390 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14391 			ip_rput_process_forward(q, mp, ire, ipha,
14392 			    ill, ll_multicast, B_FALSE);
14393 			ire_refrele(ire);
14394 			return (NULL);
14395 		}
14396 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14397 		    ntohl(ire->ire_addr)));
14398 	}
14399 
14400 	/* Restore any hardware checksum flags */
14401 	DB_CKSUMFLAGS(mp) = hcksumflags;
14402 	return (ire);
14403 }
14404 
14405 /* ARGSUSED */
14406 static boolean_t
14407 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14408     int *ll_multicast, ipaddr_t *dstp)
14409 {
14410 	ip_stack_t	*ipst = ill->ill_ipst;
14411 
14412 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14413 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14414 	    ntohs(ipha->ipha_length));
14415 
14416 	/*
14417 	 * So that we don't end up with dups, only one ill in an IPMP group is
14418 	 * nominated to receive multicast traffic.
14419 	 */
14420 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14421 		goto drop_pkt;
14422 
14423 	/*
14424 	 * Forward packets only if we have joined the allmulti
14425 	 * group on this interface.
14426 	 */
14427 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14428 		int retval;
14429 
14430 		/*
14431 		 * Clear the indication that this may have hardware
14432 		 * checksum as we are not using it.
14433 		 */
14434 		DB_CKSUMFLAGS(mp) = 0;
14435 		retval = ip_mforward(ill, ipha, mp);
14436 		/* ip_mforward updates mib variables if needed */
14437 		/* clear b_prev - used by ip_mroute_decap */
14438 		mp->b_prev = NULL;
14439 
14440 		switch (retval) {
14441 		case 0:
14442 			/*
14443 			 * pkt is okay and arrived on phyint.
14444 			 *
14445 			 * If we are running as a multicast router
14446 			 * we need to see all IGMP and/or PIM packets.
14447 			 */
14448 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14449 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14450 				goto done;
14451 			}
14452 			break;
14453 		case -1:
14454 			/* pkt is mal-formed, toss it */
14455 			goto drop_pkt;
14456 		case 1:
14457 			/* pkt is okay and arrived on a tunnel */
14458 			/*
14459 			 * If we are running a multicast router
14460 			 *  we need to see all igmp packets.
14461 			 */
14462 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14463 				*dstp = INADDR_BROADCAST;
14464 				*ll_multicast = 1;
14465 				return (B_FALSE);
14466 			}
14467 
14468 			goto drop_pkt;
14469 		}
14470 	}
14471 
14472 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14473 		/*
14474 		 * This might just be caused by the fact that
14475 		 * multiple IP Multicast addresses map to the same
14476 		 * link layer multicast - no need to increment counter!
14477 		 */
14478 		freemsg(mp);
14479 		return (B_TRUE);
14480 	}
14481 done:
14482 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14483 	/*
14484 	 * This assumes the we deliver to all streams for multicast
14485 	 * and broadcast packets.
14486 	 */
14487 	*dstp = INADDR_BROADCAST;
14488 	*ll_multicast = 1;
14489 	return (B_FALSE);
14490 drop_pkt:
14491 	ip2dbg(("ip_rput: drop pkt\n"));
14492 	freemsg(mp);
14493 	return (B_TRUE);
14494 }
14495 
14496 /*
14497  * This function is used to both return an indication of whether or not
14498  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14499  * and in doing so, determine whether or not it is broadcast vs multicast.
14500  * For it to be a broadcast packet, we must have the appropriate mblk_t
14501  * hanging off the ill_t.  If this is either not present or doesn't match
14502  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14503  * to be multicast.  Thus NICs that have no broadcast address (or no
14504  * capability for one, such as point to point links) cannot return as
14505  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14506  * the return values simplifies the current use of the return value of this
14507  * function, which is to pass through the multicast/broadcast characteristic
14508  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14509  * changing the return value to some other symbol demands the appropriate
14510  * "translation" when hpe_flags is set prior to calling hook_run() for
14511  * packet events.
14512  */
14513 int
14514 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14515 {
14516 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14517 	mblk_t *bmp;
14518 
14519 	if (ind->dl_group_address) {
14520 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14521 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14522 		    MBLKL(mb) &&
14523 		    (bmp = ill->ill_bcast_mp) != NULL) {
14524 			dl_unitdata_req_t *dlur;
14525 			uint8_t *bphys_addr;
14526 
14527 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14528 			if (ill->ill_sap_length < 0)
14529 				bphys_addr = (uchar_t *)dlur +
14530 				    dlur->dl_dest_addr_offset;
14531 			else
14532 				bphys_addr = (uchar_t *)dlur +
14533 				    dlur->dl_dest_addr_offset +
14534 				    ill->ill_sap_length;
14535 
14536 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14537 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14538 				return (HPE_BROADCAST);
14539 			}
14540 			return (HPE_MULTICAST);
14541 		}
14542 		return (HPE_MULTICAST);
14543 	}
14544 	return (0);
14545 }
14546 
14547 static boolean_t
14548 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14549     int *ll_multicast, mblk_t **mpp)
14550 {
14551 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14552 	boolean_t must_copy = B_FALSE;
14553 	struct iocblk   *iocp;
14554 	ipha_t		*ipha;
14555 	ip_stack_t	*ipst = ill->ill_ipst;
14556 
14557 #define	rptr    ((uchar_t *)ipha)
14558 
14559 	first_mp = *first_mpp;
14560 	mp = *mpp;
14561 
14562 	ASSERT(first_mp == mp);
14563 
14564 	/*
14565 	 * if db_ref > 1 then copymsg and free original. Packet may be
14566 	 * changed and do not want other entity who has a reference to this
14567 	 * message to trip over the changes. This is a blind change because
14568 	 * trying to catch all places that might change packet is too
14569 	 * difficult (since it may be a module above this one)
14570 	 *
14571 	 * This corresponds to the non-fast path case. We walk down the full
14572 	 * chain in this case, and check the db_ref count of all the dblks,
14573 	 * and do a copymsg if required. It is possible that the db_ref counts
14574 	 * of the data blocks in the mblk chain can be different.
14575 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14576 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14577 	 * 'snoop' is running.
14578 	 */
14579 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14580 		if (mp1->b_datap->db_ref > 1) {
14581 			must_copy = B_TRUE;
14582 			break;
14583 		}
14584 	}
14585 
14586 	if (must_copy) {
14587 		mp1 = copymsg(mp);
14588 		if (mp1 == NULL) {
14589 			for (mp1 = mp; mp1 != NULL;
14590 			    mp1 = mp1->b_cont) {
14591 				mp1->b_next = NULL;
14592 				mp1->b_prev = NULL;
14593 			}
14594 			freemsg(mp);
14595 			if (ill != NULL) {
14596 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14597 			} else {
14598 				BUMP_MIB(&ipst->ips_ip_mib,
14599 				    ipIfStatsInDiscards);
14600 			}
14601 			return (B_TRUE);
14602 		}
14603 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14604 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14605 			/* Copy b_prev - used by ip_mroute_decap */
14606 			to_mp->b_prev = from_mp->b_prev;
14607 			from_mp->b_prev = NULL;
14608 		}
14609 		*first_mpp = first_mp = mp1;
14610 		freemsg(mp);
14611 		mp = mp1;
14612 		*mpp = mp1;
14613 	}
14614 
14615 	ipha = (ipha_t *)mp->b_rptr;
14616 
14617 	/*
14618 	 * previous code has a case for M_DATA.
14619 	 * We want to check how that happens.
14620 	 */
14621 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14622 	switch (first_mp->b_datap->db_type) {
14623 	case M_PROTO:
14624 	case M_PCPROTO:
14625 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14626 		    DL_UNITDATA_IND) {
14627 			/* Go handle anything other than data elsewhere. */
14628 			ip_rput_dlpi(q, mp);
14629 			return (B_TRUE);
14630 		}
14631 
14632 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14633 		/* Ditch the DLPI header. */
14634 		mp1 = mp->b_cont;
14635 		ASSERT(first_mp == mp);
14636 		*first_mpp = mp1;
14637 		freeb(mp);
14638 		*mpp = mp1;
14639 		return (B_FALSE);
14640 	case M_IOCACK:
14641 		ip1dbg(("got iocack "));
14642 		iocp = (struct iocblk *)mp->b_rptr;
14643 		switch (iocp->ioc_cmd) {
14644 		case DL_IOC_HDR_INFO:
14645 			ill = (ill_t *)q->q_ptr;
14646 			ill_fastpath_ack(ill, mp);
14647 			return (B_TRUE);
14648 		case SIOCSTUNPARAM:
14649 		case OSIOCSTUNPARAM:
14650 			/* Go through qwriter_ip */
14651 			break;
14652 		case SIOCGTUNPARAM:
14653 		case OSIOCGTUNPARAM:
14654 			ip_rput_other(NULL, q, mp, NULL);
14655 			return (B_TRUE);
14656 		default:
14657 			putnext(q, mp);
14658 			return (B_TRUE);
14659 		}
14660 		/* FALLTHRU */
14661 	case M_ERROR:
14662 	case M_HANGUP:
14663 		/*
14664 		 * Since this is on the ill stream we unconditionally
14665 		 * bump up the refcount
14666 		 */
14667 		ill_refhold(ill);
14668 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14669 		return (B_TRUE);
14670 	case M_CTL:
14671 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14672 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14673 		    IPHADA_M_CTL)) {
14674 			/*
14675 			 * It's an IPsec accelerated packet.
14676 			 * Make sure that the ill from which we received the
14677 			 * packet has enabled IPsec hardware acceleration.
14678 			 */
14679 			if (!(ill->ill_capabilities &
14680 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14681 				/* IPsec kstats: bean counter */
14682 				freemsg(mp);
14683 				return (B_TRUE);
14684 			}
14685 
14686 			/*
14687 			 * Make mp point to the mblk following the M_CTL,
14688 			 * then process according to type of mp.
14689 			 * After this processing, first_mp will point to
14690 			 * the data-attributes and mp to the pkt following
14691 			 * the M_CTL.
14692 			 */
14693 			mp = first_mp->b_cont;
14694 			if (mp == NULL) {
14695 				freemsg(first_mp);
14696 				return (B_TRUE);
14697 			}
14698 			/*
14699 			 * A Hardware Accelerated packet can only be M_DATA
14700 			 * ESP or AH packet.
14701 			 */
14702 			if (mp->b_datap->db_type != M_DATA) {
14703 				/* non-M_DATA IPsec accelerated packet */
14704 				IPSECHW_DEBUG(IPSECHW_PKT,
14705 				    ("non-M_DATA IPsec accelerated pkt\n"));
14706 				freemsg(first_mp);
14707 				return (B_TRUE);
14708 			}
14709 			ipha = (ipha_t *)mp->b_rptr;
14710 			if (ipha->ipha_protocol != IPPROTO_AH &&
14711 			    ipha->ipha_protocol != IPPROTO_ESP) {
14712 				IPSECHW_DEBUG(IPSECHW_PKT,
14713 				    ("non-M_DATA IPsec accelerated pkt\n"));
14714 				freemsg(first_mp);
14715 				return (B_TRUE);
14716 			}
14717 			*mpp = mp;
14718 			return (B_FALSE);
14719 		}
14720 		putnext(q, mp);
14721 		return (B_TRUE);
14722 	case M_IOCNAK:
14723 		ip1dbg(("got iocnak "));
14724 		iocp = (struct iocblk *)mp->b_rptr;
14725 		switch (iocp->ioc_cmd) {
14726 		case SIOCSTUNPARAM:
14727 		case OSIOCSTUNPARAM:
14728 			/*
14729 			 * Since this is on the ill stream we unconditionally
14730 			 * bump up the refcount
14731 			 */
14732 			ill_refhold(ill);
14733 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14734 			return (B_TRUE);
14735 		case DL_IOC_HDR_INFO:
14736 		case SIOCGTUNPARAM:
14737 		case OSIOCGTUNPARAM:
14738 			ip_rput_other(NULL, q, mp, NULL);
14739 			return (B_TRUE);
14740 		default:
14741 			break;
14742 		}
14743 		/* FALLTHRU */
14744 	default:
14745 		putnext(q, mp);
14746 		return (B_TRUE);
14747 	}
14748 }
14749 
14750 /* Read side put procedure.  Packets coming from the wire arrive here. */
14751 void
14752 ip_rput(queue_t *q, mblk_t *mp)
14753 {
14754 	ill_t	*ill;
14755 	union DL_primitives *dl;
14756 
14757 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14758 
14759 	ill = (ill_t *)q->q_ptr;
14760 
14761 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14762 		/*
14763 		 * If things are opening or closing, only accept high-priority
14764 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14765 		 * created; on close, things hanging off the ill may have been
14766 		 * freed already.)
14767 		 */
14768 		dl = (union DL_primitives *)mp->b_rptr;
14769 		if (DB_TYPE(mp) != M_PCPROTO ||
14770 		    dl->dl_primitive == DL_UNITDATA_IND) {
14771 			/*
14772 			 * SIOC[GS]TUNPARAM ioctls can come here.
14773 			 */
14774 			inet_freemsg(mp);
14775 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14776 			    "ip_rput_end: q %p (%S)", q, "uninit");
14777 			return;
14778 		}
14779 	}
14780 
14781 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14782 	    "ip_rput_end: q %p (%S)", q, "end");
14783 
14784 	ip_input(ill, NULL, mp, NULL);
14785 }
14786 
14787 static mblk_t *
14788 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14789 {
14790 	mblk_t *mp1;
14791 	boolean_t adjusted = B_FALSE;
14792 	ip_stack_t *ipst = ill->ill_ipst;
14793 
14794 	IP_STAT(ipst, ip_db_ref);
14795 	/*
14796 	 * The IP_RECVSLLA option depends on having the
14797 	 * link layer header. First check that:
14798 	 * a> the underlying device is of type ether,
14799 	 * since this option is currently supported only
14800 	 * over ethernet.
14801 	 * b> there is enough room to copy over the link
14802 	 * layer header.
14803 	 *
14804 	 * Once the checks are done, adjust rptr so that
14805 	 * the link layer header will be copied via
14806 	 * copymsg. Note that, IFT_ETHER may be returned
14807 	 * by some non-ethernet drivers but in this case
14808 	 * the second check will fail.
14809 	 */
14810 	if (ill->ill_type == IFT_ETHER &&
14811 	    (mp->b_rptr - mp->b_datap->db_base) >=
14812 	    sizeof (struct ether_header)) {
14813 		mp->b_rptr -= sizeof (struct ether_header);
14814 		adjusted = B_TRUE;
14815 	}
14816 	mp1 = copymsg(mp);
14817 
14818 	if (mp1 == NULL) {
14819 		mp->b_next = NULL;
14820 		/* clear b_prev - used by ip_mroute_decap */
14821 		mp->b_prev = NULL;
14822 		freemsg(mp);
14823 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14824 		return (NULL);
14825 	}
14826 
14827 	if (adjusted) {
14828 		/*
14829 		 * Copy is done. Restore the pointer in
14830 		 * the _new_ mblk
14831 		 */
14832 		mp1->b_rptr += sizeof (struct ether_header);
14833 	}
14834 
14835 	/* Copy b_prev - used by ip_mroute_decap */
14836 	mp1->b_prev = mp->b_prev;
14837 	mp->b_prev = NULL;
14838 
14839 	/* preserve the hardware checksum flags and data, if present */
14840 	if (DB_CKSUMFLAGS(mp) != 0) {
14841 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14842 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14843 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14844 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14845 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14846 	}
14847 
14848 	freemsg(mp);
14849 	return (mp1);
14850 }
14851 
14852 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14853 	if (tail != NULL)					\
14854 		tail->b_next = mp;				\
14855 	else							\
14856 		head = mp;					\
14857 	tail = mp;						\
14858 	cnt++;							\
14859 }
14860 
14861 /*
14862  * Direct read side procedure capable of dealing with chains. GLDv3 based
14863  * drivers call this function directly with mblk chains while STREAMS
14864  * read side procedure ip_rput() calls this for single packet with ip_ring
14865  * set to NULL to process one packet at a time.
14866  *
14867  * The ill will always be valid if this function is called directly from
14868  * the driver.
14869  *
14870  * If ip_input() is called from GLDv3:
14871  *
14872  *   - This must be a non-VLAN IP stream.
14873  *   - 'mp' is either an untagged or a special priority-tagged packet.
14874  *   - Any VLAN tag that was in the MAC header has been stripped.
14875  *
14876  * If the IP header in packet is not 32-bit aligned, every message in the
14877  * chain will be aligned before further operations. This is required on SPARC
14878  * platform.
14879  */
14880 /* ARGSUSED */
14881 void
14882 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14883     struct mac_header_info_s *mhip)
14884 {
14885 	ipaddr_t		dst = NULL;
14886 	ipaddr_t		prev_dst;
14887 	ire_t			*ire = NULL;
14888 	ipha_t			*ipha;
14889 	uint_t			pkt_len;
14890 	ssize_t			len;
14891 	uint_t			opt_len;
14892 	int			ll_multicast;
14893 	int			cgtp_flt_pkt;
14894 	queue_t			*q = ill->ill_rq;
14895 	squeue_t		*curr_sqp = NULL;
14896 	mblk_t 			*head = NULL;
14897 	mblk_t			*tail = NULL;
14898 	mblk_t			*first_mp;
14899 	int			cnt = 0;
14900 	ip_stack_t		*ipst = ill->ill_ipst;
14901 	mblk_t			*mp;
14902 	mblk_t			*dmp;
14903 	uint8_t			tag;
14904 
14905 	ASSERT(mp_chain != NULL);
14906 	ASSERT(ill != NULL);
14907 
14908 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14909 
14910 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14911 
14912 #define	rptr	((uchar_t *)ipha)
14913 
14914 	while (mp_chain != NULL) {
14915 		mp = mp_chain;
14916 		mp_chain = mp_chain->b_next;
14917 		mp->b_next = NULL;
14918 		ll_multicast = 0;
14919 
14920 		/*
14921 		 * We do ire caching from one iteration to
14922 		 * another. In the event the packet chain contains
14923 		 * all packets from the same dst, this caching saves
14924 		 * an ire_cache_lookup for each of the succeeding
14925 		 * packets in a packet chain.
14926 		 */
14927 		prev_dst = dst;
14928 
14929 		/*
14930 		 * if db_ref > 1 then copymsg and free original. Packet
14931 		 * may be changed and we do not want the other entity
14932 		 * who has a reference to this message to trip over the
14933 		 * changes. This is a blind change because trying to
14934 		 * catch all places that might change the packet is too
14935 		 * difficult.
14936 		 *
14937 		 * This corresponds to the fast path case, where we have
14938 		 * a chain of M_DATA mblks.  We check the db_ref count
14939 		 * of only the 1st data block in the mblk chain. There
14940 		 * doesn't seem to be a reason why a device driver would
14941 		 * send up data with varying db_ref counts in the mblk
14942 		 * chain. In any case the Fast path is a private
14943 		 * interface, and our drivers don't do such a thing.
14944 		 * Given the above assumption, there is no need to walk
14945 		 * down the entire mblk chain (which could have a
14946 		 * potential performance problem)
14947 		 *
14948 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14949 		 * to here because of exclusive ip stacks and vnics.
14950 		 * Packets transmitted from exclusive stack over vnic
14951 		 * can have db_ref > 1 and when it gets looped back to
14952 		 * another vnic in a different zone, you have ip_input()
14953 		 * getting dblks with db_ref > 1. So if someone
14954 		 * complains of TCP performance under this scenario,
14955 		 * take a serious look here on the impact of copymsg().
14956 		 */
14957 
14958 		if (DB_REF(mp) > 1) {
14959 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14960 				continue;
14961 		}
14962 
14963 		/*
14964 		 * Check and align the IP header.
14965 		 */
14966 		first_mp = mp;
14967 		if (DB_TYPE(mp) == M_DATA) {
14968 			dmp = mp;
14969 		} else if (DB_TYPE(mp) == M_PROTO &&
14970 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14971 			dmp = mp->b_cont;
14972 		} else {
14973 			dmp = NULL;
14974 		}
14975 		if (dmp != NULL) {
14976 			/*
14977 			 * IP header ptr not aligned?
14978 			 * OR IP header not complete in first mblk
14979 			 */
14980 			if (!OK_32PTR(dmp->b_rptr) ||
14981 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14982 				if (!ip_check_and_align_header(q, dmp, ipst))
14983 					continue;
14984 			}
14985 		}
14986 
14987 		/*
14988 		 * ip_input fast path
14989 		 */
14990 
14991 		/* mblk type is not M_DATA */
14992 		if (DB_TYPE(mp) != M_DATA) {
14993 			if (ip_rput_process_notdata(q, &first_mp, ill,
14994 			    &ll_multicast, &mp))
14995 				continue;
14996 
14997 			/*
14998 			 * The only way we can get here is if we had a
14999 			 * packet that was either a DL_UNITDATA_IND or
15000 			 * an M_CTL for an IPsec accelerated packet.
15001 			 *
15002 			 * In either case, the first_mp will point to
15003 			 * the leading M_PROTO or M_CTL.
15004 			 */
15005 			ASSERT(first_mp != NULL);
15006 		} else if (mhip != NULL) {
15007 			/*
15008 			 * ll_multicast is set here so that it is ready
15009 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15010 			 * manipulates ll_multicast in the same fashion when
15011 			 * called from ip_rput_process_notdata.
15012 			 */
15013 			switch (mhip->mhi_dsttype) {
15014 			case MAC_ADDRTYPE_MULTICAST :
15015 				ll_multicast = HPE_MULTICAST;
15016 				break;
15017 			case MAC_ADDRTYPE_BROADCAST :
15018 				ll_multicast = HPE_BROADCAST;
15019 				break;
15020 			default :
15021 				break;
15022 			}
15023 		}
15024 
15025 		/* Only M_DATA can come here and it is always aligned */
15026 		ASSERT(DB_TYPE(mp) == M_DATA);
15027 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15028 
15029 		ipha = (ipha_t *)mp->b_rptr;
15030 		len = mp->b_wptr - rptr;
15031 		pkt_len = ntohs(ipha->ipha_length);
15032 
15033 		/*
15034 		 * We must count all incoming packets, even if they end
15035 		 * up being dropped later on.
15036 		 */
15037 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15038 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15039 
15040 		/* multiple mblk or too short */
15041 		len -= pkt_len;
15042 		if (len != 0) {
15043 			/*
15044 			 * Make sure we have data length consistent
15045 			 * with the IP header.
15046 			 */
15047 			if (mp->b_cont == NULL) {
15048 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15049 					BUMP_MIB(ill->ill_ip_mib,
15050 					    ipIfStatsInHdrErrors);
15051 					ip2dbg(("ip_input: drop pkt\n"));
15052 					freemsg(mp);
15053 					continue;
15054 				}
15055 				mp->b_wptr = rptr + pkt_len;
15056 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15057 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15058 					BUMP_MIB(ill->ill_ip_mib,
15059 					    ipIfStatsInHdrErrors);
15060 					ip2dbg(("ip_input: drop pkt\n"));
15061 					freemsg(mp);
15062 					continue;
15063 				}
15064 				(void) adjmsg(mp, -len);
15065 				IP_STAT(ipst, ip_multimblk3);
15066 			}
15067 		}
15068 
15069 		/* Obtain the dst of the current packet */
15070 		dst = ipha->ipha_dst;
15071 
15072 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15073 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15074 		    ipha, ip6_t *, NULL, int, 0);
15075 
15076 		/*
15077 		 * The following test for loopback is faster than
15078 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15079 		 * operations.
15080 		 * Note that these addresses are always in network byte order
15081 		 */
15082 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15083 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15084 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15085 			freemsg(mp);
15086 			continue;
15087 		}
15088 
15089 		/*
15090 		 * The event for packets being received from a 'physical'
15091 		 * interface is placed after validation of the source and/or
15092 		 * destination address as being local so that packets can be
15093 		 * redirected to loopback addresses using ipnat.
15094 		 */
15095 		DTRACE_PROBE4(ip4__physical__in__start,
15096 		    ill_t *, ill, ill_t *, NULL,
15097 		    ipha_t *, ipha, mblk_t *, first_mp);
15098 
15099 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15100 		    ipst->ips_ipv4firewall_physical_in,
15101 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15102 
15103 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15104 
15105 		if (first_mp == NULL) {
15106 			continue;
15107 		}
15108 		dst = ipha->ipha_dst;
15109 		/*
15110 		 * Attach any necessary label information to
15111 		 * this packet
15112 		 */
15113 		if (is_system_labeled() &&
15114 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15115 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15116 			freemsg(mp);
15117 			continue;
15118 		}
15119 
15120 		if (ipst->ips_ipobs_enabled) {
15121 			zoneid_t dzone;
15122 
15123 			/*
15124 			 * On the inbound path the src zone will be unknown as
15125 			 * this packet has come from the wire.
15126 			 */
15127 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15128 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15129 			    ill, IPV4_VERSION, 0, ipst);
15130 		}
15131 
15132 		/*
15133 		 * Reuse the cached ire only if the ipha_dst of the previous
15134 		 * packet is the same as the current packet AND it is not
15135 		 * INADDR_ANY.
15136 		 */
15137 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15138 		    (ire != NULL)) {
15139 			ire_refrele(ire);
15140 			ire = NULL;
15141 		}
15142 
15143 		opt_len = ipha->ipha_version_and_hdr_length -
15144 		    IP_SIMPLE_HDR_VERSION;
15145 
15146 		/*
15147 		 * Check to see if we can take the fastpath.
15148 		 * That is possible if the following conditions are met
15149 		 *	o Tsol disabled
15150 		 *	o CGTP disabled
15151 		 *	o ipp_action_count is 0
15152 		 *	o no options in the packet
15153 		 *	o not a RSVP packet
15154 		 * 	o not a multicast packet
15155 		 *	o ill not in IP_DHCPINIT_IF mode
15156 		 */
15157 		if (!is_system_labeled() &&
15158 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15159 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15160 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15161 			if (ire == NULL)
15162 				ire = ire_cache_lookup_simple(dst, ipst);
15163 			/*
15164 			 * Unless forwarding is enabled, dont call
15165 			 * ip_fast_forward(). Incoming packet is for forwarding
15166 			 */
15167 			if ((ill->ill_flags & ILLF_ROUTER) &&
15168 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15169 				ire = ip_fast_forward(ire, dst, ill, mp);
15170 				continue;
15171 			}
15172 			/* incoming packet is for local consumption */
15173 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15174 				goto local;
15175 		}
15176 
15177 		/*
15178 		 * Disable ire caching for anything more complex
15179 		 * than the simple fast path case we checked for above.
15180 		 */
15181 		if (ire != NULL) {
15182 			ire_refrele(ire);
15183 			ire = NULL;
15184 		}
15185 
15186 		/*
15187 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15188 		 * server to unicast DHCP packets to a DHCP client using the
15189 		 * IP address it is offering to the client.  This can be
15190 		 * disabled through the "broadcast bit", but not all DHCP
15191 		 * servers honor that bit.  Therefore, to interoperate with as
15192 		 * many DHCP servers as possible, the DHCP client allows the
15193 		 * server to unicast, but we treat those packets as broadcast
15194 		 * here.  Note that we don't rewrite the packet itself since
15195 		 * (a) that would mess up the checksums and (b) the DHCP
15196 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15197 		 * hand it the packet regardless.
15198 		 */
15199 		if (ill->ill_dhcpinit != 0 &&
15200 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15201 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15202 			udpha_t *udpha;
15203 
15204 			/*
15205 			 * Reload ipha since pullupmsg() can change b_rptr.
15206 			 */
15207 			ipha = (ipha_t *)mp->b_rptr;
15208 			udpha = (udpha_t *)&ipha[1];
15209 
15210 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15211 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15212 				    mblk_t *, mp);
15213 				dst = INADDR_BROADCAST;
15214 			}
15215 		}
15216 
15217 		/* Full-blown slow path */
15218 		if (opt_len != 0) {
15219 			if (len != 0)
15220 				IP_STAT(ipst, ip_multimblk4);
15221 			else
15222 				IP_STAT(ipst, ip_ipoptions);
15223 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15224 			    &dst, ipst))
15225 				continue;
15226 		}
15227 
15228 		/*
15229 		 * Invoke the CGTP (multirouting) filtering module to process
15230 		 * the incoming packet. Packets identified as duplicates
15231 		 * must be discarded. Filtering is active only if the
15232 		 * the ip_cgtp_filter ndd variable is non-zero.
15233 		 */
15234 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15235 		if (ipst->ips_ip_cgtp_filter &&
15236 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15237 			netstackid_t stackid;
15238 
15239 			stackid = ipst->ips_netstack->netstack_stackid;
15240 			cgtp_flt_pkt =
15241 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15242 			    ill->ill_phyint->phyint_ifindex, mp);
15243 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15244 				freemsg(first_mp);
15245 				continue;
15246 			}
15247 		}
15248 
15249 		/*
15250 		 * If rsvpd is running, let RSVP daemon handle its processing
15251 		 * and forwarding of RSVP multicast/unicast packets.
15252 		 * If rsvpd is not running but mrouted is running, RSVP
15253 		 * multicast packets are forwarded as multicast traffic
15254 		 * and RSVP unicast packets are forwarded by unicast router.
15255 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15256 		 * packets are not forwarded, but the unicast packets are
15257 		 * forwarded like unicast traffic.
15258 		 */
15259 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15260 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15261 		    NULL) {
15262 			/* RSVP packet and rsvpd running. Treat as ours */
15263 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15264 			/*
15265 			 * This assumes that we deliver to all streams for
15266 			 * multicast and broadcast packets.
15267 			 * We have to force ll_multicast to 1 to handle the
15268 			 * M_DATA messages passed in from ip_mroute_decap.
15269 			 */
15270 			dst = INADDR_BROADCAST;
15271 			ll_multicast = 1;
15272 		} else if (CLASSD(dst)) {
15273 			/* packet is multicast */
15274 			mp->b_next = NULL;
15275 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15276 			    &ll_multicast, &dst))
15277 				continue;
15278 		}
15279 
15280 		if (ire == NULL) {
15281 			ire = ire_cache_lookup(dst, ALL_ZONES,
15282 			    msg_getlabel(mp), ipst);
15283 		}
15284 
15285 		if (ire != NULL && ire->ire_stq != NULL &&
15286 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15287 		    ire->ire_zoneid != ALL_ZONES) {
15288 			/*
15289 			 * Should only use IREs that are visible from the
15290 			 * global zone for forwarding.
15291 			 */
15292 			ire_refrele(ire);
15293 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15294 			    msg_getlabel(mp), ipst);
15295 		}
15296 
15297 		if (ire == NULL) {
15298 			/*
15299 			 * No IRE for this destination, so it can't be for us.
15300 			 * Unless we are forwarding, drop the packet.
15301 			 * We have to let source routed packets through
15302 			 * since we don't yet know if they are 'ping -l'
15303 			 * packets i.e. if they will go out over the
15304 			 * same interface as they came in on.
15305 			 */
15306 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15307 			if (ire == NULL)
15308 				continue;
15309 		}
15310 
15311 		/*
15312 		 * Broadcast IRE may indicate either broadcast or
15313 		 * multicast packet
15314 		 */
15315 		if (ire->ire_type == IRE_BROADCAST) {
15316 			/*
15317 			 * Skip broadcast checks if packet is UDP multicast;
15318 			 * we'd rather not enter ip_rput_process_broadcast()
15319 			 * unless the packet is broadcast for real, since
15320 			 * that routine is a no-op for multicast.
15321 			 */
15322 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15323 			    !CLASSD(ipha->ipha_dst)) {
15324 				ire = ip_rput_process_broadcast(&q, mp,
15325 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15326 				    ll_multicast);
15327 				if (ire == NULL)
15328 					continue;
15329 			}
15330 		} else if (ire->ire_stq != NULL) {
15331 			/* fowarding? */
15332 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15333 			    ll_multicast, B_FALSE);
15334 			/* ip_rput_process_forward consumed the packet */
15335 			continue;
15336 		}
15337 
15338 local:
15339 		/*
15340 		 * If the queue in the ire is different to the ingress queue
15341 		 * then we need to check to see if we can accept the packet.
15342 		 * Note that for multicast packets and broadcast packets sent
15343 		 * to a broadcast address which is shared between multiple
15344 		 * interfaces we should not do this since we just got a random
15345 		 * broadcast ire.
15346 		 */
15347 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15348 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15349 			if (ire == NULL) {
15350 				/* Drop packet */
15351 				BUMP_MIB(ill->ill_ip_mib,
15352 				    ipIfStatsForwProhibits);
15353 				freemsg(mp);
15354 				continue;
15355 			}
15356 			if (ire->ire_rfq != NULL)
15357 				q = ire->ire_rfq;
15358 		}
15359 
15360 		switch (ipha->ipha_protocol) {
15361 		case IPPROTO_TCP:
15362 			ASSERT(first_mp == mp);
15363 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15364 			    mp, 0, q, ip_ring)) != NULL) {
15365 				if (curr_sqp == NULL) {
15366 					curr_sqp = GET_SQUEUE(mp);
15367 					ASSERT(cnt == 0);
15368 					cnt++;
15369 					head = tail = mp;
15370 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15371 					ASSERT(tail != NULL);
15372 					cnt++;
15373 					tail->b_next = mp;
15374 					tail = mp;
15375 				} else {
15376 					/*
15377 					 * A different squeue. Send the
15378 					 * chain for the previous squeue on
15379 					 * its way. This shouldn't happen
15380 					 * often unless interrupt binding
15381 					 * changes.
15382 					 */
15383 					IP_STAT(ipst, ip_input_multi_squeue);
15384 					SQUEUE_ENTER(curr_sqp, head,
15385 					    tail, cnt, SQ_PROCESS, tag);
15386 					curr_sqp = GET_SQUEUE(mp);
15387 					head = mp;
15388 					tail = mp;
15389 					cnt = 1;
15390 				}
15391 			}
15392 			continue;
15393 		case IPPROTO_UDP:
15394 			ASSERT(first_mp == mp);
15395 			ip_udp_input(q, mp, ipha, ire, ill);
15396 			continue;
15397 		case IPPROTO_SCTP:
15398 			ASSERT(first_mp == mp);
15399 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15400 			    q, dst);
15401 			/* ire has been released by ip_sctp_input */
15402 			ire = NULL;
15403 			continue;
15404 		default:
15405 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15406 			continue;
15407 		}
15408 	}
15409 
15410 	if (ire != NULL)
15411 		ire_refrele(ire);
15412 
15413 	if (head != NULL)
15414 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15415 
15416 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15417 	    "ip_input_end: q %p (%S)", q, "end");
15418 #undef  rptr
15419 }
15420 
15421 /*
15422  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15423  * a chain of packets in the poll mode. The packets have gone through the
15424  * data link processing but not IP processing. For performance and latency
15425  * reasons, the squeue wants to process the chain in line instead of feeding
15426  * it back via ip_input path.
15427  *
15428  * So this is a light weight function which checks to see if the packets
15429  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15430  * but we still do the paranoid check) meant for local machine and we don't
15431  * have labels etc enabled. Packets that meet the criterion are returned to
15432  * the squeue and processed inline while the rest go via ip_input path.
15433  */
15434 /*ARGSUSED*/
15435 mblk_t *
15436 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15437     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15438 {
15439 	mblk_t 		*mp;
15440 	ipaddr_t	dst = NULL;
15441 	ipaddr_t	prev_dst;
15442 	ire_t		*ire = NULL;
15443 	ipha_t		*ipha;
15444 	uint_t		pkt_len;
15445 	ssize_t		len;
15446 	uint_t		opt_len;
15447 	queue_t		*q = ill->ill_rq;
15448 	squeue_t	*curr_sqp;
15449 	mblk_t 		*ahead = NULL;	/* Accepted head */
15450 	mblk_t		*atail = NULL;	/* Accepted tail */
15451 	uint_t		acnt = 0;	/* Accepted count */
15452 	mblk_t		*utail = NULL;	/* Unaccepted head */
15453 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15454 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15455 	ip_stack_t	*ipst = ill->ill_ipst;
15456 
15457 	*cnt = 0;
15458 
15459 	ASSERT(ill != NULL);
15460 	ASSERT(ip_ring != NULL);
15461 
15462 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15463 
15464 #define	rptr	((uchar_t *)ipha)
15465 
15466 	while (mp_chain != NULL) {
15467 		mp = mp_chain;
15468 		mp_chain = mp_chain->b_next;
15469 		mp->b_next = NULL;
15470 
15471 		/*
15472 		 * We do ire caching from one iteration to
15473 		 * another. In the event the packet chain contains
15474 		 * all packets from the same dst, this caching saves
15475 		 * an ire_cache_lookup for each of the succeeding
15476 		 * packets in a packet chain.
15477 		 */
15478 		prev_dst = dst;
15479 
15480 		ipha = (ipha_t *)mp->b_rptr;
15481 		len = mp->b_wptr - rptr;
15482 
15483 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15484 
15485 		/*
15486 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15487 		 * or doesn't have min len, reject.
15488 		 */
15489 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15490 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15491 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15492 			continue;
15493 		}
15494 
15495 		pkt_len = ntohs(ipha->ipha_length);
15496 		if (len != pkt_len) {
15497 			if (len > pkt_len) {
15498 				mp->b_wptr = rptr + pkt_len;
15499 			} else {
15500 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15501 				continue;
15502 			}
15503 		}
15504 
15505 		opt_len = ipha->ipha_version_and_hdr_length -
15506 		    IP_SIMPLE_HDR_VERSION;
15507 		dst = ipha->ipha_dst;
15508 
15509 		/* IP version bad or there are IP options */
15510 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15511 		    mp, &ipha, &dst, ipst)))
15512 			continue;
15513 
15514 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15515 		    (ipst->ips_ip_cgtp_filter &&
15516 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15517 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15518 			continue;
15519 		}
15520 
15521 		/*
15522 		 * Reuse the cached ire only if the ipha_dst of the previous
15523 		 * packet is the same as the current packet AND it is not
15524 		 * INADDR_ANY.
15525 		 */
15526 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15527 		    (ire != NULL)) {
15528 			ire_refrele(ire);
15529 			ire = NULL;
15530 		}
15531 
15532 		if (ire == NULL)
15533 			ire = ire_cache_lookup_simple(dst, ipst);
15534 
15535 		/*
15536 		 * Unless forwarding is enabled, dont call
15537 		 * ip_fast_forward(). Incoming packet is for forwarding
15538 		 */
15539 		if ((ill->ill_flags & ILLF_ROUTER) &&
15540 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15541 
15542 			DTRACE_PROBE4(ip4__physical__in__start,
15543 			    ill_t *, ill, ill_t *, NULL,
15544 			    ipha_t *, ipha, mblk_t *, mp);
15545 
15546 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15547 			    ipst->ips_ipv4firewall_physical_in,
15548 			    ill, NULL, ipha, mp, mp, 0, ipst);
15549 
15550 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15551 
15552 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15553 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15554 			    pkt_len);
15555 
15556 			if (mp != NULL)
15557 				ire = ip_fast_forward(ire, dst, ill, mp);
15558 			continue;
15559 		}
15560 
15561 		/* incoming packet is for local consumption */
15562 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15563 			goto local_accept;
15564 
15565 		/*
15566 		 * Disable ire caching for anything more complex
15567 		 * than the simple fast path case we checked for above.
15568 		 */
15569 		if (ire != NULL) {
15570 			ire_refrele(ire);
15571 			ire = NULL;
15572 		}
15573 
15574 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15575 		    ipst);
15576 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15577 		    ire->ire_stq != NULL) {
15578 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15579 			if (ire != NULL) {
15580 				ire_refrele(ire);
15581 				ire = NULL;
15582 			}
15583 			continue;
15584 		}
15585 
15586 local_accept:
15587 
15588 		if (ire->ire_rfq != q) {
15589 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15590 			if (ire != NULL) {
15591 				ire_refrele(ire);
15592 				ire = NULL;
15593 			}
15594 			continue;
15595 		}
15596 
15597 		/*
15598 		 * The event for packets being received from a 'physical'
15599 		 * interface is placed after validation of the source and/or
15600 		 * destination address as being local so that packets can be
15601 		 * redirected to loopback addresses using ipnat.
15602 		 */
15603 		DTRACE_PROBE4(ip4__physical__in__start,
15604 		    ill_t *, ill, ill_t *, NULL,
15605 		    ipha_t *, ipha, mblk_t *, mp);
15606 
15607 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15608 		    ipst->ips_ipv4firewall_physical_in,
15609 		    ill, NULL, ipha, mp, mp, 0, ipst);
15610 
15611 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15612 
15613 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15614 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15615 
15616 		if (mp != NULL &&
15617 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15618 		    0, q, ip_ring)) != NULL) {
15619 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15620 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15621 			} else {
15622 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15623 				    SQ_FILL, SQTAG_IP_INPUT);
15624 			}
15625 		}
15626 	}
15627 
15628 	if (ire != NULL)
15629 		ire_refrele(ire);
15630 
15631 	if (uhead != NULL)
15632 		ip_input(ill, ip_ring, uhead, NULL);
15633 
15634 	if (ahead != NULL) {
15635 		*last = atail;
15636 		*cnt = acnt;
15637 		return (ahead);
15638 	}
15639 
15640 	return (NULL);
15641 #undef  rptr
15642 }
15643 
15644 static void
15645 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15646     t_uscalar_t err)
15647 {
15648 	if (dl_err == DL_SYSERR) {
15649 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15650 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15651 		    ill->ill_name, dl_primstr(prim), err);
15652 		return;
15653 	}
15654 
15655 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15656 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15657 	    dl_errstr(dl_err));
15658 }
15659 
15660 /*
15661  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15662  * than DL_UNITDATA_IND messages. If we need to process this message
15663  * exclusively, we call qwriter_ip, in which case we also need to call
15664  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15665  */
15666 void
15667 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15668 {
15669 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15670 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15671 	ill_t		*ill = q->q_ptr;
15672 	t_uscalar_t	prim = dloa->dl_primitive;
15673 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15674 
15675 	ip1dbg(("ip_rput_dlpi"));
15676 
15677 	/*
15678 	 * If we received an ACK but didn't send a request for it, then it
15679 	 * can't be part of any pending operation; discard up-front.
15680 	 */
15681 	switch (prim) {
15682 	case DL_ERROR_ACK:
15683 		reqprim = dlea->dl_error_primitive;
15684 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15685 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15686 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15687 		    dlea->dl_unix_errno));
15688 		break;
15689 	case DL_OK_ACK:
15690 		reqprim = dloa->dl_correct_primitive;
15691 		break;
15692 	case DL_INFO_ACK:
15693 		reqprim = DL_INFO_REQ;
15694 		break;
15695 	case DL_BIND_ACK:
15696 		reqprim = DL_BIND_REQ;
15697 		break;
15698 	case DL_PHYS_ADDR_ACK:
15699 		reqprim = DL_PHYS_ADDR_REQ;
15700 		break;
15701 	case DL_NOTIFY_ACK:
15702 		reqprim = DL_NOTIFY_REQ;
15703 		break;
15704 	case DL_CONTROL_ACK:
15705 		reqprim = DL_CONTROL_REQ;
15706 		break;
15707 	case DL_CAPABILITY_ACK:
15708 		reqprim = DL_CAPABILITY_REQ;
15709 		break;
15710 	}
15711 
15712 	if (prim != DL_NOTIFY_IND) {
15713 		if (reqprim == DL_PRIM_INVAL ||
15714 		    !ill_dlpi_pending(ill, reqprim)) {
15715 			/* Not a DLPI message we support or expected */
15716 			freemsg(mp);
15717 			return;
15718 		}
15719 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15720 		    dl_primstr(reqprim)));
15721 	}
15722 
15723 	switch (reqprim) {
15724 	case DL_UNBIND_REQ:
15725 		/*
15726 		 * NOTE: we mark the unbind as complete even if we got a
15727 		 * DL_ERROR_ACK, since there's not much else we can do.
15728 		 */
15729 		mutex_enter(&ill->ill_lock);
15730 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15731 		cv_signal(&ill->ill_cv);
15732 		mutex_exit(&ill->ill_lock);
15733 		break;
15734 
15735 	case DL_ENABMULTI_REQ:
15736 		if (prim == DL_OK_ACK) {
15737 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15738 				ill->ill_dlpi_multicast_state = IDS_OK;
15739 		}
15740 		break;
15741 	}
15742 
15743 	/*
15744 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15745 	 * need to become writer to continue to process it.  Because an
15746 	 * exclusive operation doesn't complete until replies to all queued
15747 	 * DLPI messages have been received, we know we're in the middle of an
15748 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15749 	 *
15750 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15751 	 * Since this is on the ill stream we unconditionally bump up the
15752 	 * refcount without doing ILL_CAN_LOOKUP().
15753 	 */
15754 	ill_refhold(ill);
15755 	if (prim == DL_NOTIFY_IND)
15756 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15757 	else
15758 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15759 }
15760 
15761 /*
15762  * Handling of DLPI messages that require exclusive access to the ipsq.
15763  *
15764  * Need to do ill_pending_mp_release on ioctl completion, which could
15765  * happen here. (along with mi_copy_done)
15766  */
15767 /* ARGSUSED */
15768 static void
15769 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15770 {
15771 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15772 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15773 	int		err = 0;
15774 	ill_t		*ill;
15775 	ipif_t		*ipif = NULL;
15776 	mblk_t		*mp1 = NULL;
15777 	conn_t		*connp = NULL;
15778 	t_uscalar_t	paddrreq;
15779 	mblk_t		*mp_hw;
15780 	boolean_t	success;
15781 	boolean_t	ioctl_aborted = B_FALSE;
15782 	boolean_t	log = B_TRUE;
15783 	ip_stack_t		*ipst;
15784 
15785 	ip1dbg(("ip_rput_dlpi_writer .."));
15786 	ill = (ill_t *)q->q_ptr;
15787 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15788 	ASSERT(IAM_WRITER_ILL(ill));
15789 
15790 	ipst = ill->ill_ipst;
15791 
15792 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15793 	/*
15794 	 * The current ioctl could have been aborted by the user and a new
15795 	 * ioctl to bring up another ill could have started. We could still
15796 	 * get a response from the driver later.
15797 	 */
15798 	if (ipif != NULL && ipif->ipif_ill != ill)
15799 		ioctl_aborted = B_TRUE;
15800 
15801 	switch (dloa->dl_primitive) {
15802 	case DL_ERROR_ACK:
15803 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15804 		    dl_primstr(dlea->dl_error_primitive)));
15805 
15806 		switch (dlea->dl_error_primitive) {
15807 		case DL_DISABMULTI_REQ:
15808 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15809 			break;
15810 		case DL_PROMISCON_REQ:
15811 		case DL_PROMISCOFF_REQ:
15812 		case DL_UNBIND_REQ:
15813 		case DL_ATTACH_REQ:
15814 		case DL_INFO_REQ:
15815 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15816 			break;
15817 		case DL_NOTIFY_REQ:
15818 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15819 			log = B_FALSE;
15820 			break;
15821 		case DL_PHYS_ADDR_REQ:
15822 			/*
15823 			 * For IPv6 only, there are two additional
15824 			 * phys_addr_req's sent to the driver to get the
15825 			 * IPv6 token and lla. This allows IP to acquire
15826 			 * the hardware address format for a given interface
15827 			 * without having built in knowledge of the hardware
15828 			 * address. ill_phys_addr_pend keeps track of the last
15829 			 * DL_PAR sent so we know which response we are
15830 			 * dealing with. ill_dlpi_done will update
15831 			 * ill_phys_addr_pend when it sends the next req.
15832 			 * We don't complete the IOCTL until all three DL_PARs
15833 			 * have been attempted, so set *_len to 0 and break.
15834 			 */
15835 			paddrreq = ill->ill_phys_addr_pend;
15836 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15837 			if (paddrreq == DL_IPV6_TOKEN) {
15838 				ill->ill_token_length = 0;
15839 				log = B_FALSE;
15840 				break;
15841 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15842 				ill->ill_nd_lla_len = 0;
15843 				log = B_FALSE;
15844 				break;
15845 			}
15846 			/*
15847 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15848 			 * We presumably have an IOCTL hanging out waiting
15849 			 * for completion. Find it and complete the IOCTL
15850 			 * with the error noted.
15851 			 * However, ill_dl_phys was called on an ill queue
15852 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15853 			 * set. But the ioctl is known to be pending on ill_wq.
15854 			 */
15855 			if (!ill->ill_ifname_pending)
15856 				break;
15857 			ill->ill_ifname_pending = 0;
15858 			if (!ioctl_aborted)
15859 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15860 			if (mp1 != NULL) {
15861 				/*
15862 				 * This operation (SIOCSLIFNAME) must have
15863 				 * happened on the ill. Assert there is no conn
15864 				 */
15865 				ASSERT(connp == NULL);
15866 				q = ill->ill_wq;
15867 			}
15868 			break;
15869 		case DL_BIND_REQ:
15870 			ill_dlpi_done(ill, DL_BIND_REQ);
15871 			if (ill->ill_ifname_pending)
15872 				break;
15873 			/*
15874 			 * Something went wrong with the bind.  We presumably
15875 			 * have an IOCTL hanging out waiting for completion.
15876 			 * Find it, take down the interface that was coming
15877 			 * up, and complete the IOCTL with the error noted.
15878 			 */
15879 			if (!ioctl_aborted)
15880 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15881 			if (mp1 != NULL) {
15882 				/*
15883 				 * This might be a result of a DL_NOTE_REPLUMB
15884 				 * notification. In that case, connp is NULL.
15885 				 */
15886 				if (connp != NULL)
15887 					q = CONNP_TO_WQ(connp);
15888 
15889 				(void) ipif_down(ipif, NULL, NULL);
15890 				/* error is set below the switch */
15891 			}
15892 			break;
15893 		case DL_ENABMULTI_REQ:
15894 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15895 
15896 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15897 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15898 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15899 				ipif_t *ipif;
15900 
15901 				printf("ip: joining multicasts failed (%d)"
15902 				    " on %s - will use link layer "
15903 				    "broadcasts for multicast\n",
15904 				    dlea->dl_errno, ill->ill_name);
15905 
15906 				/*
15907 				 * Set up the multicast mapping alone.
15908 				 * writer, so ok to access ill->ill_ipif
15909 				 * without any lock.
15910 				 */
15911 				ipif = ill->ill_ipif;
15912 				mutex_enter(&ill->ill_phyint->phyint_lock);
15913 				ill->ill_phyint->phyint_flags |=
15914 				    PHYI_MULTI_BCAST;
15915 				mutex_exit(&ill->ill_phyint->phyint_lock);
15916 
15917 				if (!ill->ill_isv6) {
15918 					(void) ipif_arp_setup_multicast(ipif,
15919 					    NULL);
15920 				} else {
15921 					(void) ipif_ndp_setup_multicast(ipif,
15922 					    NULL);
15923 				}
15924 			}
15925 			freemsg(mp);	/* Don't want to pass this up */
15926 			return;
15927 		case DL_CONTROL_REQ:
15928 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15929 			    "DL_CONTROL_REQ\n"));
15930 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15931 			freemsg(mp);
15932 			return;
15933 		case DL_CAPABILITY_REQ:
15934 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15935 			    "DL_CAPABILITY REQ\n"));
15936 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15937 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15938 			ill_capability_done(ill);
15939 			freemsg(mp);
15940 			return;
15941 		}
15942 		/*
15943 		 * Note the error for IOCTL completion (mp1 is set when
15944 		 * ready to complete ioctl). If ill_ifname_pending_err is
15945 		 * set, an error occured during plumbing (ill_ifname_pending),
15946 		 * so we want to report that error.
15947 		 *
15948 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15949 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15950 		 * expected to get errack'd if the driver doesn't support
15951 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15952 		 * if these error conditions are encountered.
15953 		 */
15954 		if (mp1 != NULL) {
15955 			if (ill->ill_ifname_pending_err != 0)  {
15956 				err = ill->ill_ifname_pending_err;
15957 				ill->ill_ifname_pending_err = 0;
15958 			} else {
15959 				err = dlea->dl_unix_errno ?
15960 				    dlea->dl_unix_errno : ENXIO;
15961 			}
15962 		/*
15963 		 * If we're plumbing an interface and an error hasn't already
15964 		 * been saved, set ill_ifname_pending_err to the error passed
15965 		 * up. Ignore the error if log is B_FALSE (see comment above).
15966 		 */
15967 		} else if (log && ill->ill_ifname_pending &&
15968 		    ill->ill_ifname_pending_err == 0) {
15969 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15970 			    dlea->dl_unix_errno : ENXIO;
15971 		}
15972 
15973 		if (log)
15974 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15975 			    dlea->dl_errno, dlea->dl_unix_errno);
15976 		break;
15977 	case DL_CAPABILITY_ACK:
15978 		ill_capability_ack(ill, mp);
15979 		/*
15980 		 * The message has been handed off to ill_capability_ack
15981 		 * and must not be freed below
15982 		 */
15983 		mp = NULL;
15984 		break;
15985 
15986 	case DL_CONTROL_ACK:
15987 		/* We treat all of these as "fire and forget" */
15988 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15989 		break;
15990 	case DL_INFO_ACK:
15991 		/* Call a routine to handle this one. */
15992 		ill_dlpi_done(ill, DL_INFO_REQ);
15993 		ip_ll_subnet_defaults(ill, mp);
15994 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15995 		return;
15996 	case DL_BIND_ACK:
15997 		/*
15998 		 * We should have an IOCTL waiting on this unless
15999 		 * sent by ill_dl_phys, in which case just return
16000 		 */
16001 		ill_dlpi_done(ill, DL_BIND_REQ);
16002 		if (ill->ill_ifname_pending)
16003 			break;
16004 
16005 		if (!ioctl_aborted)
16006 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16007 		if (mp1 == NULL)
16008 			break;
16009 		/*
16010 		 * mp1 was added by ill_dl_up(). if that is a result of
16011 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
16012 		 */
16013 		if (connp != NULL)
16014 			q = CONNP_TO_WQ(connp);
16015 
16016 		/*
16017 		 * We are exclusive. So nothing can change even after
16018 		 * we get the pending mp. If need be we can put it back
16019 		 * and restart, as in calling ipif_arp_up()  below.
16020 		 */
16021 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16022 
16023 		mutex_enter(&ill->ill_lock);
16024 		ill->ill_dl_up = 1;
16025 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16026 		mutex_exit(&ill->ill_lock);
16027 
16028 		/*
16029 		 * Now bring up the resolver; when that is complete, we'll
16030 		 * create IREs.  Note that we intentionally mirror what
16031 		 * ipif_up() would have done, because we got here by way of
16032 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16033 		 */
16034 		if (ill->ill_isv6) {
16035 			if (ill->ill_flags & ILLF_XRESOLV) {
16036 				if (connp != NULL)
16037 					mutex_enter(&connp->conn_lock);
16038 				mutex_enter(&ill->ill_lock);
16039 				success = ipsq_pending_mp_add(connp, ipif, q,
16040 				    mp1, 0);
16041 				mutex_exit(&ill->ill_lock);
16042 				if (connp != NULL)
16043 					mutex_exit(&connp->conn_lock);
16044 				if (success) {
16045 					err = ipif_resolver_up(ipif,
16046 					    Res_act_initial);
16047 					if (err == EINPROGRESS) {
16048 						freemsg(mp);
16049 						return;
16050 					}
16051 					ASSERT(err != 0);
16052 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16053 					ASSERT(mp1 != NULL);
16054 				} else {
16055 					/* conn has started closing */
16056 					err = EINTR;
16057 				}
16058 			} else { /* Non XRESOLV interface */
16059 				(void) ipif_resolver_up(ipif, Res_act_initial);
16060 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16061 					err = ipif_up_done_v6(ipif);
16062 			}
16063 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16064 			/*
16065 			 * ARP and other v4 external resolvers.
16066 			 * Leave the pending mblk intact so that
16067 			 * the ioctl completes in ip_rput().
16068 			 */
16069 			if (connp != NULL)
16070 				mutex_enter(&connp->conn_lock);
16071 			mutex_enter(&ill->ill_lock);
16072 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16073 			mutex_exit(&ill->ill_lock);
16074 			if (connp != NULL)
16075 				mutex_exit(&connp->conn_lock);
16076 			if (success) {
16077 				err = ipif_resolver_up(ipif, Res_act_initial);
16078 				if (err == EINPROGRESS) {
16079 					freemsg(mp);
16080 					return;
16081 				}
16082 				ASSERT(err != 0);
16083 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16084 			} else {
16085 				/* The conn has started closing */
16086 				err = EINTR;
16087 			}
16088 		} else {
16089 			/*
16090 			 * This one is complete. Reply to pending ioctl.
16091 			 */
16092 			(void) ipif_resolver_up(ipif, Res_act_initial);
16093 			err = ipif_up_done(ipif);
16094 		}
16095 
16096 		if ((err == 0) && (ill->ill_up_ipifs)) {
16097 			err = ill_up_ipifs(ill, q, mp1);
16098 			if (err == EINPROGRESS) {
16099 				freemsg(mp);
16100 				return;
16101 			}
16102 		}
16103 
16104 		/*
16105 		 * If we have a moved ipif to bring up, and everything has
16106 		 * succeeded to this point, bring it up on the IPMP ill.
16107 		 * Otherwise, leave it down -- the admin can try to bring it
16108 		 * up by hand if need be.
16109 		 */
16110 		if (ill->ill_move_ipif != NULL) {
16111 			if (err != 0) {
16112 				ill->ill_move_ipif = NULL;
16113 			} else {
16114 				ipif = ill->ill_move_ipif;
16115 				ill->ill_move_ipif = NULL;
16116 				err = ipif_up(ipif, q, mp1);
16117 				if (err == EINPROGRESS) {
16118 					freemsg(mp);
16119 					return;
16120 				}
16121 			}
16122 		}
16123 		break;
16124 
16125 	case DL_NOTIFY_IND: {
16126 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16127 		ire_t *ire;
16128 		uint_t orig_mtu;
16129 		boolean_t need_ire_walk_v4 = B_FALSE;
16130 		boolean_t need_ire_walk_v6 = B_FALSE;
16131 
16132 		switch (notify->dl_notification) {
16133 		case DL_NOTE_PHYS_ADDR:
16134 			err = ill_set_phys_addr(ill, mp);
16135 			break;
16136 
16137 		case DL_NOTE_REPLUMB:
16138 			/*
16139 			 * Directly return after calling ill_replumb().
16140 			 * Note that we should not free mp as it is reused
16141 			 * in the ill_replumb() function.
16142 			 */
16143 			err = ill_replumb(ill, mp);
16144 			return;
16145 
16146 		case DL_NOTE_FASTPATH_FLUSH:
16147 			ill_fastpath_flush(ill);
16148 			break;
16149 
16150 		case DL_NOTE_SDU_SIZE:
16151 			/*
16152 			 * Change the MTU size of the interface, of all
16153 			 * attached ipif's, and of all relevant ire's.  The
16154 			 * new value's a uint32_t at notify->dl_data.
16155 			 * Mtu change Vs. new ire creation - protocol below.
16156 			 *
16157 			 * a Mark the ipif as IPIF_CHANGING.
16158 			 * b Set the new mtu in the ipif.
16159 			 * c Change the ire_max_frag on all affected ires
16160 			 * d Unmark the IPIF_CHANGING
16161 			 *
16162 			 * To see how the protocol works, assume an interface
16163 			 * route is also being added simultaneously by
16164 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16165 			 * the ire. If the ire is created before step a,
16166 			 * it will be cleaned up by step c. If the ire is
16167 			 * created after step d, it will see the new value of
16168 			 * ipif_mtu. Any attempt to create the ire between
16169 			 * steps a to d will fail because of the IPIF_CHANGING
16170 			 * flag. Note that ire_create() is passed a pointer to
16171 			 * the ipif_mtu, and not the value. During ire_add
16172 			 * under the bucket lock, the ire_max_frag of the
16173 			 * new ire being created is set from the ipif/ire from
16174 			 * which it is being derived.
16175 			 */
16176 			mutex_enter(&ill->ill_lock);
16177 
16178 			orig_mtu = ill->ill_max_mtu;
16179 			ill->ill_max_frag = (uint_t)notify->dl_data;
16180 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16181 
16182 			/*
16183 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16184 			 * clamp ill_max_mtu at it.
16185 			 */
16186 			if (ill->ill_user_mtu != 0 &&
16187 			    ill->ill_user_mtu < ill->ill_max_mtu)
16188 				ill->ill_max_mtu = ill->ill_user_mtu;
16189 
16190 			/*
16191 			 * If the MTU is unchanged, we're done.
16192 			 */
16193 			if (orig_mtu == ill->ill_max_mtu) {
16194 				mutex_exit(&ill->ill_lock);
16195 				break;
16196 			}
16197 
16198 			if (ill->ill_isv6) {
16199 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16200 					ill->ill_max_mtu = IPV6_MIN_MTU;
16201 			} else {
16202 				if (ill->ill_max_mtu < IP_MIN_MTU)
16203 					ill->ill_max_mtu = IP_MIN_MTU;
16204 			}
16205 			for (ipif = ill->ill_ipif; ipif != NULL;
16206 			    ipif = ipif->ipif_next) {
16207 				/*
16208 				 * Don't override the mtu if the user
16209 				 * has explicitly set it.
16210 				 */
16211 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16212 					continue;
16213 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16214 				if (ipif->ipif_isv6)
16215 					ire = ipif_to_ire_v6(ipif);
16216 				else
16217 					ire = ipif_to_ire(ipif);
16218 				if (ire != NULL) {
16219 					ire->ire_max_frag = ipif->ipif_mtu;
16220 					ire_refrele(ire);
16221 				}
16222 				if (ipif->ipif_flags & IPIF_UP) {
16223 					if (ill->ill_isv6)
16224 						need_ire_walk_v6 = B_TRUE;
16225 					else
16226 						need_ire_walk_v4 = B_TRUE;
16227 				}
16228 			}
16229 			mutex_exit(&ill->ill_lock);
16230 			if (need_ire_walk_v4)
16231 				ire_walk_v4(ill_mtu_change, (char *)ill,
16232 				    ALL_ZONES, ipst);
16233 			if (need_ire_walk_v6)
16234 				ire_walk_v6(ill_mtu_change, (char *)ill,
16235 				    ALL_ZONES, ipst);
16236 
16237 			/*
16238 			 * Refresh IPMP meta-interface MTU if necessary.
16239 			 */
16240 			if (IS_UNDER_IPMP(ill))
16241 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16242 			break;
16243 
16244 		case DL_NOTE_LINK_UP:
16245 		case DL_NOTE_LINK_DOWN: {
16246 			/*
16247 			 * We are writer. ill / phyint / ipsq assocs stable.
16248 			 * The RUNNING flag reflects the state of the link.
16249 			 */
16250 			phyint_t *phyint = ill->ill_phyint;
16251 			uint64_t new_phyint_flags;
16252 			boolean_t changed = B_FALSE;
16253 			boolean_t went_up;
16254 
16255 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16256 			mutex_enter(&phyint->phyint_lock);
16257 
16258 			new_phyint_flags = went_up ?
16259 			    phyint->phyint_flags | PHYI_RUNNING :
16260 			    phyint->phyint_flags & ~PHYI_RUNNING;
16261 
16262 			if (IS_IPMP(ill)) {
16263 				new_phyint_flags = went_up ?
16264 				    new_phyint_flags & ~PHYI_FAILED :
16265 				    new_phyint_flags | PHYI_FAILED;
16266 			}
16267 
16268 			if (new_phyint_flags != phyint->phyint_flags) {
16269 				phyint->phyint_flags = new_phyint_flags;
16270 				changed = B_TRUE;
16271 			}
16272 			mutex_exit(&phyint->phyint_lock);
16273 			/*
16274 			 * ill_restart_dad handles the DAD restart and routing
16275 			 * socket notification logic.
16276 			 */
16277 			if (changed) {
16278 				ill_restart_dad(phyint->phyint_illv4, went_up);
16279 				ill_restart_dad(phyint->phyint_illv6, went_up);
16280 			}
16281 			break;
16282 		}
16283 		case DL_NOTE_PROMISC_ON_PHYS:
16284 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16285 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16286 			mutex_enter(&ill->ill_lock);
16287 			ill->ill_promisc_on_phys = B_TRUE;
16288 			mutex_exit(&ill->ill_lock);
16289 			break;
16290 		case DL_NOTE_PROMISC_OFF_PHYS:
16291 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16292 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16293 			mutex_enter(&ill->ill_lock);
16294 			ill->ill_promisc_on_phys = B_FALSE;
16295 			mutex_exit(&ill->ill_lock);
16296 			break;
16297 		case DL_NOTE_CAPAB_RENEG:
16298 			/*
16299 			 * Something changed on the driver side.
16300 			 * It wants us to renegotiate the capabilities
16301 			 * on this ill. One possible cause is the aggregation
16302 			 * interface under us where a port got added or
16303 			 * went away.
16304 			 *
16305 			 * If the capability negotiation is already done
16306 			 * or is in progress, reset the capabilities and
16307 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16308 			 * so that when the ack comes back, we can start
16309 			 * the renegotiation process.
16310 			 *
16311 			 * Note that if ill_capab_reneg is already B_TRUE
16312 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16313 			 * the capability resetting request has been sent
16314 			 * and the renegotiation has not been started yet;
16315 			 * nothing needs to be done in this case.
16316 			 */
16317 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16318 			ill_capability_reset(ill, B_TRUE);
16319 			ipsq_current_finish(ipsq);
16320 			break;
16321 		default:
16322 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16323 			    "type 0x%x for DL_NOTIFY_IND\n",
16324 			    notify->dl_notification));
16325 			break;
16326 		}
16327 
16328 		/*
16329 		 * As this is an asynchronous operation, we
16330 		 * should not call ill_dlpi_done
16331 		 */
16332 		break;
16333 	}
16334 	case DL_NOTIFY_ACK: {
16335 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16336 
16337 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16338 			ill->ill_note_link = 1;
16339 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16340 		break;
16341 	}
16342 	case DL_PHYS_ADDR_ACK: {
16343 		/*
16344 		 * As part of plumbing the interface via SIOCSLIFNAME,
16345 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16346 		 * whose answers we receive here.  As each answer is received,
16347 		 * we call ill_dlpi_done() to dispatch the next request as
16348 		 * we're processing the current one.  Once all answers have
16349 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16350 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16351 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16352 		 * available, but we know the ioctl is pending on ill_wq.)
16353 		 */
16354 		uint_t	paddrlen, paddroff;
16355 
16356 		paddrreq = ill->ill_phys_addr_pend;
16357 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16358 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16359 
16360 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16361 		if (paddrreq == DL_IPV6_TOKEN) {
16362 			/*
16363 			 * bcopy to low-order bits of ill_token
16364 			 *
16365 			 * XXX Temporary hack - currently, all known tokens
16366 			 * are 64 bits, so I'll cheat for the moment.
16367 			 */
16368 			bcopy(mp->b_rptr + paddroff,
16369 			    &ill->ill_token.s6_addr32[2], paddrlen);
16370 			ill->ill_token_length = paddrlen;
16371 			break;
16372 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16373 			ASSERT(ill->ill_nd_lla_mp == NULL);
16374 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16375 			mp = NULL;
16376 			break;
16377 		}
16378 
16379 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16380 		ASSERT(ill->ill_phys_addr_mp == NULL);
16381 		if (!ill->ill_ifname_pending)
16382 			break;
16383 		ill->ill_ifname_pending = 0;
16384 		if (!ioctl_aborted)
16385 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16386 		if (mp1 != NULL) {
16387 			ASSERT(connp == NULL);
16388 			q = ill->ill_wq;
16389 		}
16390 		/*
16391 		 * If any error acks received during the plumbing sequence,
16392 		 * ill_ifname_pending_err will be set. Break out and send up
16393 		 * the error to the pending ioctl.
16394 		 */
16395 		if (ill->ill_ifname_pending_err != 0) {
16396 			err = ill->ill_ifname_pending_err;
16397 			ill->ill_ifname_pending_err = 0;
16398 			break;
16399 		}
16400 
16401 		ill->ill_phys_addr_mp = mp;
16402 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16403 		mp = NULL;
16404 
16405 		/*
16406 		 * If paddrlen is zero, the DLPI provider doesn't support
16407 		 * physical addresses.  The other two tests were historical
16408 		 * workarounds for bugs in our former PPP implementation, but
16409 		 * now other things have grown dependencies on them -- e.g.,
16410 		 * the tun module specifies a dl_addr_length of zero in its
16411 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16412 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16413 		 * but only after careful testing ensures that all dependent
16414 		 * broken DLPI providers have been fixed.
16415 		 */
16416 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16417 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16418 			ill->ill_phys_addr = NULL;
16419 		} else if (paddrlen != ill->ill_phys_addr_length) {
16420 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16421 			    paddrlen, ill->ill_phys_addr_length));
16422 			err = EINVAL;
16423 			break;
16424 		}
16425 
16426 		if (ill->ill_nd_lla_mp == NULL) {
16427 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16428 				err = ENOMEM;
16429 				break;
16430 			}
16431 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16432 		}
16433 
16434 		/*
16435 		 * Set the interface token.  If the zeroth interface address
16436 		 * is unspecified, then set it to the link local address.
16437 		 */
16438 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16439 			(void) ill_setdefaulttoken(ill);
16440 
16441 		ASSERT(ill->ill_ipif->ipif_id == 0);
16442 		if (ipif != NULL &&
16443 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16444 			(void) ipif_setlinklocal(ipif);
16445 		}
16446 		break;
16447 	}
16448 	case DL_OK_ACK:
16449 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16450 		    dl_primstr((int)dloa->dl_correct_primitive),
16451 		    dloa->dl_correct_primitive));
16452 		switch (dloa->dl_correct_primitive) {
16453 		case DL_ENABMULTI_REQ:
16454 		case DL_DISABMULTI_REQ:
16455 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16456 			break;
16457 		case DL_PROMISCON_REQ:
16458 		case DL_PROMISCOFF_REQ:
16459 		case DL_UNBIND_REQ:
16460 		case DL_ATTACH_REQ:
16461 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16462 			break;
16463 		}
16464 		break;
16465 	default:
16466 		break;
16467 	}
16468 
16469 	freemsg(mp);
16470 	if (mp1 == NULL)
16471 		return;
16472 
16473 	/*
16474 	 * The operation must complete without EINPROGRESS since
16475 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16476 	 * the operation will be stuck forever inside the IPSQ.
16477 	 */
16478 	ASSERT(err != EINPROGRESS);
16479 
16480 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16481 	case 0:
16482 		ipsq_current_finish(ipsq);
16483 		break;
16484 
16485 	case SIOCSLIFNAME:
16486 	case IF_UNITSEL: {
16487 		ill_t *ill_other = ILL_OTHER(ill);
16488 
16489 		/*
16490 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16491 		 * ill has a peer which is in an IPMP group, then place ill
16492 		 * into the same group.  One catch: although ifconfig plumbs
16493 		 * the appropriate IPMP meta-interface prior to plumbing this
16494 		 * ill, it is possible for multiple ifconfig applications to
16495 		 * race (or for another application to adjust plumbing), in
16496 		 * which case the IPMP meta-interface we need will be missing.
16497 		 * If so, kick the phyint out of the group.
16498 		 */
16499 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16500 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16501 			ipmp_illgrp_t	*illg;
16502 
16503 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16504 			if (illg == NULL)
16505 				ipmp_phyint_leave_grp(ill->ill_phyint);
16506 			else
16507 				ipmp_ill_join_illgrp(ill, illg);
16508 		}
16509 
16510 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16511 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16512 		else
16513 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16514 		break;
16515 	}
16516 	case SIOCLIFADDIF:
16517 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16518 		break;
16519 
16520 	default:
16521 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16522 		break;
16523 	}
16524 }
16525 
16526 /*
16527  * ip_rput_other is called by ip_rput to handle messages modifying the global
16528  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16529  */
16530 /* ARGSUSED */
16531 void
16532 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16533 {
16534 	ill_t		*ill = q->q_ptr;
16535 	struct iocblk	*iocp;
16536 	mblk_t		*mp1;
16537 	conn_t		*connp = NULL;
16538 
16539 	ip1dbg(("ip_rput_other "));
16540 	if (ipsq != NULL) {
16541 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16542 		ASSERT(ipsq->ipsq_xop ==
16543 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16544 	}
16545 
16546 	switch (mp->b_datap->db_type) {
16547 	case M_ERROR:
16548 	case M_HANGUP:
16549 		/*
16550 		 * The device has a problem.  We force the ILL down.  It can
16551 		 * be brought up again manually using SIOCSIFFLAGS (via
16552 		 * ifconfig or equivalent).
16553 		 */
16554 		ASSERT(ipsq != NULL);
16555 		if (mp->b_rptr < mp->b_wptr)
16556 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16557 		if (ill->ill_error == 0)
16558 			ill->ill_error = ENXIO;
16559 		if (!ill_down_start(q, mp))
16560 			return;
16561 		ipif_all_down_tail(ipsq, q, mp, NULL);
16562 		break;
16563 	case M_IOCACK:
16564 		iocp = (struct iocblk *)mp->b_rptr;
16565 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16566 		switch (iocp->ioc_cmd) {
16567 		case SIOCSTUNPARAM:
16568 		case OSIOCSTUNPARAM:
16569 			ASSERT(ipsq != NULL);
16570 			/*
16571 			 * Finish socket ioctl passed through to tun.
16572 			 * We should have an IOCTL waiting on this.
16573 			 */
16574 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16575 			if (ill->ill_isv6) {
16576 				struct iftun_req *ta;
16577 
16578 				/*
16579 				 * if a source or destination is
16580 				 * being set, try and set the link
16581 				 * local address for the tunnel
16582 				 */
16583 				ta = (struct iftun_req *)mp->b_cont->
16584 				    b_cont->b_rptr;
16585 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16586 					ipif_set_tun_llink(ill, ta);
16587 				}
16588 
16589 			}
16590 			if (mp1 != NULL) {
16591 				/*
16592 				 * Now copy back the b_next/b_prev used by
16593 				 * mi code for the mi_copy* functions.
16594 				 * See ip_sioctl_tunparam() for the reason.
16595 				 * Also protect against missing b_cont.
16596 				 */
16597 				if (mp->b_cont != NULL) {
16598 					mp->b_cont->b_next =
16599 					    mp1->b_cont->b_next;
16600 					mp->b_cont->b_prev =
16601 					    mp1->b_cont->b_prev;
16602 				}
16603 				inet_freemsg(mp1);
16604 				ASSERT(connp != NULL);
16605 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16606 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16607 			} else {
16608 				ASSERT(connp == NULL);
16609 				putnext(q, mp);
16610 			}
16611 			break;
16612 		case SIOCGTUNPARAM:
16613 		case OSIOCGTUNPARAM:
16614 			/*
16615 			 * This is really M_IOCDATA from the tunnel driver.
16616 			 * convert back and complete the ioctl.
16617 			 * We should have an IOCTL waiting on this.
16618 			 */
16619 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16620 			if (mp1) {
16621 				/*
16622 				 * Now copy back the b_next/b_prev used by
16623 				 * mi code for the mi_copy* functions.
16624 				 * See ip_sioctl_tunparam() for the reason.
16625 				 * Also protect against missing b_cont.
16626 				 */
16627 				if (mp->b_cont != NULL) {
16628 					mp->b_cont->b_next =
16629 					    mp1->b_cont->b_next;
16630 					mp->b_cont->b_prev =
16631 					    mp1->b_cont->b_prev;
16632 				}
16633 				inet_freemsg(mp1);
16634 				if (iocp->ioc_error == 0)
16635 					mp->b_datap->db_type = M_IOCDATA;
16636 				ASSERT(connp != NULL);
16637 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16638 				    iocp->ioc_error, COPYOUT, NULL);
16639 			} else {
16640 				ASSERT(connp == NULL);
16641 				putnext(q, mp);
16642 			}
16643 			break;
16644 		default:
16645 			break;
16646 		}
16647 		break;
16648 	case M_IOCNAK:
16649 		iocp = (struct iocblk *)mp->b_rptr;
16650 
16651 		switch (iocp->ioc_cmd) {
16652 			int mode;
16653 
16654 		case DL_IOC_HDR_INFO:
16655 			/*
16656 			 * If this was the first attempt, turn off the
16657 			 * fastpath probing.
16658 			 */
16659 			mutex_enter(&ill->ill_lock);
16660 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16661 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16662 				mutex_exit(&ill->ill_lock);
16663 				ill_fastpath_nack(ill);
16664 				ip1dbg(("ip_rput: DLPI fastpath off on "
16665 				    "interface %s\n",
16666 				    ill->ill_name));
16667 			} else {
16668 				mutex_exit(&ill->ill_lock);
16669 			}
16670 			freemsg(mp);
16671 			break;
16672 			case SIOCSTUNPARAM:
16673 		case OSIOCSTUNPARAM:
16674 			ASSERT(ipsq != NULL);
16675 			/*
16676 			 * Finish socket ioctl passed through to tun
16677 			 * We should have an IOCTL waiting on this.
16678 			 */
16679 			/* FALLTHRU */
16680 		case SIOCGTUNPARAM:
16681 		case OSIOCGTUNPARAM:
16682 			/*
16683 			 * This is really M_IOCDATA from the tunnel driver.
16684 			 * convert back and complete the ioctl.
16685 			 * We should have an IOCTL waiting on this.
16686 			 */
16687 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16688 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16689 				mp1 = ill_pending_mp_get(ill, &connp,
16690 				    iocp->ioc_id);
16691 				mode = COPYOUT;
16692 				ipsq = NULL;
16693 			} else {
16694 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16695 				mode = NO_COPYOUT;
16696 			}
16697 			if (mp1 != NULL) {
16698 				/*
16699 				 * Now copy back the b_next/b_prev used by
16700 				 * mi code for the mi_copy* functions.
16701 				 * See ip_sioctl_tunparam() for the reason.
16702 				 * Also protect against missing b_cont.
16703 				 */
16704 				if (mp->b_cont != NULL) {
16705 					mp->b_cont->b_next =
16706 					    mp1->b_cont->b_next;
16707 					mp->b_cont->b_prev =
16708 					    mp1->b_cont->b_prev;
16709 				}
16710 				inet_freemsg(mp1);
16711 				if (iocp->ioc_error == 0)
16712 					iocp->ioc_error = EINVAL;
16713 				ASSERT(connp != NULL);
16714 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16715 				    iocp->ioc_error, mode, ipsq);
16716 			} else {
16717 				ASSERT(connp == NULL);
16718 				putnext(q, mp);
16719 			}
16720 			break;
16721 		default:
16722 			break;
16723 		}
16724 	default:
16725 		break;
16726 	}
16727 }
16728 
16729 /*
16730  * NOTE : This function does not ire_refrele the ire argument passed in.
16731  *
16732  * IPQoS notes
16733  * IP policy is invoked twice for a forwarded packet, once on the read side
16734  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16735  * enabled. An additional parameter, in_ill, has been added for this purpose.
16736  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16737  * because ip_mroute drops this information.
16738  *
16739  */
16740 void
16741 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16742 {
16743 	uint32_t	old_pkt_len;
16744 	uint32_t	pkt_len;
16745 	queue_t	*q;
16746 	uint32_t	sum;
16747 #define	rptr	((uchar_t *)ipha)
16748 	uint32_t	max_frag;
16749 	uint32_t	ill_index;
16750 	ill_t		*out_ill;
16751 	mib2_ipIfStatsEntry_t *mibptr;
16752 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16753 
16754 	/* Get the ill_index of the incoming ILL */
16755 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16756 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16757 
16758 	/* Initiate Read side IPPF processing */
16759 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16760 		ip_process(IPP_FWD_IN, &mp, ill_index);
16761 		if (mp == NULL) {
16762 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16763 			    "during IPPF processing\n"));
16764 			return;
16765 		}
16766 	}
16767 
16768 	/* Adjust the checksum to reflect the ttl decrement. */
16769 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16770 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16771 
16772 	if (ipha->ipha_ttl-- <= 1) {
16773 		if (ip_csum_hdr(ipha)) {
16774 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16775 			goto drop_pkt;
16776 		}
16777 		/*
16778 		 * Note: ire_stq this will be NULL for multicast
16779 		 * datagrams using the long path through arp (the IRE
16780 		 * is not an IRE_CACHE). This should not cause
16781 		 * problems since we don't generate ICMP errors for
16782 		 * multicast packets.
16783 		 */
16784 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16785 		q = ire->ire_stq;
16786 		if (q != NULL) {
16787 			/* Sent by forwarding path, and router is global zone */
16788 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16789 			    GLOBAL_ZONEID, ipst);
16790 		} else
16791 			freemsg(mp);
16792 		return;
16793 	}
16794 
16795 	/*
16796 	 * Don't forward if the interface is down
16797 	 */
16798 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16799 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16800 		ip2dbg(("ip_rput_forward:interface is down\n"));
16801 		goto drop_pkt;
16802 	}
16803 
16804 	/* Get the ill_index of the outgoing ILL */
16805 	out_ill = ire_to_ill(ire);
16806 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16807 
16808 	DTRACE_PROBE4(ip4__forwarding__start,
16809 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16810 
16811 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16812 	    ipst->ips_ipv4firewall_forwarding,
16813 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16814 
16815 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16816 
16817 	if (mp == NULL)
16818 		return;
16819 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16820 
16821 	if (is_system_labeled()) {
16822 		mblk_t *mp1;
16823 
16824 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16825 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16826 			goto drop_pkt;
16827 		}
16828 		/* Size may have changed */
16829 		mp = mp1;
16830 		ipha = (ipha_t *)mp->b_rptr;
16831 		pkt_len = ntohs(ipha->ipha_length);
16832 	}
16833 
16834 	/* Check if there are options to update */
16835 	if (!IS_SIMPLE_IPH(ipha)) {
16836 		if (ip_csum_hdr(ipha)) {
16837 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16838 			goto drop_pkt;
16839 		}
16840 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16841 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16842 			return;
16843 		}
16844 
16845 		ipha->ipha_hdr_checksum = 0;
16846 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16847 	}
16848 	max_frag = ire->ire_max_frag;
16849 	if (pkt_len > max_frag) {
16850 		/*
16851 		 * It needs fragging on its way out.  We haven't
16852 		 * verified the header checksum yet.  Since we
16853 		 * are going to put a surely good checksum in the
16854 		 * outgoing header, we have to make sure that it
16855 		 * was good coming in.
16856 		 */
16857 		if (ip_csum_hdr(ipha)) {
16858 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16859 			goto drop_pkt;
16860 		}
16861 		/* Initiate Write side IPPF processing */
16862 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16863 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16864 			if (mp == NULL) {
16865 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16866 				    " during IPPF processing\n"));
16867 				return;
16868 			}
16869 		}
16870 		/*
16871 		 * Handle labeled packet resizing.
16872 		 *
16873 		 * If we have added a label, inform ip_wput_frag() of its
16874 		 * effect on the MTU for ICMP messages.
16875 		 */
16876 		if (pkt_len > old_pkt_len) {
16877 			uint32_t secopt_size;
16878 
16879 			secopt_size = pkt_len - old_pkt_len;
16880 			if (secopt_size < max_frag)
16881 				max_frag -= secopt_size;
16882 		}
16883 
16884 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16885 		    GLOBAL_ZONEID, ipst, NULL);
16886 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16887 		return;
16888 	}
16889 
16890 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16891 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16892 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16893 	    ipst->ips_ipv4firewall_physical_out,
16894 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16895 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16896 	if (mp == NULL)
16897 		return;
16898 
16899 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16900 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16901 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16902 	/* ip_xmit_v4 always consumes the packet */
16903 	return;
16904 
16905 drop_pkt:;
16906 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16907 	freemsg(mp);
16908 #undef	rptr
16909 }
16910 
16911 void
16912 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16913 {
16914 	ire_t	*ire;
16915 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16916 
16917 	ASSERT(!ipif->ipif_isv6);
16918 	/*
16919 	 * Find an IRE which matches the destination and the outgoing
16920 	 * queue in the cache table. All we need is an IRE_CACHE which
16921 	 * is pointing at ipif->ipif_ill.
16922 	 */
16923 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16924 		dst = ipif->ipif_pp_dst_addr;
16925 
16926 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16927 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16928 	if (ire == NULL) {
16929 		/*
16930 		 * Mark this packet to make it be delivered to
16931 		 * ip_rput_forward after the new ire has been
16932 		 * created.
16933 		 */
16934 		mp->b_prev = NULL;
16935 		mp->b_next = mp;
16936 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16937 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16938 	} else {
16939 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16940 		IRE_REFRELE(ire);
16941 	}
16942 }
16943 
16944 /* Update any source route, record route or timestamp options */
16945 static int
16946 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16947 {
16948 	ipoptp_t	opts;
16949 	uchar_t		*opt;
16950 	uint8_t		optval;
16951 	uint8_t		optlen;
16952 	ipaddr_t	dst;
16953 	uint32_t	ts;
16954 	ire_t		*dst_ire = NULL;
16955 	ire_t		*tmp_ire = NULL;
16956 	timestruc_t	now;
16957 
16958 	ip2dbg(("ip_rput_forward_options\n"));
16959 	dst = ipha->ipha_dst;
16960 	for (optval = ipoptp_first(&opts, ipha);
16961 	    optval != IPOPT_EOL;
16962 	    optval = ipoptp_next(&opts)) {
16963 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16964 		opt = opts.ipoptp_cur;
16965 		optlen = opts.ipoptp_len;
16966 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16967 		    optval, opts.ipoptp_len));
16968 		switch (optval) {
16969 			uint32_t off;
16970 		case IPOPT_SSRR:
16971 		case IPOPT_LSRR:
16972 			/* Check if adminstratively disabled */
16973 			if (!ipst->ips_ip_forward_src_routed) {
16974 				if (ire->ire_stq != NULL) {
16975 					/*
16976 					 * Sent by forwarding path, and router
16977 					 * is global zone
16978 					 */
16979 					icmp_unreachable(ire->ire_stq, mp,
16980 					    ICMP_SOURCE_ROUTE_FAILED,
16981 					    GLOBAL_ZONEID, ipst);
16982 				} else {
16983 					ip0dbg(("ip_rput_forward_options: "
16984 					    "unable to send unreach\n"));
16985 					freemsg(mp);
16986 				}
16987 				return (-1);
16988 			}
16989 
16990 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16991 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16992 			if (dst_ire == NULL) {
16993 				/*
16994 				 * Must be partial since ip_rput_options
16995 				 * checked for strict.
16996 				 */
16997 				break;
16998 			}
16999 			off = opt[IPOPT_OFFSET];
17000 			off--;
17001 		redo_srr:
17002 			if (optlen < IP_ADDR_LEN ||
17003 			    off > optlen - IP_ADDR_LEN) {
17004 				/* End of source route */
17005 				ip1dbg((
17006 				    "ip_rput_forward_options: end of SR\n"));
17007 				ire_refrele(dst_ire);
17008 				break;
17009 			}
17010 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17011 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17012 			    IP_ADDR_LEN);
17013 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17014 			    ntohl(dst)));
17015 
17016 			/*
17017 			 * Check if our address is present more than
17018 			 * once as consecutive hops in source route.
17019 			 */
17020 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17021 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17022 			if (tmp_ire != NULL) {
17023 				ire_refrele(tmp_ire);
17024 				off += IP_ADDR_LEN;
17025 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17026 				goto redo_srr;
17027 			}
17028 			ipha->ipha_dst = dst;
17029 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17030 			ire_refrele(dst_ire);
17031 			break;
17032 		case IPOPT_RR:
17033 			off = opt[IPOPT_OFFSET];
17034 			off--;
17035 			if (optlen < IP_ADDR_LEN ||
17036 			    off > optlen - IP_ADDR_LEN) {
17037 				/* No more room - ignore */
17038 				ip1dbg((
17039 				    "ip_rput_forward_options: end of RR\n"));
17040 				break;
17041 			}
17042 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17043 			    IP_ADDR_LEN);
17044 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17045 			break;
17046 		case IPOPT_TS:
17047 			/* Insert timestamp if there is room */
17048 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17049 			case IPOPT_TS_TSONLY:
17050 				off = IPOPT_TS_TIMELEN;
17051 				break;
17052 			case IPOPT_TS_PRESPEC:
17053 			case IPOPT_TS_PRESPEC_RFC791:
17054 				/* Verify that the address matched */
17055 				off = opt[IPOPT_OFFSET] - 1;
17056 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17057 				dst_ire = ire_ctable_lookup(dst, 0,
17058 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17059 				    MATCH_IRE_TYPE, ipst);
17060 				if (dst_ire == NULL) {
17061 					/* Not for us */
17062 					break;
17063 				}
17064 				ire_refrele(dst_ire);
17065 				/* FALLTHRU */
17066 			case IPOPT_TS_TSANDADDR:
17067 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17068 				break;
17069 			default:
17070 				/*
17071 				 * ip_*put_options should have already
17072 				 * dropped this packet.
17073 				 */
17074 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17075 				    "unknown IT - bug in ip_rput_options?\n");
17076 				return (0);	/* Keep "lint" happy */
17077 			}
17078 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17079 				/* Increase overflow counter */
17080 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17081 				opt[IPOPT_POS_OV_FLG] =
17082 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17083 				    (off << 4));
17084 				break;
17085 			}
17086 			off = opt[IPOPT_OFFSET] - 1;
17087 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17088 			case IPOPT_TS_PRESPEC:
17089 			case IPOPT_TS_PRESPEC_RFC791:
17090 			case IPOPT_TS_TSANDADDR:
17091 				bcopy(&ire->ire_src_addr,
17092 				    (char *)opt + off, IP_ADDR_LEN);
17093 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17094 				/* FALLTHRU */
17095 			case IPOPT_TS_TSONLY:
17096 				off = opt[IPOPT_OFFSET] - 1;
17097 				/* Compute # of milliseconds since midnight */
17098 				gethrestime(&now);
17099 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17100 				    now.tv_nsec / (NANOSEC / MILLISEC);
17101 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17102 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17103 				break;
17104 			}
17105 			break;
17106 		}
17107 	}
17108 	return (0);
17109 }
17110 
17111 /*
17112  * This is called after processing at least one of AH/ESP headers.
17113  *
17114  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17115  * the actual, physical interface on which the packet was received,
17116  * but, when ip_strict_dst_multihoming is set to 1, could be the
17117  * interface which had the ipha_dst configured when the packet went
17118  * through ip_rput. The ill_index corresponding to the recv_ill
17119  * is saved in ipsec_in_rill_index
17120  *
17121  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17122  * cannot assume "ire" points to valid data for any IPv6 cases.
17123  */
17124 void
17125 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17126 {
17127 	mblk_t *mp;
17128 	ipaddr_t dst;
17129 	in6_addr_t *v6dstp;
17130 	ipha_t *ipha;
17131 	ip6_t *ip6h;
17132 	ipsec_in_t *ii;
17133 	boolean_t ill_need_rele = B_FALSE;
17134 	boolean_t rill_need_rele = B_FALSE;
17135 	boolean_t ire_need_rele = B_FALSE;
17136 	netstack_t	*ns;
17137 	ip_stack_t	*ipst;
17138 
17139 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17140 	ASSERT(ii->ipsec_in_ill_index != 0);
17141 	ns = ii->ipsec_in_ns;
17142 	ASSERT(ii->ipsec_in_ns != NULL);
17143 	ipst = ns->netstack_ip;
17144 
17145 	mp = ipsec_mp->b_cont;
17146 	ASSERT(mp != NULL);
17147 
17148 	if (ill == NULL) {
17149 		ASSERT(recv_ill == NULL);
17150 		/*
17151 		 * We need to get the original queue on which ip_rput_local
17152 		 * or ip_rput_data_v6 was called.
17153 		 */
17154 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17155 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17156 		ill_need_rele = B_TRUE;
17157 
17158 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17159 			recv_ill = ill_lookup_on_ifindex(
17160 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17161 			    NULL, NULL, NULL, NULL, ipst);
17162 			rill_need_rele = B_TRUE;
17163 		} else {
17164 			recv_ill = ill;
17165 		}
17166 
17167 		if ((ill == NULL) || (recv_ill == NULL)) {
17168 			ip0dbg(("ip_fanout_proto_again: interface "
17169 			    "disappeared\n"));
17170 			if (ill != NULL)
17171 				ill_refrele(ill);
17172 			if (recv_ill != NULL)
17173 				ill_refrele(recv_ill);
17174 			freemsg(ipsec_mp);
17175 			return;
17176 		}
17177 	}
17178 
17179 	ASSERT(ill != NULL && recv_ill != NULL);
17180 
17181 	if (mp->b_datap->db_type == M_CTL) {
17182 		/*
17183 		 * AH/ESP is returning the ICMP message after
17184 		 * removing their headers. Fanout again till
17185 		 * it gets to the right protocol.
17186 		 */
17187 		if (ii->ipsec_in_v4) {
17188 			icmph_t *icmph;
17189 			int iph_hdr_length;
17190 			int hdr_length;
17191 
17192 			ipha = (ipha_t *)mp->b_rptr;
17193 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17194 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17195 			ipha = (ipha_t *)&icmph[1];
17196 			hdr_length = IPH_HDR_LENGTH(ipha);
17197 			/*
17198 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17199 			 * Reset the type to M_DATA.
17200 			 */
17201 			mp->b_datap->db_type = M_DATA;
17202 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17203 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17204 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17205 		} else {
17206 			icmp6_t *icmp6;
17207 			int hdr_length;
17208 
17209 			ip6h = (ip6_t *)mp->b_rptr;
17210 			/* Don't call hdr_length_v6() unless you have to. */
17211 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17212 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17213 			else
17214 				hdr_length = IPV6_HDR_LEN;
17215 
17216 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17217 			/*
17218 			 * icmp_inbound_error_fanout_v6 may need to do
17219 			 * pullupmsg.  Reset the type to M_DATA.
17220 			 */
17221 			mp->b_datap->db_type = M_DATA;
17222 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17223 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17224 			    ii->ipsec_in_zoneid);
17225 		}
17226 		if (ill_need_rele)
17227 			ill_refrele(ill);
17228 		if (rill_need_rele)
17229 			ill_refrele(recv_ill);
17230 		return;
17231 	}
17232 
17233 	if (ii->ipsec_in_v4) {
17234 		ipha = (ipha_t *)mp->b_rptr;
17235 		dst = ipha->ipha_dst;
17236 		if (CLASSD(dst)) {
17237 			/*
17238 			 * Multicast has to be delivered to all streams.
17239 			 */
17240 			dst = INADDR_BROADCAST;
17241 		}
17242 
17243 		if (ire == NULL) {
17244 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17245 			    msg_getlabel(mp), ipst);
17246 			if (ire == NULL) {
17247 				if (ill_need_rele)
17248 					ill_refrele(ill);
17249 				if (rill_need_rele)
17250 					ill_refrele(recv_ill);
17251 				ip1dbg(("ip_fanout_proto_again: "
17252 				    "IRE not found"));
17253 				freemsg(ipsec_mp);
17254 				return;
17255 			}
17256 			ire_need_rele = B_TRUE;
17257 		}
17258 
17259 		switch (ipha->ipha_protocol) {
17260 		case IPPROTO_UDP:
17261 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17262 			    recv_ill);
17263 			if (ire_need_rele)
17264 				ire_refrele(ire);
17265 			break;
17266 		case IPPROTO_TCP:
17267 			if (!ire_need_rele)
17268 				IRE_REFHOLD(ire);
17269 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17270 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17271 			IRE_REFRELE(ire);
17272 			if (mp != NULL) {
17273 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17274 				    mp, 1, SQ_PROCESS,
17275 				    SQTAG_IP_PROTO_AGAIN);
17276 			}
17277 			break;
17278 		case IPPROTO_SCTP:
17279 			if (!ire_need_rele)
17280 				IRE_REFHOLD(ire);
17281 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17282 			    ipsec_mp, 0, ill->ill_rq, dst);
17283 			break;
17284 		default:
17285 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17286 			    recv_ill, 0);
17287 			if (ire_need_rele)
17288 				ire_refrele(ire);
17289 			break;
17290 		}
17291 	} else {
17292 		uint32_t rput_flags = 0;
17293 
17294 		ip6h = (ip6_t *)mp->b_rptr;
17295 		v6dstp = &ip6h->ip6_dst;
17296 		/*
17297 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17298 		 * address.
17299 		 *
17300 		 * Currently, we don't store that state in the IPSEC_IN
17301 		 * message, and we may need to.
17302 		 */
17303 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17304 		    IP6_IN_LLMCAST : 0);
17305 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17306 		    NULL, NULL);
17307 	}
17308 	if (ill_need_rele)
17309 		ill_refrele(ill);
17310 	if (rill_need_rele)
17311 		ill_refrele(recv_ill);
17312 }
17313 
17314 /*
17315  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17316  * returns 'true' if there are still fragments left on the queue, in
17317  * which case we restart the timer.
17318  */
17319 void
17320 ill_frag_timer(void *arg)
17321 {
17322 	ill_t	*ill = (ill_t *)arg;
17323 	boolean_t frag_pending;
17324 	ip_stack_t	*ipst = ill->ill_ipst;
17325 
17326 	mutex_enter(&ill->ill_lock);
17327 	ASSERT(!ill->ill_fragtimer_executing);
17328 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17329 		ill->ill_frag_timer_id = 0;
17330 		mutex_exit(&ill->ill_lock);
17331 		return;
17332 	}
17333 	ill->ill_fragtimer_executing = 1;
17334 	mutex_exit(&ill->ill_lock);
17335 
17336 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17337 
17338 	/*
17339 	 * Restart the timer, if we have fragments pending or if someone
17340 	 * wanted us to be scheduled again.
17341 	 */
17342 	mutex_enter(&ill->ill_lock);
17343 	ill->ill_fragtimer_executing = 0;
17344 	ill->ill_frag_timer_id = 0;
17345 	if (frag_pending || ill->ill_fragtimer_needrestart)
17346 		ill_frag_timer_start(ill);
17347 	mutex_exit(&ill->ill_lock);
17348 }
17349 
17350 void
17351 ill_frag_timer_start(ill_t *ill)
17352 {
17353 	ip_stack_t	*ipst = ill->ill_ipst;
17354 
17355 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17356 
17357 	/* If the ill is closing or opening don't proceed */
17358 	if (ill->ill_state_flags & ILL_CONDEMNED)
17359 		return;
17360 
17361 	if (ill->ill_fragtimer_executing) {
17362 		/*
17363 		 * ill_frag_timer is currently executing. Just record the
17364 		 * the fact that we want the timer to be restarted.
17365 		 * ill_frag_timer will post a timeout before it returns,
17366 		 * ensuring it will be called again.
17367 		 */
17368 		ill->ill_fragtimer_needrestart = 1;
17369 		return;
17370 	}
17371 
17372 	if (ill->ill_frag_timer_id == 0) {
17373 		/*
17374 		 * The timer is neither running nor is the timeout handler
17375 		 * executing. Post a timeout so that ill_frag_timer will be
17376 		 * called
17377 		 */
17378 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17379 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17380 		ill->ill_fragtimer_needrestart = 0;
17381 	}
17382 }
17383 
17384 /*
17385  * This routine is needed for loopback when forwarding multicasts.
17386  *
17387  * IPQoS Notes:
17388  * IPPF processing is done in fanout routines.
17389  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17390  * processing for IPsec packets is done when it comes back in clear.
17391  * NOTE : The callers of this function need to do the ire_refrele for the
17392  *	  ire that is being passed in.
17393  */
17394 void
17395 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17396     ill_t *recv_ill, uint32_t esp_udp_ports)
17397 {
17398 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17399 	ill_t	*ill = (ill_t *)q->q_ptr;
17400 	uint32_t	sum;
17401 	uint32_t	u1;
17402 	uint32_t	u2;
17403 	int		hdr_length;
17404 	boolean_t	mctl_present;
17405 	mblk_t		*first_mp = mp;
17406 	mblk_t		*hada_mp = NULL;
17407 	ipha_t		*inner_ipha;
17408 	ip_stack_t	*ipst;
17409 
17410 	ASSERT(recv_ill != NULL);
17411 	ipst = recv_ill->ill_ipst;
17412 
17413 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17414 	    "ip_rput_locl_start: q %p", q);
17415 
17416 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17417 	ASSERT(ill != NULL);
17418 
17419 #define	rptr	((uchar_t *)ipha)
17420 #define	iphs	((uint16_t *)ipha)
17421 
17422 	/*
17423 	 * no UDP or TCP packet should come here anymore.
17424 	 */
17425 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17426 	    ipha->ipha_protocol != IPPROTO_UDP);
17427 
17428 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17429 	if (mctl_present &&
17430 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17431 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17432 
17433 		/*
17434 		 * It's an IPsec accelerated packet.
17435 		 * Keep a pointer to the data attributes around until
17436 		 * we allocate the ipsec_info_t.
17437 		 */
17438 		IPSECHW_DEBUG(IPSECHW_PKT,
17439 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17440 		hada_mp = first_mp;
17441 		hada_mp->b_cont = NULL;
17442 		/*
17443 		 * Since it is accelerated, it comes directly from
17444 		 * the ill and the data attributes is followed by
17445 		 * the packet data.
17446 		 */
17447 		ASSERT(mp->b_datap->db_type != M_CTL);
17448 		first_mp = mp;
17449 		mctl_present = B_FALSE;
17450 	}
17451 
17452 	/*
17453 	 * IF M_CTL is not present, then ipsec_in_is_secure
17454 	 * should return B_TRUE. There is a case where loopback
17455 	 * packets has an M_CTL in the front with all the
17456 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17457 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17458 	 * packets never comes here, it is safe to ASSERT the
17459 	 * following.
17460 	 */
17461 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17462 
17463 	/*
17464 	 * Also, we should never have an mctl_present if this is an
17465 	 * ESP-in-UDP packet.
17466 	 */
17467 	ASSERT(!mctl_present || !esp_in_udp_packet);
17468 
17469 	/* u1 is # words of IP options */
17470 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17471 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17472 
17473 	/*
17474 	 * Don't verify header checksum if we just removed UDP header or
17475 	 * packet is coming back from AH/ESP.
17476 	 */
17477 	if (!esp_in_udp_packet && !mctl_present) {
17478 		if (u1) {
17479 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17480 				if (hada_mp != NULL)
17481 					freemsg(hada_mp);
17482 				return;
17483 			}
17484 		} else {
17485 			/* Check the IP header checksum.  */
17486 #define	uph	((uint16_t *)ipha)
17487 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17488 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17489 #undef  uph
17490 			/* finish doing IP checksum */
17491 			sum = (sum & 0xFFFF) + (sum >> 16);
17492 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17493 			if (sum && sum != 0xFFFF) {
17494 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17495 				goto drop_pkt;
17496 			}
17497 		}
17498 	}
17499 
17500 	/*
17501 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17502 	 * might be called more than once for secure packets, count only
17503 	 * the first time.
17504 	 */
17505 	if (!mctl_present) {
17506 		UPDATE_IB_PKT_COUNT(ire);
17507 		ire->ire_last_used_time = lbolt;
17508 	}
17509 
17510 	/* Check for fragmentation offset. */
17511 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17512 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17513 	if (u1) {
17514 		/*
17515 		 * We re-assemble fragments before we do the AH/ESP
17516 		 * processing. Thus, M_CTL should not be present
17517 		 * while we are re-assembling.
17518 		 */
17519 		ASSERT(!mctl_present);
17520 		ASSERT(first_mp == mp);
17521 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17522 			return;
17523 
17524 		/*
17525 		 * Make sure that first_mp points back to mp as
17526 		 * the mp we came in with could have changed in
17527 		 * ip_rput_fragment().
17528 		 */
17529 		ipha = (ipha_t *)mp->b_rptr;
17530 		first_mp = mp;
17531 	}
17532 
17533 	/*
17534 	 * Clear hardware checksumming flag as it is currently only
17535 	 * used by TCP and UDP.
17536 	 */
17537 	DB_CKSUMFLAGS(mp) = 0;
17538 
17539 	/* Now we have a complete datagram, destined for this machine. */
17540 	u1 = IPH_HDR_LENGTH(ipha);
17541 	switch (ipha->ipha_protocol) {
17542 	case IPPROTO_ICMP: {
17543 		ire_t		*ire_zone;
17544 		ilm_t		*ilm;
17545 		mblk_t		*mp1;
17546 		zoneid_t	last_zoneid;
17547 		ilm_walker_t	ilw;
17548 
17549 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17550 			ASSERT(ire->ire_type == IRE_BROADCAST);
17551 
17552 			/*
17553 			 * In the multicast case, applications may have joined
17554 			 * the group from different zones, so we need to deliver
17555 			 * the packet to each of them. Loop through the
17556 			 * multicast memberships structures (ilm) on the receive
17557 			 * ill and send a copy of the packet up each matching
17558 			 * one. However, we don't do this for multicasts sent on
17559 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17560 			 * they must stay in the sender's zone.
17561 			 *
17562 			 * ilm_add_v6() ensures that ilms in the same zone are
17563 			 * contiguous in the ill_ilm list. We use this property
17564 			 * to avoid sending duplicates needed when two
17565 			 * applications in the same zone join the same group on
17566 			 * different logical interfaces: we ignore the ilm if
17567 			 * its zoneid is the same as the last matching one.
17568 			 * In addition, the sending of the packet for
17569 			 * ire_zoneid is delayed until all of the other ilms
17570 			 * have been exhausted.
17571 			 */
17572 			last_zoneid = -1;
17573 			ilm = ilm_walker_start(&ilw, recv_ill);
17574 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17575 				if (ipha->ipha_dst != ilm->ilm_addr ||
17576 				    ilm->ilm_zoneid == last_zoneid ||
17577 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17578 				    ilm->ilm_zoneid == ALL_ZONES ||
17579 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17580 					continue;
17581 				mp1 = ip_copymsg(first_mp);
17582 				if (mp1 == NULL)
17583 					continue;
17584 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17585 				    0, sum, mctl_present, B_TRUE,
17586 				    recv_ill, ilm->ilm_zoneid);
17587 				last_zoneid = ilm->ilm_zoneid;
17588 			}
17589 			ilm_walker_finish(&ilw);
17590 		} else if (ire->ire_type == IRE_BROADCAST) {
17591 			/*
17592 			 * In the broadcast case, there may be many zones
17593 			 * which need a copy of the packet delivered to them.
17594 			 * There is one IRE_BROADCAST per broadcast address
17595 			 * and per zone; we walk those using a helper function.
17596 			 * In addition, the sending of the packet for ire is
17597 			 * delayed until all of the other ires have been
17598 			 * processed.
17599 			 */
17600 			IRB_REFHOLD(ire->ire_bucket);
17601 			ire_zone = NULL;
17602 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17603 			    ire)) != NULL) {
17604 				mp1 = ip_copymsg(first_mp);
17605 				if (mp1 == NULL)
17606 					continue;
17607 
17608 				UPDATE_IB_PKT_COUNT(ire_zone);
17609 				ire_zone->ire_last_used_time = lbolt;
17610 				icmp_inbound(q, mp1, B_TRUE, ill,
17611 				    0, sum, mctl_present, B_TRUE,
17612 				    recv_ill, ire_zone->ire_zoneid);
17613 			}
17614 			IRB_REFRELE(ire->ire_bucket);
17615 		}
17616 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17617 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17618 		    ire->ire_zoneid);
17619 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17620 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17621 		return;
17622 	}
17623 	case IPPROTO_IGMP:
17624 		/*
17625 		 * If we are not willing to accept IGMP packets in clear,
17626 		 * then check with global policy.
17627 		 */
17628 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17629 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17630 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17631 			if (first_mp == NULL)
17632 				return;
17633 		}
17634 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17635 			freemsg(first_mp);
17636 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17637 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17638 			return;
17639 		}
17640 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17641 			/* Bad packet - discarded by igmp_input */
17642 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17643 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17644 			if (mctl_present)
17645 				freeb(first_mp);
17646 			return;
17647 		}
17648 		/*
17649 		 * igmp_input() may have returned the pulled up message.
17650 		 * So first_mp and ipha need to be reinitialized.
17651 		 */
17652 		ipha = (ipha_t *)mp->b_rptr;
17653 		if (mctl_present)
17654 			first_mp->b_cont = mp;
17655 		else
17656 			first_mp = mp;
17657 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17658 		    connf_head != NULL) {
17659 			/* No user-level listener for IGMP packets */
17660 			goto drop_pkt;
17661 		}
17662 		/* deliver to local raw users */
17663 		break;
17664 	case IPPROTO_PIM:
17665 		/*
17666 		 * If we are not willing to accept PIM packets in clear,
17667 		 * then check with global policy.
17668 		 */
17669 		if (ipst->ips_pim_accept_clear_messages == 0) {
17670 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17671 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17672 			if (first_mp == NULL)
17673 				return;
17674 		}
17675 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17676 			freemsg(first_mp);
17677 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17678 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17679 			return;
17680 		}
17681 		if (pim_input(q, mp, ill) != 0) {
17682 			/* Bad packet - discarded by pim_input */
17683 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17684 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17685 			if (mctl_present)
17686 				freeb(first_mp);
17687 			return;
17688 		}
17689 
17690 		/*
17691 		 * pim_input() may have pulled up the message so ipha needs to
17692 		 * be reinitialized.
17693 		 */
17694 		ipha = (ipha_t *)mp->b_rptr;
17695 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17696 		    connf_head != NULL) {
17697 			/* No user-level listener for PIM packets */
17698 			goto drop_pkt;
17699 		}
17700 		/* deliver to local raw users */
17701 		break;
17702 	case IPPROTO_ENCAP:
17703 		/*
17704 		 * Handle self-encapsulated packets (IP-in-IP where
17705 		 * the inner addresses == the outer addresses).
17706 		 */
17707 		hdr_length = IPH_HDR_LENGTH(ipha);
17708 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17709 		    mp->b_wptr) {
17710 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17711 			    sizeof (ipha_t) - mp->b_rptr)) {
17712 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17713 				freemsg(first_mp);
17714 				return;
17715 			}
17716 			ipha = (ipha_t *)mp->b_rptr;
17717 		}
17718 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17719 		/*
17720 		 * Check the sanity of the inner IP header.
17721 		 */
17722 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17723 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17724 			freemsg(first_mp);
17725 			return;
17726 		}
17727 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17728 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17729 			freemsg(first_mp);
17730 			return;
17731 		}
17732 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17733 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17734 			ipsec_in_t *ii;
17735 
17736 			/*
17737 			 * Self-encapsulated tunnel packet. Remove
17738 			 * the outer IP header and fanout again.
17739 			 * We also need to make sure that the inner
17740 			 * header is pulled up until options.
17741 			 */
17742 			mp->b_rptr = (uchar_t *)inner_ipha;
17743 			ipha = inner_ipha;
17744 			hdr_length = IPH_HDR_LENGTH(ipha);
17745 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17746 				if (!pullupmsg(mp, (uchar_t *)ipha +
17747 				    + hdr_length - mp->b_rptr)) {
17748 					freemsg(first_mp);
17749 					return;
17750 				}
17751 				ipha = (ipha_t *)mp->b_rptr;
17752 			}
17753 			if (hdr_length > sizeof (ipha_t)) {
17754 				/* We got options on the inner packet. */
17755 				ipaddr_t dst = ipha->ipha_dst;
17756 
17757 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17758 				    -1) {
17759 					/* Bad options! */
17760 					return;
17761 				}
17762 				if (dst != ipha->ipha_dst) {
17763 					/*
17764 					 * Someone put a source-route in
17765 					 * the inside header of a self-
17766 					 * encapsulated packet.  Drop it
17767 					 * with extreme prejudice and let
17768 					 * the sender know.
17769 					 */
17770 					icmp_unreachable(q, first_mp,
17771 					    ICMP_SOURCE_ROUTE_FAILED,
17772 					    recv_ill->ill_zoneid, ipst);
17773 					return;
17774 				}
17775 			}
17776 			if (!mctl_present) {
17777 				ASSERT(first_mp == mp);
17778 				/*
17779 				 * This means that somebody is sending
17780 				 * Self-encapsualted packets without AH/ESP.
17781 				 * If AH/ESP was present, we would have already
17782 				 * allocated the first_mp.
17783 				 *
17784 				 * Send this packet to find a tunnel endpoint.
17785 				 * if I can't find one, an ICMP
17786 				 * PROTOCOL_UNREACHABLE will get sent.
17787 				 */
17788 				goto fanout;
17789 			}
17790 			/*
17791 			 * We generally store the ill_index if we need to
17792 			 * do IPsec processing as we lose the ill queue when
17793 			 * we come back. But in this case, we never should
17794 			 * have to store the ill_index here as it should have
17795 			 * been stored previously when we processed the
17796 			 * AH/ESP header in this routine or for non-ipsec
17797 			 * cases, we still have the queue. But for some bad
17798 			 * packets from the wire, we can get to IPsec after
17799 			 * this and we better store the index for that case.
17800 			 */
17801 			ill = (ill_t *)q->q_ptr;
17802 			ii = (ipsec_in_t *)first_mp->b_rptr;
17803 			ii->ipsec_in_ill_index =
17804 			    ill->ill_phyint->phyint_ifindex;
17805 			ii->ipsec_in_rill_index =
17806 			    recv_ill->ill_phyint->phyint_ifindex;
17807 			if (ii->ipsec_in_decaps) {
17808 				/*
17809 				 * This packet is self-encapsulated multiple
17810 				 * times. We don't want to recurse infinitely.
17811 				 * To keep it simple, drop the packet.
17812 				 */
17813 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17814 				freemsg(first_mp);
17815 				return;
17816 			}
17817 			ii->ipsec_in_decaps = B_TRUE;
17818 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17819 			    ire);
17820 			return;
17821 		}
17822 		break;
17823 	case IPPROTO_AH:
17824 	case IPPROTO_ESP: {
17825 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17826 
17827 		/*
17828 		 * Fast path for AH/ESP. If this is the first time
17829 		 * we are sending a datagram to AH/ESP, allocate
17830 		 * a IPSEC_IN message and prepend it. Otherwise,
17831 		 * just fanout.
17832 		 */
17833 
17834 		int ipsec_rc;
17835 		ipsec_in_t *ii;
17836 		netstack_t *ns = ipst->ips_netstack;
17837 
17838 		IP_STAT(ipst, ipsec_proto_ahesp);
17839 		if (!mctl_present) {
17840 			ASSERT(first_mp == mp);
17841 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17842 			if (first_mp == NULL) {
17843 				ip1dbg(("ip_proto_input: IPSEC_IN "
17844 				    "allocation failure.\n"));
17845 				freemsg(hada_mp); /* okay ifnull */
17846 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17847 				freemsg(mp);
17848 				return;
17849 			}
17850 			/*
17851 			 * Store the ill_index so that when we come back
17852 			 * from IPsec we ride on the same queue.
17853 			 */
17854 			ill = (ill_t *)q->q_ptr;
17855 			ii = (ipsec_in_t *)first_mp->b_rptr;
17856 			ii->ipsec_in_ill_index =
17857 			    ill->ill_phyint->phyint_ifindex;
17858 			ii->ipsec_in_rill_index =
17859 			    recv_ill->ill_phyint->phyint_ifindex;
17860 			first_mp->b_cont = mp;
17861 			/*
17862 			 * Cache hardware acceleration info.
17863 			 */
17864 			if (hada_mp != NULL) {
17865 				IPSECHW_DEBUG(IPSECHW_PKT,
17866 				    ("ip_rput_local: caching data attr.\n"));
17867 				ii->ipsec_in_accelerated = B_TRUE;
17868 				ii->ipsec_in_da = hada_mp;
17869 				hada_mp = NULL;
17870 			}
17871 		} else {
17872 			ii = (ipsec_in_t *)first_mp->b_rptr;
17873 		}
17874 
17875 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17876 
17877 		if (!ipsec_loaded(ipss)) {
17878 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17879 			    ire->ire_zoneid, ipst);
17880 			return;
17881 		}
17882 
17883 		ns = ipst->ips_netstack;
17884 		/* select inbound SA and have IPsec process the pkt */
17885 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17886 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17887 			boolean_t esp_in_udp_sa;
17888 			if (esph == NULL)
17889 				return;
17890 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17891 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17892 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17893 			    IPSA_F_NATT) != 0);
17894 			/*
17895 			 * The following is a fancy, but quick, way of saying:
17896 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17897 			 *    OR
17898 			 * ESP SA and ESP-in-UDP packet --> drop
17899 			 */
17900 			if (esp_in_udp_sa != esp_in_udp_packet) {
17901 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17902 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17903 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17904 				    &ns->netstack_ipsec->ipsec_dropper);
17905 				return;
17906 			}
17907 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17908 			    first_mp, esph);
17909 		} else {
17910 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17911 			if (ah == NULL)
17912 				return;
17913 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17914 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17915 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17916 			    first_mp, ah);
17917 		}
17918 
17919 		switch (ipsec_rc) {
17920 		case IPSEC_STATUS_SUCCESS:
17921 			break;
17922 		case IPSEC_STATUS_FAILED:
17923 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17924 			/* FALLTHRU */
17925 		case IPSEC_STATUS_PENDING:
17926 			return;
17927 		}
17928 		/* we're done with IPsec processing, send it up */
17929 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17930 		return;
17931 	}
17932 	default:
17933 		break;
17934 	}
17935 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17936 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17937 		    ire->ire_zoneid));
17938 		goto drop_pkt;
17939 	}
17940 	/*
17941 	 * Handle protocols with which IP is less intimate.  There
17942 	 * can be more than one stream bound to a particular
17943 	 * protocol.  When this is the case, each one gets a copy
17944 	 * of any incoming packets.
17945 	 */
17946 fanout:
17947 	ip_fanout_proto(q, first_mp, ill, ipha,
17948 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17949 	    B_TRUE, recv_ill, ire->ire_zoneid);
17950 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17951 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17952 	return;
17953 
17954 drop_pkt:
17955 	freemsg(first_mp);
17956 	if (hada_mp != NULL)
17957 		freeb(hada_mp);
17958 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17959 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17960 #undef	rptr
17961 #undef  iphs
17962 
17963 }
17964 
17965 /*
17966  * Update any source route, record route or timestamp options.
17967  * Check that we are at end of strict source route.
17968  * The options have already been checked for sanity in ip_rput_options().
17969  */
17970 static boolean_t
17971 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17972     ip_stack_t *ipst)
17973 {
17974 	ipoptp_t	opts;
17975 	uchar_t		*opt;
17976 	uint8_t		optval;
17977 	uint8_t		optlen;
17978 	ipaddr_t	dst;
17979 	uint32_t	ts;
17980 	ire_t		*dst_ire;
17981 	timestruc_t	now;
17982 	zoneid_t	zoneid;
17983 	ill_t		*ill;
17984 
17985 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17986 
17987 	ip2dbg(("ip_rput_local_options\n"));
17988 
17989 	for (optval = ipoptp_first(&opts, ipha);
17990 	    optval != IPOPT_EOL;
17991 	    optval = ipoptp_next(&opts)) {
17992 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17993 		opt = opts.ipoptp_cur;
17994 		optlen = opts.ipoptp_len;
17995 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17996 		    optval, optlen));
17997 		switch (optval) {
17998 			uint32_t off;
17999 		case IPOPT_SSRR:
18000 		case IPOPT_LSRR:
18001 			off = opt[IPOPT_OFFSET];
18002 			off--;
18003 			if (optlen < IP_ADDR_LEN ||
18004 			    off > optlen - IP_ADDR_LEN) {
18005 				/* End of source route */
18006 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18007 				break;
18008 			}
18009 			/*
18010 			 * This will only happen if two consecutive entries
18011 			 * in the source route contains our address or if
18012 			 * it is a packet with a loose source route which
18013 			 * reaches us before consuming the whole source route
18014 			 */
18015 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18016 			if (optval == IPOPT_SSRR) {
18017 				goto bad_src_route;
18018 			}
18019 			/*
18020 			 * Hack: instead of dropping the packet truncate the
18021 			 * source route to what has been used by filling the
18022 			 * rest with IPOPT_NOP.
18023 			 */
18024 			opt[IPOPT_OLEN] = (uint8_t)off;
18025 			while (off < optlen) {
18026 				opt[off++] = IPOPT_NOP;
18027 			}
18028 			break;
18029 		case IPOPT_RR:
18030 			off = opt[IPOPT_OFFSET];
18031 			off--;
18032 			if (optlen < IP_ADDR_LEN ||
18033 			    off > optlen - IP_ADDR_LEN) {
18034 				/* No more room - ignore */
18035 				ip1dbg((
18036 				    "ip_rput_local_options: end of RR\n"));
18037 				break;
18038 			}
18039 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18040 			    IP_ADDR_LEN);
18041 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18042 			break;
18043 		case IPOPT_TS:
18044 			/* Insert timestamp if there is romm */
18045 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18046 			case IPOPT_TS_TSONLY:
18047 				off = IPOPT_TS_TIMELEN;
18048 				break;
18049 			case IPOPT_TS_PRESPEC:
18050 			case IPOPT_TS_PRESPEC_RFC791:
18051 				/* Verify that the address matched */
18052 				off = opt[IPOPT_OFFSET] - 1;
18053 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18054 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18055 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18056 				    ipst);
18057 				if (dst_ire == NULL) {
18058 					/* Not for us */
18059 					break;
18060 				}
18061 				ire_refrele(dst_ire);
18062 				/* FALLTHRU */
18063 			case IPOPT_TS_TSANDADDR:
18064 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18065 				break;
18066 			default:
18067 				/*
18068 				 * ip_*put_options should have already
18069 				 * dropped this packet.
18070 				 */
18071 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18072 				    "unknown IT - bug in ip_rput_options?\n");
18073 				return (B_TRUE);	/* Keep "lint" happy */
18074 			}
18075 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18076 				/* Increase overflow counter */
18077 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18078 				opt[IPOPT_POS_OV_FLG] =
18079 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18080 				    (off << 4));
18081 				break;
18082 			}
18083 			off = opt[IPOPT_OFFSET] - 1;
18084 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18085 			case IPOPT_TS_PRESPEC:
18086 			case IPOPT_TS_PRESPEC_RFC791:
18087 			case IPOPT_TS_TSANDADDR:
18088 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18089 				    IP_ADDR_LEN);
18090 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18091 				/* FALLTHRU */
18092 			case IPOPT_TS_TSONLY:
18093 				off = opt[IPOPT_OFFSET] - 1;
18094 				/* Compute # of milliseconds since midnight */
18095 				gethrestime(&now);
18096 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18097 				    now.tv_nsec / (NANOSEC / MILLISEC);
18098 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18099 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18100 				break;
18101 			}
18102 			break;
18103 		}
18104 	}
18105 	return (B_TRUE);
18106 
18107 bad_src_route:
18108 	q = WR(q);
18109 	if (q->q_next != NULL)
18110 		ill = q->q_ptr;
18111 	else
18112 		ill = NULL;
18113 
18114 	/* make sure we clear any indication of a hardware checksum */
18115 	DB_CKSUMFLAGS(mp) = 0;
18116 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18117 	if (zoneid == ALL_ZONES)
18118 		freemsg(mp);
18119 	else
18120 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18121 	return (B_FALSE);
18122 
18123 }
18124 
18125 /*
18126  * Process IP options in an inbound packet.  If an option affects the
18127  * effective destination address, return the next hop address via dstp.
18128  * Returns -1 if something fails in which case an ICMP error has been sent
18129  * and mp freed.
18130  */
18131 static int
18132 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18133     ip_stack_t *ipst)
18134 {
18135 	ipoptp_t	opts;
18136 	uchar_t		*opt;
18137 	uint8_t		optval;
18138 	uint8_t		optlen;
18139 	ipaddr_t	dst;
18140 	intptr_t	code = 0;
18141 	ire_t		*ire = NULL;
18142 	zoneid_t	zoneid;
18143 	ill_t		*ill;
18144 
18145 	ip2dbg(("ip_rput_options\n"));
18146 	dst = ipha->ipha_dst;
18147 	for (optval = ipoptp_first(&opts, ipha);
18148 	    optval != IPOPT_EOL;
18149 	    optval = ipoptp_next(&opts)) {
18150 		opt = opts.ipoptp_cur;
18151 		optlen = opts.ipoptp_len;
18152 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18153 		    optval, optlen));
18154 		/*
18155 		 * Note: we need to verify the checksum before we
18156 		 * modify anything thus this routine only extracts the next
18157 		 * hop dst from any source route.
18158 		 */
18159 		switch (optval) {
18160 			uint32_t off;
18161 		case IPOPT_SSRR:
18162 		case IPOPT_LSRR:
18163 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18164 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18165 			if (ire == NULL) {
18166 				if (optval == IPOPT_SSRR) {
18167 					ip1dbg(("ip_rput_options: not next"
18168 					    " strict source route 0x%x\n",
18169 					    ntohl(dst)));
18170 					code = (char *)&ipha->ipha_dst -
18171 					    (char *)ipha;
18172 					goto param_prob; /* RouterReq's */
18173 				}
18174 				ip2dbg(("ip_rput_options: "
18175 				    "not next source route 0x%x\n",
18176 				    ntohl(dst)));
18177 				break;
18178 			}
18179 			ire_refrele(ire);
18180 
18181 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18182 				ip1dbg((
18183 				    "ip_rput_options: bad option offset\n"));
18184 				code = (char *)&opt[IPOPT_OLEN] -
18185 				    (char *)ipha;
18186 				goto param_prob;
18187 			}
18188 			off = opt[IPOPT_OFFSET];
18189 			off--;
18190 		redo_srr:
18191 			if (optlen < IP_ADDR_LEN ||
18192 			    off > optlen - IP_ADDR_LEN) {
18193 				/* End of source route */
18194 				ip1dbg(("ip_rput_options: end of SR\n"));
18195 				break;
18196 			}
18197 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18198 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18199 			    ntohl(dst)));
18200 
18201 			/*
18202 			 * Check if our address is present more than
18203 			 * once as consecutive hops in source route.
18204 			 * XXX verify per-interface ip_forwarding
18205 			 * for source route?
18206 			 */
18207 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18208 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18209 
18210 			if (ire != NULL) {
18211 				ire_refrele(ire);
18212 				off += IP_ADDR_LEN;
18213 				goto redo_srr;
18214 			}
18215 
18216 			if (dst == htonl(INADDR_LOOPBACK)) {
18217 				ip1dbg(("ip_rput_options: loopback addr in "
18218 				    "source route!\n"));
18219 				goto bad_src_route;
18220 			}
18221 			/*
18222 			 * For strict: verify that dst is directly
18223 			 * reachable.
18224 			 */
18225 			if (optval == IPOPT_SSRR) {
18226 				ire = ire_ftable_lookup(dst, 0, 0,
18227 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18228 				    msg_getlabel(mp),
18229 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18230 				if (ire == NULL) {
18231 					ip1dbg(("ip_rput_options: SSRR not "
18232 					    "directly reachable: 0x%x\n",
18233 					    ntohl(dst)));
18234 					goto bad_src_route;
18235 				}
18236 				ire_refrele(ire);
18237 			}
18238 			/*
18239 			 * Defer update of the offset and the record route
18240 			 * until the packet is forwarded.
18241 			 */
18242 			break;
18243 		case IPOPT_RR:
18244 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18245 				ip1dbg((
18246 				    "ip_rput_options: bad option offset\n"));
18247 				code = (char *)&opt[IPOPT_OLEN] -
18248 				    (char *)ipha;
18249 				goto param_prob;
18250 			}
18251 			break;
18252 		case IPOPT_TS:
18253 			/*
18254 			 * Verify that length >= 5 and that there is either
18255 			 * room for another timestamp or that the overflow
18256 			 * counter is not maxed out.
18257 			 */
18258 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18259 			if (optlen < IPOPT_MINLEN_IT) {
18260 				goto param_prob;
18261 			}
18262 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18263 				ip1dbg((
18264 				    "ip_rput_options: bad option offset\n"));
18265 				code = (char *)&opt[IPOPT_OFFSET] -
18266 				    (char *)ipha;
18267 				goto param_prob;
18268 			}
18269 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18270 			case IPOPT_TS_TSONLY:
18271 				off = IPOPT_TS_TIMELEN;
18272 				break;
18273 			case IPOPT_TS_TSANDADDR:
18274 			case IPOPT_TS_PRESPEC:
18275 			case IPOPT_TS_PRESPEC_RFC791:
18276 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18277 				break;
18278 			default:
18279 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18280 				    (char *)ipha;
18281 				goto param_prob;
18282 			}
18283 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18284 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18285 				/*
18286 				 * No room and the overflow counter is 15
18287 				 * already.
18288 				 */
18289 				goto param_prob;
18290 			}
18291 			break;
18292 		}
18293 	}
18294 
18295 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18296 		*dstp = dst;
18297 		return (0);
18298 	}
18299 
18300 	ip1dbg(("ip_rput_options: error processing IP options."));
18301 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18302 
18303 param_prob:
18304 	q = WR(q);
18305 	if (q->q_next != NULL)
18306 		ill = q->q_ptr;
18307 	else
18308 		ill = NULL;
18309 
18310 	/* make sure we clear any indication of a hardware checksum */
18311 	DB_CKSUMFLAGS(mp) = 0;
18312 	/* Don't know whether this is for non-global or global/forwarding */
18313 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18314 	if (zoneid == ALL_ZONES)
18315 		freemsg(mp);
18316 	else
18317 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18318 	return (-1);
18319 
18320 bad_src_route:
18321 	q = WR(q);
18322 	if (q->q_next != NULL)
18323 		ill = q->q_ptr;
18324 	else
18325 		ill = NULL;
18326 
18327 	/* make sure we clear any indication of a hardware checksum */
18328 	DB_CKSUMFLAGS(mp) = 0;
18329 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18330 	if (zoneid == ALL_ZONES)
18331 		freemsg(mp);
18332 	else
18333 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18334 	return (-1);
18335 }
18336 
18337 /*
18338  * IP & ICMP info in >=14 msg's ...
18339  *  - ip fixed part (mib2_ip_t)
18340  *  - icmp fixed part (mib2_icmp_t)
18341  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18342  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18343  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18344  *  - ipRouteAttributeTable (ip 102)	labeled routes
18345  *  - ip multicast membership (ip_member_t)
18346  *  - ip multicast source filtering (ip_grpsrc_t)
18347  *  - igmp fixed part (struct igmpstat)
18348  *  - multicast routing stats (struct mrtstat)
18349  *  - multicast routing vifs (array of struct vifctl)
18350  *  - multicast routing routes (array of struct mfcctl)
18351  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18352  *					One per ill plus one generic
18353  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18354  *					One per ill plus one generic
18355  *  - ipv6RouteEntry			all IPv6 IREs
18356  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18357  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18358  *  - ipv6AddrEntry			all IPv6 ipifs
18359  *  - ipv6 multicast membership (ipv6_member_t)
18360  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18361  *
18362  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18363  *
18364  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18365  * already filled in by the caller.
18366  * Return value of 0 indicates that no messages were sent and caller
18367  * should free mpctl.
18368  */
18369 int
18370 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18371 {
18372 	ip_stack_t *ipst;
18373 	sctp_stack_t *sctps;
18374 
18375 	if (q->q_next != NULL) {
18376 		ipst = ILLQ_TO_IPST(q);
18377 	} else {
18378 		ipst = CONNQ_TO_IPST(q);
18379 	}
18380 	ASSERT(ipst != NULL);
18381 	sctps = ipst->ips_netstack->netstack_sctp;
18382 
18383 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18384 		return (0);
18385 	}
18386 
18387 	/*
18388 	 * For the purposes of the (broken) packet shell use
18389 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18390 	 * to make TCP and UDP appear first in the list of mib items.
18391 	 * TBD: We could expand this and use it in netstat so that
18392 	 * the kernel doesn't have to produce large tables (connections,
18393 	 * routes, etc) when netstat only wants the statistics or a particular
18394 	 * table.
18395 	 */
18396 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18397 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18398 			return (1);
18399 		}
18400 	}
18401 
18402 	if (level != MIB2_TCP) {
18403 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18404 			return (1);
18405 		}
18406 	}
18407 
18408 	if (level != MIB2_UDP) {
18409 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18410 			return (1);
18411 		}
18412 	}
18413 
18414 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18415 	    ipst)) == NULL) {
18416 		return (1);
18417 	}
18418 
18419 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18420 		return (1);
18421 	}
18422 
18423 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18424 		return (1);
18425 	}
18426 
18427 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18428 		return (1);
18429 	}
18430 
18431 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18432 		return (1);
18433 	}
18434 
18435 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18436 		return (1);
18437 	}
18438 
18439 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18440 		return (1);
18441 	}
18442 
18443 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18444 		return (1);
18445 	}
18446 
18447 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18448 		return (1);
18449 	}
18450 
18451 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18452 		return (1);
18453 	}
18454 
18455 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18456 		return (1);
18457 	}
18458 
18459 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18460 		return (1);
18461 	}
18462 
18463 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18464 		return (1);
18465 	}
18466 
18467 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18468 		return (1);
18469 	}
18470 
18471 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18472 	if (mpctl == NULL)
18473 		return (1);
18474 
18475 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18476 	if (mpctl == NULL)
18477 		return (1);
18478 
18479 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18480 		return (1);
18481 	}
18482 	freemsg(mpctl);
18483 	return (1);
18484 }
18485 
18486 /* Get global (legacy) IPv4 statistics */
18487 static mblk_t *
18488 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18489     ip_stack_t *ipst)
18490 {
18491 	mib2_ip_t		old_ip_mib;
18492 	struct opthdr		*optp;
18493 	mblk_t			*mp2ctl;
18494 
18495 	/*
18496 	 * make a copy of the original message
18497 	 */
18498 	mp2ctl = copymsg(mpctl);
18499 
18500 	/* fixed length IP structure... */
18501 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18502 	optp->level = MIB2_IP;
18503 	optp->name = 0;
18504 	SET_MIB(old_ip_mib.ipForwarding,
18505 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18506 	SET_MIB(old_ip_mib.ipDefaultTTL,
18507 	    (uint32_t)ipst->ips_ip_def_ttl);
18508 	SET_MIB(old_ip_mib.ipReasmTimeout,
18509 	    ipst->ips_ip_g_frag_timeout);
18510 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18511 	    sizeof (mib2_ipAddrEntry_t));
18512 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18513 	    sizeof (mib2_ipRouteEntry_t));
18514 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18515 	    sizeof (mib2_ipNetToMediaEntry_t));
18516 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18517 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18518 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18519 	    sizeof (mib2_ipAttributeEntry_t));
18520 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18521 
18522 	/*
18523 	 * Grab the statistics from the new IP MIB
18524 	 */
18525 	SET_MIB(old_ip_mib.ipInReceives,
18526 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18527 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18528 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18529 	SET_MIB(old_ip_mib.ipForwDatagrams,
18530 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18531 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18532 	    ipmib->ipIfStatsInUnknownProtos);
18533 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18534 	SET_MIB(old_ip_mib.ipInDelivers,
18535 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18536 	SET_MIB(old_ip_mib.ipOutRequests,
18537 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18538 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18539 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18540 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18541 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18542 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18543 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18544 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18545 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18546 
18547 	/* ipRoutingDiscards is not being used */
18548 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18549 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18550 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18551 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18552 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18553 	    ipmib->ipIfStatsReasmDuplicates);
18554 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18555 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18556 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18557 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18558 	SET_MIB(old_ip_mib.rawipInOverflows,
18559 	    ipmib->rawipIfStatsInOverflows);
18560 
18561 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18562 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18563 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18564 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18565 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18566 	    ipmib->ipIfStatsOutSwitchIPVersion);
18567 
18568 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18569 	    (int)sizeof (old_ip_mib))) {
18570 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18571 		    (uint_t)sizeof (old_ip_mib)));
18572 	}
18573 
18574 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18575 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18576 	    (int)optp->level, (int)optp->name, (int)optp->len));
18577 	qreply(q, mpctl);
18578 	return (mp2ctl);
18579 }
18580 
18581 /* Per interface IPv4 statistics */
18582 static mblk_t *
18583 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18584 {
18585 	struct opthdr		*optp;
18586 	mblk_t			*mp2ctl;
18587 	ill_t			*ill;
18588 	ill_walk_context_t	ctx;
18589 	mblk_t			*mp_tail = NULL;
18590 	mib2_ipIfStatsEntry_t	global_ip_mib;
18591 
18592 	/*
18593 	 * Make a copy of the original message
18594 	 */
18595 	mp2ctl = copymsg(mpctl);
18596 
18597 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18598 	optp->level = MIB2_IP;
18599 	optp->name = MIB2_IP_TRAFFIC_STATS;
18600 	/* Include "unknown interface" ip_mib */
18601 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18602 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18603 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18604 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18605 	    (ipst->ips_ip_g_forward ? 1 : 2));
18606 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18607 	    (uint32_t)ipst->ips_ip_def_ttl);
18608 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18609 	    sizeof (mib2_ipIfStatsEntry_t));
18610 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18611 	    sizeof (mib2_ipAddrEntry_t));
18612 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18613 	    sizeof (mib2_ipRouteEntry_t));
18614 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18615 	    sizeof (mib2_ipNetToMediaEntry_t));
18616 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18617 	    sizeof (ip_member_t));
18618 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18619 	    sizeof (ip_grpsrc_t));
18620 
18621 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18622 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18623 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18624 		    "failed to allocate %u bytes\n",
18625 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18626 	}
18627 
18628 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18629 
18630 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18631 	ill = ILL_START_WALK_V4(&ctx, ipst);
18632 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18633 		ill->ill_ip_mib->ipIfStatsIfIndex =
18634 		    ill->ill_phyint->phyint_ifindex;
18635 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18636 		    (ipst->ips_ip_g_forward ? 1 : 2));
18637 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18638 		    (uint32_t)ipst->ips_ip_def_ttl);
18639 
18640 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18641 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18642 		    (char *)ill->ill_ip_mib,
18643 		    (int)sizeof (*ill->ill_ip_mib))) {
18644 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18645 			    "failed to allocate %u bytes\n",
18646 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18647 		}
18648 	}
18649 	rw_exit(&ipst->ips_ill_g_lock);
18650 
18651 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18652 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18653 	    "level %d, name %d, len %d\n",
18654 	    (int)optp->level, (int)optp->name, (int)optp->len));
18655 	qreply(q, mpctl);
18656 
18657 	if (mp2ctl == NULL)
18658 		return (NULL);
18659 
18660 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18661 }
18662 
18663 /* Global IPv4 ICMP statistics */
18664 static mblk_t *
18665 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18666 {
18667 	struct opthdr		*optp;
18668 	mblk_t			*mp2ctl;
18669 
18670 	/*
18671 	 * Make a copy of the original message
18672 	 */
18673 	mp2ctl = copymsg(mpctl);
18674 
18675 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18676 	optp->level = MIB2_ICMP;
18677 	optp->name = 0;
18678 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18679 	    (int)sizeof (ipst->ips_icmp_mib))) {
18680 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18681 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18682 	}
18683 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18684 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18685 	    (int)optp->level, (int)optp->name, (int)optp->len));
18686 	qreply(q, mpctl);
18687 	return (mp2ctl);
18688 }
18689 
18690 /* Global IPv4 IGMP statistics */
18691 static mblk_t *
18692 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18693 {
18694 	struct opthdr		*optp;
18695 	mblk_t			*mp2ctl;
18696 
18697 	/*
18698 	 * make a copy of the original message
18699 	 */
18700 	mp2ctl = copymsg(mpctl);
18701 
18702 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18703 	optp->level = EXPER_IGMP;
18704 	optp->name = 0;
18705 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18706 	    (int)sizeof (ipst->ips_igmpstat))) {
18707 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18708 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18709 	}
18710 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18711 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18712 	    (int)optp->level, (int)optp->name, (int)optp->len));
18713 	qreply(q, mpctl);
18714 	return (mp2ctl);
18715 }
18716 
18717 /* Global IPv4 Multicast Routing statistics */
18718 static mblk_t *
18719 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18720 {
18721 	struct opthdr		*optp;
18722 	mblk_t			*mp2ctl;
18723 
18724 	/*
18725 	 * make a copy of the original message
18726 	 */
18727 	mp2ctl = copymsg(mpctl);
18728 
18729 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18730 	optp->level = EXPER_DVMRP;
18731 	optp->name = 0;
18732 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18733 		ip0dbg(("ip_mroute_stats: failed\n"));
18734 	}
18735 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18736 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18737 	    (int)optp->level, (int)optp->name, (int)optp->len));
18738 	qreply(q, mpctl);
18739 	return (mp2ctl);
18740 }
18741 
18742 /* IPv4 address information */
18743 static mblk_t *
18744 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18745 {
18746 	struct opthdr		*optp;
18747 	mblk_t			*mp2ctl;
18748 	mblk_t			*mp_tail = NULL;
18749 	ill_t			*ill;
18750 	ipif_t			*ipif;
18751 	uint_t			bitval;
18752 	mib2_ipAddrEntry_t	mae;
18753 	zoneid_t		zoneid;
18754 	ill_walk_context_t ctx;
18755 
18756 	/*
18757 	 * make a copy of the original message
18758 	 */
18759 	mp2ctl = copymsg(mpctl);
18760 
18761 	/* ipAddrEntryTable */
18762 
18763 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18764 	optp->level = MIB2_IP;
18765 	optp->name = MIB2_IP_ADDR;
18766 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18767 
18768 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18769 	ill = ILL_START_WALK_V4(&ctx, ipst);
18770 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18771 		for (ipif = ill->ill_ipif; ipif != NULL;
18772 		    ipif = ipif->ipif_next) {
18773 			if (ipif->ipif_zoneid != zoneid &&
18774 			    ipif->ipif_zoneid != ALL_ZONES)
18775 				continue;
18776 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18777 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18778 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18779 
18780 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18781 			    OCTET_LENGTH);
18782 			mae.ipAdEntIfIndex.o_length =
18783 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18784 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18785 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18786 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18787 			mae.ipAdEntInfo.ae_subnet_len =
18788 			    ip_mask_to_plen(ipif->ipif_net_mask);
18789 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18790 			for (bitval = 1;
18791 			    bitval &&
18792 			    !(bitval & ipif->ipif_brd_addr);
18793 			    bitval <<= 1)
18794 				noop;
18795 			mae.ipAdEntBcastAddr = bitval;
18796 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18797 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18798 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18799 			mae.ipAdEntInfo.ae_broadcast_addr =
18800 			    ipif->ipif_brd_addr;
18801 			mae.ipAdEntInfo.ae_pp_dst_addr =
18802 			    ipif->ipif_pp_dst_addr;
18803 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18804 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18805 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18806 
18807 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18808 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18809 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18810 				    "allocate %u bytes\n",
18811 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18812 			}
18813 		}
18814 	}
18815 	rw_exit(&ipst->ips_ill_g_lock);
18816 
18817 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18818 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18819 	    (int)optp->level, (int)optp->name, (int)optp->len));
18820 	qreply(q, mpctl);
18821 	return (mp2ctl);
18822 }
18823 
18824 /* IPv6 address information */
18825 static mblk_t *
18826 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18827 {
18828 	struct opthdr		*optp;
18829 	mblk_t			*mp2ctl;
18830 	mblk_t			*mp_tail = NULL;
18831 	ill_t			*ill;
18832 	ipif_t			*ipif;
18833 	mib2_ipv6AddrEntry_t	mae6;
18834 	zoneid_t		zoneid;
18835 	ill_walk_context_t	ctx;
18836 
18837 	/*
18838 	 * make a copy of the original message
18839 	 */
18840 	mp2ctl = copymsg(mpctl);
18841 
18842 	/* ipv6AddrEntryTable */
18843 
18844 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18845 	optp->level = MIB2_IP6;
18846 	optp->name = MIB2_IP6_ADDR;
18847 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18848 
18849 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18850 	ill = ILL_START_WALK_V6(&ctx, ipst);
18851 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18852 		for (ipif = ill->ill_ipif; ipif != NULL;
18853 		    ipif = ipif->ipif_next) {
18854 			if (ipif->ipif_zoneid != zoneid &&
18855 			    ipif->ipif_zoneid != ALL_ZONES)
18856 				continue;
18857 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18858 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18859 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18860 
18861 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18862 			    OCTET_LENGTH);
18863 			mae6.ipv6AddrIfIndex.o_length =
18864 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18865 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18866 			mae6.ipv6AddrPfxLength =
18867 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18868 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18869 			mae6.ipv6AddrInfo.ae_subnet_len =
18870 			    mae6.ipv6AddrPfxLength;
18871 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18872 
18873 			/* Type: stateless(1), stateful(2), unknown(3) */
18874 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18875 				mae6.ipv6AddrType = 1;
18876 			else
18877 				mae6.ipv6AddrType = 2;
18878 			/* Anycast: true(1), false(2) */
18879 			if (ipif->ipif_flags & IPIF_ANYCAST)
18880 				mae6.ipv6AddrAnycastFlag = 1;
18881 			else
18882 				mae6.ipv6AddrAnycastFlag = 2;
18883 
18884 			/*
18885 			 * Address status: preferred(1), deprecated(2),
18886 			 * invalid(3), inaccessible(4), unknown(5)
18887 			 */
18888 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18889 				mae6.ipv6AddrStatus = 3;
18890 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18891 				mae6.ipv6AddrStatus = 2;
18892 			else
18893 				mae6.ipv6AddrStatus = 1;
18894 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18895 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18896 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18897 			    ipif->ipif_v6pp_dst_addr;
18898 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18899 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18900 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18901 			mae6.ipv6AddrIdentifier = ill->ill_token;
18902 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18903 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18904 			mae6.ipv6AddrRetransmitTime =
18905 			    ill->ill_reachable_retrans_time;
18906 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18907 			    (char *)&mae6,
18908 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18909 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18910 				    "allocate %u bytes\n",
18911 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18912 			}
18913 		}
18914 	}
18915 	rw_exit(&ipst->ips_ill_g_lock);
18916 
18917 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18918 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18919 	    (int)optp->level, (int)optp->name, (int)optp->len));
18920 	qreply(q, mpctl);
18921 	return (mp2ctl);
18922 }
18923 
18924 /* IPv4 multicast group membership. */
18925 static mblk_t *
18926 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18927 {
18928 	struct opthdr		*optp;
18929 	mblk_t			*mp2ctl;
18930 	ill_t			*ill;
18931 	ipif_t			*ipif;
18932 	ilm_t			*ilm;
18933 	ip_member_t		ipm;
18934 	mblk_t			*mp_tail = NULL;
18935 	ill_walk_context_t	ctx;
18936 	zoneid_t		zoneid;
18937 	ilm_walker_t		ilw;
18938 
18939 	/*
18940 	 * make a copy of the original message
18941 	 */
18942 	mp2ctl = copymsg(mpctl);
18943 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18944 
18945 	/* ipGroupMember table */
18946 	optp = (struct opthdr *)&mpctl->b_rptr[
18947 	    sizeof (struct T_optmgmt_ack)];
18948 	optp->level = MIB2_IP;
18949 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18950 
18951 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18952 	ill = ILL_START_WALK_V4(&ctx, ipst);
18953 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18954 		if (IS_UNDER_IPMP(ill))
18955 			continue;
18956 
18957 		ilm = ilm_walker_start(&ilw, ill);
18958 		for (ipif = ill->ill_ipif; ipif != NULL;
18959 		    ipif = ipif->ipif_next) {
18960 			if (ipif->ipif_zoneid != zoneid &&
18961 			    ipif->ipif_zoneid != ALL_ZONES)
18962 				continue;	/* not this zone */
18963 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18964 			    OCTET_LENGTH);
18965 			ipm.ipGroupMemberIfIndex.o_length =
18966 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18967 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
18968 				ASSERT(ilm->ilm_ipif != NULL);
18969 				ASSERT(ilm->ilm_ill == NULL);
18970 				if (ilm->ilm_ipif != ipif)
18971 					continue;
18972 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18973 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18974 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18975 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18976 				    (char *)&ipm, (int)sizeof (ipm))) {
18977 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18978 					    "failed to allocate %u bytes\n",
18979 					    (uint_t)sizeof (ipm)));
18980 				}
18981 			}
18982 		}
18983 		ilm_walker_finish(&ilw);
18984 	}
18985 	rw_exit(&ipst->ips_ill_g_lock);
18986 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18987 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18988 	    (int)optp->level, (int)optp->name, (int)optp->len));
18989 	qreply(q, mpctl);
18990 	return (mp2ctl);
18991 }
18992 
18993 /* IPv6 multicast group membership. */
18994 static mblk_t *
18995 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18996 {
18997 	struct opthdr		*optp;
18998 	mblk_t			*mp2ctl;
18999 	ill_t			*ill;
19000 	ilm_t			*ilm;
19001 	ipv6_member_t		ipm6;
19002 	mblk_t			*mp_tail = NULL;
19003 	ill_walk_context_t	ctx;
19004 	zoneid_t		zoneid;
19005 	ilm_walker_t		ilw;
19006 
19007 	/*
19008 	 * make a copy of the original message
19009 	 */
19010 	mp2ctl = copymsg(mpctl);
19011 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19012 
19013 	/* ip6GroupMember table */
19014 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19015 	optp->level = MIB2_IP6;
19016 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19017 
19018 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19019 	ill = ILL_START_WALK_V6(&ctx, ipst);
19020 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19021 		if (IS_UNDER_IPMP(ill))
19022 			continue;
19023 
19024 		ilm = ilm_walker_start(&ilw, ill);
19025 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19026 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19027 			ASSERT(ilm->ilm_ipif == NULL);
19028 			ASSERT(ilm->ilm_ill != NULL);
19029 			if (ilm->ilm_zoneid != zoneid)
19030 				continue;	/* not this zone */
19031 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19032 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19033 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19034 			if (!snmp_append_data2(mpctl->b_cont,
19035 			    &mp_tail,
19036 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19037 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19038 				    "failed to allocate %u bytes\n",
19039 				    (uint_t)sizeof (ipm6)));
19040 			}
19041 		}
19042 		ilm_walker_finish(&ilw);
19043 	}
19044 	rw_exit(&ipst->ips_ill_g_lock);
19045 
19046 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19047 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19048 	    (int)optp->level, (int)optp->name, (int)optp->len));
19049 	qreply(q, mpctl);
19050 	return (mp2ctl);
19051 }
19052 
19053 /* IP multicast filtered sources */
19054 static mblk_t *
19055 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19056 {
19057 	struct opthdr		*optp;
19058 	mblk_t			*mp2ctl;
19059 	ill_t			*ill;
19060 	ipif_t			*ipif;
19061 	ilm_t			*ilm;
19062 	ip_grpsrc_t		ips;
19063 	mblk_t			*mp_tail = NULL;
19064 	ill_walk_context_t	ctx;
19065 	zoneid_t		zoneid;
19066 	int			i;
19067 	slist_t			*sl;
19068 	ilm_walker_t		ilw;
19069 
19070 	/*
19071 	 * make a copy of the original message
19072 	 */
19073 	mp2ctl = copymsg(mpctl);
19074 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19075 
19076 	/* ipGroupSource table */
19077 	optp = (struct opthdr *)&mpctl->b_rptr[
19078 	    sizeof (struct T_optmgmt_ack)];
19079 	optp->level = MIB2_IP;
19080 	optp->name = EXPER_IP_GROUP_SOURCES;
19081 
19082 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19083 	ill = ILL_START_WALK_V4(&ctx, ipst);
19084 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19085 		if (IS_UNDER_IPMP(ill))
19086 			continue;
19087 
19088 		ilm = ilm_walker_start(&ilw, ill);
19089 		for (ipif = ill->ill_ipif; ipif != NULL;
19090 		    ipif = ipif->ipif_next) {
19091 			if (ipif->ipif_zoneid != zoneid)
19092 				continue;	/* not this zone */
19093 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19094 			    OCTET_LENGTH);
19095 			ips.ipGroupSourceIfIndex.o_length =
19096 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19097 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19098 				ASSERT(ilm->ilm_ipif != NULL);
19099 				ASSERT(ilm->ilm_ill == NULL);
19100 				sl = ilm->ilm_filter;
19101 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19102 					continue;
19103 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19104 				for (i = 0; i < sl->sl_numsrc; i++) {
19105 					if (!IN6_IS_ADDR_V4MAPPED(
19106 					    &sl->sl_addr[i]))
19107 						continue;
19108 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19109 					    ips.ipGroupSourceAddress);
19110 					if (snmp_append_data2(mpctl->b_cont,
19111 					    &mp_tail, (char *)&ips,
19112 					    (int)sizeof (ips)) == 0) {
19113 						ip1dbg(("ip_snmp_get_mib2_"
19114 						    "ip_group_src: failed to "
19115 						    "allocate %u bytes\n",
19116 						    (uint_t)sizeof (ips)));
19117 					}
19118 				}
19119 			}
19120 		}
19121 		ilm_walker_finish(&ilw);
19122 	}
19123 	rw_exit(&ipst->ips_ill_g_lock);
19124 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19125 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19126 	    (int)optp->level, (int)optp->name, (int)optp->len));
19127 	qreply(q, mpctl);
19128 	return (mp2ctl);
19129 }
19130 
19131 /* IPv6 multicast filtered sources. */
19132 static mblk_t *
19133 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19134 {
19135 	struct opthdr		*optp;
19136 	mblk_t			*mp2ctl;
19137 	ill_t			*ill;
19138 	ilm_t			*ilm;
19139 	ipv6_grpsrc_t		ips6;
19140 	mblk_t			*mp_tail = NULL;
19141 	ill_walk_context_t	ctx;
19142 	zoneid_t		zoneid;
19143 	int			i;
19144 	slist_t			*sl;
19145 	ilm_walker_t		ilw;
19146 
19147 	/*
19148 	 * make a copy of the original message
19149 	 */
19150 	mp2ctl = copymsg(mpctl);
19151 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19152 
19153 	/* ip6GroupMember table */
19154 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19155 	optp->level = MIB2_IP6;
19156 	optp->name = EXPER_IP6_GROUP_SOURCES;
19157 
19158 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19159 	ill = ILL_START_WALK_V6(&ctx, ipst);
19160 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19161 		if (IS_UNDER_IPMP(ill))
19162 			continue;
19163 
19164 		ilm = ilm_walker_start(&ilw, ill);
19165 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19166 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19167 			ASSERT(ilm->ilm_ipif == NULL);
19168 			ASSERT(ilm->ilm_ill != NULL);
19169 			sl = ilm->ilm_filter;
19170 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19171 				continue;
19172 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19173 			for (i = 0; i < sl->sl_numsrc; i++) {
19174 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19175 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19176 				    (char *)&ips6, (int)sizeof (ips6))) {
19177 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19178 					    "group_src: failed to allocate "
19179 					    "%u bytes\n",
19180 					    (uint_t)sizeof (ips6)));
19181 				}
19182 			}
19183 		}
19184 		ilm_walker_finish(&ilw);
19185 	}
19186 	rw_exit(&ipst->ips_ill_g_lock);
19187 
19188 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19189 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19190 	    (int)optp->level, (int)optp->name, (int)optp->len));
19191 	qreply(q, mpctl);
19192 	return (mp2ctl);
19193 }
19194 
19195 /* Multicast routing virtual interface table. */
19196 static mblk_t *
19197 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19198 {
19199 	struct opthdr		*optp;
19200 	mblk_t			*mp2ctl;
19201 
19202 	/*
19203 	 * make a copy of the original message
19204 	 */
19205 	mp2ctl = copymsg(mpctl);
19206 
19207 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19208 	optp->level = EXPER_DVMRP;
19209 	optp->name = EXPER_DVMRP_VIF;
19210 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19211 		ip0dbg(("ip_mroute_vif: failed\n"));
19212 	}
19213 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19214 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19215 	    (int)optp->level, (int)optp->name, (int)optp->len));
19216 	qreply(q, mpctl);
19217 	return (mp2ctl);
19218 }
19219 
19220 /* Multicast routing table. */
19221 static mblk_t *
19222 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19223 {
19224 	struct opthdr		*optp;
19225 	mblk_t			*mp2ctl;
19226 
19227 	/*
19228 	 * make a copy of the original message
19229 	 */
19230 	mp2ctl = copymsg(mpctl);
19231 
19232 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19233 	optp->level = EXPER_DVMRP;
19234 	optp->name = EXPER_DVMRP_MRT;
19235 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19236 		ip0dbg(("ip_mroute_mrt: failed\n"));
19237 	}
19238 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19239 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19240 	    (int)optp->level, (int)optp->name, (int)optp->len));
19241 	qreply(q, mpctl);
19242 	return (mp2ctl);
19243 }
19244 
19245 /*
19246  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19247  * in one IRE walk.
19248  */
19249 static mblk_t *
19250 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19251     ip_stack_t *ipst)
19252 {
19253 	struct opthdr	*optp;
19254 	mblk_t		*mp2ctl;	/* Returned */
19255 	mblk_t		*mp3ctl;	/* nettomedia */
19256 	mblk_t		*mp4ctl;	/* routeattrs */
19257 	iproutedata_t	ird;
19258 	zoneid_t	zoneid;
19259 
19260 	/*
19261 	 * make copies of the original message
19262 	 *	- mp2ctl is returned unchanged to the caller for his use
19263 	 *	- mpctl is sent upstream as ipRouteEntryTable
19264 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19265 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19266 	 */
19267 	mp2ctl = copymsg(mpctl);
19268 	mp3ctl = copymsg(mpctl);
19269 	mp4ctl = copymsg(mpctl);
19270 	if (mp3ctl == NULL || mp4ctl == NULL) {
19271 		freemsg(mp4ctl);
19272 		freemsg(mp3ctl);
19273 		freemsg(mp2ctl);
19274 		freemsg(mpctl);
19275 		return (NULL);
19276 	}
19277 
19278 	bzero(&ird, sizeof (ird));
19279 
19280 	ird.ird_route.lp_head = mpctl->b_cont;
19281 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19282 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19283 	/*
19284 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19285 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19286 	 * intended a temporary solution until a proper MIB API is provided
19287 	 * that provides complete filtering/caller-opt-in.
19288 	 */
19289 	if (level == EXPER_IP_AND_TESTHIDDEN)
19290 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19291 
19292 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19293 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19294 
19295 	/* ipRouteEntryTable in mpctl */
19296 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19297 	optp->level = MIB2_IP;
19298 	optp->name = MIB2_IP_ROUTE;
19299 	optp->len = msgdsize(ird.ird_route.lp_head);
19300 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19301 	    (int)optp->level, (int)optp->name, (int)optp->len));
19302 	qreply(q, mpctl);
19303 
19304 	/* ipNetToMediaEntryTable in mp3ctl */
19305 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19306 	optp->level = MIB2_IP;
19307 	optp->name = MIB2_IP_MEDIA;
19308 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19309 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19310 	    (int)optp->level, (int)optp->name, (int)optp->len));
19311 	qreply(q, mp3ctl);
19312 
19313 	/* ipRouteAttributeTable in mp4ctl */
19314 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19315 	optp->level = MIB2_IP;
19316 	optp->name = EXPER_IP_RTATTR;
19317 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19318 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19319 	    (int)optp->level, (int)optp->name, (int)optp->len));
19320 	if (optp->len == 0)
19321 		freemsg(mp4ctl);
19322 	else
19323 		qreply(q, mp4ctl);
19324 
19325 	return (mp2ctl);
19326 }
19327 
19328 /*
19329  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19330  * ipv6NetToMediaEntryTable in an NDP walk.
19331  */
19332 static mblk_t *
19333 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19334     ip_stack_t *ipst)
19335 {
19336 	struct opthdr	*optp;
19337 	mblk_t		*mp2ctl;	/* Returned */
19338 	mblk_t		*mp3ctl;	/* nettomedia */
19339 	mblk_t		*mp4ctl;	/* routeattrs */
19340 	iproutedata_t	ird;
19341 	zoneid_t	zoneid;
19342 
19343 	/*
19344 	 * make copies of the original message
19345 	 *	- mp2ctl is returned unchanged to the caller for his use
19346 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19347 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19348 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19349 	 */
19350 	mp2ctl = copymsg(mpctl);
19351 	mp3ctl = copymsg(mpctl);
19352 	mp4ctl = copymsg(mpctl);
19353 	if (mp3ctl == NULL || mp4ctl == NULL) {
19354 		freemsg(mp4ctl);
19355 		freemsg(mp3ctl);
19356 		freemsg(mp2ctl);
19357 		freemsg(mpctl);
19358 		return (NULL);
19359 	}
19360 
19361 	bzero(&ird, sizeof (ird));
19362 
19363 	ird.ird_route.lp_head = mpctl->b_cont;
19364 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19365 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19366 	/*
19367 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19368 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19369 	 * intended a temporary solution until a proper MIB API is provided
19370 	 * that provides complete filtering/caller-opt-in.
19371 	 */
19372 	if (level == EXPER_IP_AND_TESTHIDDEN)
19373 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19374 
19375 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19376 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19377 
19378 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19379 	optp->level = MIB2_IP6;
19380 	optp->name = MIB2_IP6_ROUTE;
19381 	optp->len = msgdsize(ird.ird_route.lp_head);
19382 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19383 	    (int)optp->level, (int)optp->name, (int)optp->len));
19384 	qreply(q, mpctl);
19385 
19386 	/* ipv6NetToMediaEntryTable in mp3ctl */
19387 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19388 
19389 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19390 	optp->level = MIB2_IP6;
19391 	optp->name = MIB2_IP6_MEDIA;
19392 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19393 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19394 	    (int)optp->level, (int)optp->name, (int)optp->len));
19395 	qreply(q, mp3ctl);
19396 
19397 	/* ipv6RouteAttributeTable in mp4ctl */
19398 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19399 	optp->level = MIB2_IP6;
19400 	optp->name = EXPER_IP_RTATTR;
19401 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19402 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19403 	    (int)optp->level, (int)optp->name, (int)optp->len));
19404 	if (optp->len == 0)
19405 		freemsg(mp4ctl);
19406 	else
19407 		qreply(q, mp4ctl);
19408 
19409 	return (mp2ctl);
19410 }
19411 
19412 /*
19413  * IPv6 mib: One per ill
19414  */
19415 static mblk_t *
19416 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19417 {
19418 	struct opthdr		*optp;
19419 	mblk_t			*mp2ctl;
19420 	ill_t			*ill;
19421 	ill_walk_context_t	ctx;
19422 	mblk_t			*mp_tail = NULL;
19423 
19424 	/*
19425 	 * Make a copy of the original message
19426 	 */
19427 	mp2ctl = copymsg(mpctl);
19428 
19429 	/* fixed length IPv6 structure ... */
19430 
19431 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19432 	optp->level = MIB2_IP6;
19433 	optp->name = 0;
19434 	/* Include "unknown interface" ip6_mib */
19435 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19436 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19437 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19438 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19439 	    ipst->ips_ipv6_forward ? 1 : 2);
19440 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19441 	    ipst->ips_ipv6_def_hops);
19442 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19443 	    sizeof (mib2_ipIfStatsEntry_t));
19444 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19445 	    sizeof (mib2_ipv6AddrEntry_t));
19446 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19447 	    sizeof (mib2_ipv6RouteEntry_t));
19448 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19449 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19450 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19451 	    sizeof (ipv6_member_t));
19452 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19453 	    sizeof (ipv6_grpsrc_t));
19454 
19455 	/*
19456 	 * Synchronize 64- and 32-bit counters
19457 	 */
19458 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19459 	    ipIfStatsHCInReceives);
19460 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19461 	    ipIfStatsHCInDelivers);
19462 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19463 	    ipIfStatsHCOutRequests);
19464 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19465 	    ipIfStatsHCOutForwDatagrams);
19466 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19467 	    ipIfStatsHCOutMcastPkts);
19468 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19469 	    ipIfStatsHCInMcastPkts);
19470 
19471 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19472 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19473 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19474 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19475 	}
19476 
19477 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19478 	ill = ILL_START_WALK_V6(&ctx, ipst);
19479 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19480 		ill->ill_ip_mib->ipIfStatsIfIndex =
19481 		    ill->ill_phyint->phyint_ifindex;
19482 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19483 		    ipst->ips_ipv6_forward ? 1 : 2);
19484 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19485 		    ill->ill_max_hops);
19486 
19487 		/*
19488 		 * Synchronize 64- and 32-bit counters
19489 		 */
19490 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19491 		    ipIfStatsHCInReceives);
19492 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19493 		    ipIfStatsHCInDelivers);
19494 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19495 		    ipIfStatsHCOutRequests);
19496 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19497 		    ipIfStatsHCOutForwDatagrams);
19498 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19499 		    ipIfStatsHCOutMcastPkts);
19500 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19501 		    ipIfStatsHCInMcastPkts);
19502 
19503 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19504 		    (char *)ill->ill_ip_mib,
19505 		    (int)sizeof (*ill->ill_ip_mib))) {
19506 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19507 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19508 		}
19509 	}
19510 	rw_exit(&ipst->ips_ill_g_lock);
19511 
19512 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19513 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19514 	    (int)optp->level, (int)optp->name, (int)optp->len));
19515 	qreply(q, mpctl);
19516 	return (mp2ctl);
19517 }
19518 
19519 /*
19520  * ICMPv6 mib: One per ill
19521  */
19522 static mblk_t *
19523 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19524 {
19525 	struct opthdr		*optp;
19526 	mblk_t			*mp2ctl;
19527 	ill_t			*ill;
19528 	ill_walk_context_t	ctx;
19529 	mblk_t			*mp_tail = NULL;
19530 	/*
19531 	 * Make a copy of the original message
19532 	 */
19533 	mp2ctl = copymsg(mpctl);
19534 
19535 	/* fixed length ICMPv6 structure ... */
19536 
19537 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19538 	optp->level = MIB2_ICMP6;
19539 	optp->name = 0;
19540 	/* Include "unknown interface" icmp6_mib */
19541 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19542 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19543 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19544 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19545 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19546 	    (char *)&ipst->ips_icmp6_mib,
19547 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19548 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19549 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19550 	}
19551 
19552 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19553 	ill = ILL_START_WALK_V6(&ctx, ipst);
19554 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19555 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19556 		    ill->ill_phyint->phyint_ifindex;
19557 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19558 		    (char *)ill->ill_icmp6_mib,
19559 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19560 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19561 			    "%u bytes\n",
19562 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19563 		}
19564 	}
19565 	rw_exit(&ipst->ips_ill_g_lock);
19566 
19567 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19568 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19569 	    (int)optp->level, (int)optp->name, (int)optp->len));
19570 	qreply(q, mpctl);
19571 	return (mp2ctl);
19572 }
19573 
19574 /*
19575  * ire_walk routine to create both ipRouteEntryTable and
19576  * ipRouteAttributeTable in one IRE walk
19577  */
19578 static void
19579 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19580 {
19581 	ill_t				*ill;
19582 	ipif_t				*ipif;
19583 	mib2_ipRouteEntry_t		*re;
19584 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19585 	ipaddr_t			gw_addr;
19586 	tsol_ire_gw_secattr_t		*attrp;
19587 	tsol_gc_t			*gc = NULL;
19588 	tsol_gcgrp_t			*gcgrp = NULL;
19589 	uint_t				sacnt = 0;
19590 	int				i;
19591 
19592 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19593 
19594 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19595 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19596 		return;
19597 	}
19598 
19599 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19600 		return;
19601 
19602 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19603 		mutex_enter(&attrp->igsa_lock);
19604 		if ((gc = attrp->igsa_gc) != NULL) {
19605 			gcgrp = gc->gc_grp;
19606 			ASSERT(gcgrp != NULL);
19607 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19608 			sacnt = 1;
19609 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19610 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19611 			gc = gcgrp->gcgrp_head;
19612 			sacnt = gcgrp->gcgrp_count;
19613 		}
19614 		mutex_exit(&attrp->igsa_lock);
19615 
19616 		/* do nothing if there's no gc to report */
19617 		if (gc == NULL) {
19618 			ASSERT(sacnt == 0);
19619 			if (gcgrp != NULL) {
19620 				/* we might as well drop the lock now */
19621 				rw_exit(&gcgrp->gcgrp_rwlock);
19622 				gcgrp = NULL;
19623 			}
19624 			attrp = NULL;
19625 		}
19626 
19627 		ASSERT(gc == NULL || (gcgrp != NULL &&
19628 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19629 	}
19630 	ASSERT(sacnt == 0 || gc != NULL);
19631 
19632 	if (sacnt != 0 &&
19633 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19634 		kmem_free(re, sizeof (*re));
19635 		rw_exit(&gcgrp->gcgrp_rwlock);
19636 		return;
19637 	}
19638 
19639 	/*
19640 	 * Return all IRE types for route table... let caller pick and choose
19641 	 */
19642 	re->ipRouteDest = ire->ire_addr;
19643 	ipif = ire->ire_ipif;
19644 	re->ipRouteIfIndex.o_length = 0;
19645 	if (ire->ire_type == IRE_CACHE) {
19646 		ill = (ill_t *)ire->ire_stq->q_ptr;
19647 		re->ipRouteIfIndex.o_length =
19648 		    ill->ill_name_length == 0 ? 0 :
19649 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19650 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19651 		    re->ipRouteIfIndex.o_length);
19652 	} else if (ipif != NULL) {
19653 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19654 		re->ipRouteIfIndex.o_length =
19655 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19656 	}
19657 	re->ipRouteMetric1 = -1;
19658 	re->ipRouteMetric2 = -1;
19659 	re->ipRouteMetric3 = -1;
19660 	re->ipRouteMetric4 = -1;
19661 
19662 	gw_addr = ire->ire_gateway_addr;
19663 
19664 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19665 		re->ipRouteNextHop = ire->ire_src_addr;
19666 	else
19667 		re->ipRouteNextHop = gw_addr;
19668 	/* indirect(4), direct(3), or invalid(2) */
19669 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19670 		re->ipRouteType = 2;
19671 	else
19672 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19673 	re->ipRouteProto = -1;
19674 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19675 	re->ipRouteMask = ire->ire_mask;
19676 	re->ipRouteMetric5 = -1;
19677 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19678 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19679 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19680 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19681 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19682 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19683 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19684 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19685 
19686 	if (ire->ire_flags & RTF_DYNAMIC) {
19687 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19688 	} else {
19689 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19690 	}
19691 
19692 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19693 	    (char *)re, (int)sizeof (*re))) {
19694 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19695 		    (uint_t)sizeof (*re)));
19696 	}
19697 
19698 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19699 		iaeptr->iae_routeidx = ird->ird_idx;
19700 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19701 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19702 	}
19703 
19704 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19705 	    (char *)iae, sacnt * sizeof (*iae))) {
19706 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19707 		    (unsigned)(sacnt * sizeof (*iae))));
19708 	}
19709 
19710 	/* bump route index for next pass */
19711 	ird->ird_idx++;
19712 
19713 	kmem_free(re, sizeof (*re));
19714 	if (sacnt != 0)
19715 		kmem_free(iae, sacnt * sizeof (*iae));
19716 
19717 	if (gcgrp != NULL)
19718 		rw_exit(&gcgrp->gcgrp_rwlock);
19719 }
19720 
19721 /*
19722  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19723  */
19724 static void
19725 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19726 {
19727 	ill_t				*ill;
19728 	ipif_t				*ipif;
19729 	mib2_ipv6RouteEntry_t		*re;
19730 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19731 	in6_addr_t			gw_addr_v6;
19732 	tsol_ire_gw_secattr_t		*attrp;
19733 	tsol_gc_t			*gc = NULL;
19734 	tsol_gcgrp_t			*gcgrp = NULL;
19735 	uint_t				sacnt = 0;
19736 	int				i;
19737 
19738 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19739 
19740 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19741 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19742 		return;
19743 	}
19744 
19745 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19746 		return;
19747 
19748 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19749 		mutex_enter(&attrp->igsa_lock);
19750 		if ((gc = attrp->igsa_gc) != NULL) {
19751 			gcgrp = gc->gc_grp;
19752 			ASSERT(gcgrp != NULL);
19753 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19754 			sacnt = 1;
19755 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19756 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19757 			gc = gcgrp->gcgrp_head;
19758 			sacnt = gcgrp->gcgrp_count;
19759 		}
19760 		mutex_exit(&attrp->igsa_lock);
19761 
19762 		/* do nothing if there's no gc to report */
19763 		if (gc == NULL) {
19764 			ASSERT(sacnt == 0);
19765 			if (gcgrp != NULL) {
19766 				/* we might as well drop the lock now */
19767 				rw_exit(&gcgrp->gcgrp_rwlock);
19768 				gcgrp = NULL;
19769 			}
19770 			attrp = NULL;
19771 		}
19772 
19773 		ASSERT(gc == NULL || (gcgrp != NULL &&
19774 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19775 	}
19776 	ASSERT(sacnt == 0 || gc != NULL);
19777 
19778 	if (sacnt != 0 &&
19779 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19780 		kmem_free(re, sizeof (*re));
19781 		rw_exit(&gcgrp->gcgrp_rwlock);
19782 		return;
19783 	}
19784 
19785 	/*
19786 	 * Return all IRE types for route table... let caller pick and choose
19787 	 */
19788 	re->ipv6RouteDest = ire->ire_addr_v6;
19789 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19790 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19791 	re->ipv6RouteIfIndex.o_length = 0;
19792 	ipif = ire->ire_ipif;
19793 	if (ire->ire_type == IRE_CACHE) {
19794 		ill = (ill_t *)ire->ire_stq->q_ptr;
19795 		re->ipv6RouteIfIndex.o_length =
19796 		    ill->ill_name_length == 0 ? 0 :
19797 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19798 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19799 		    re->ipv6RouteIfIndex.o_length);
19800 	} else if (ipif != NULL) {
19801 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19802 		re->ipv6RouteIfIndex.o_length =
19803 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19804 	}
19805 
19806 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19807 
19808 	mutex_enter(&ire->ire_lock);
19809 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19810 	mutex_exit(&ire->ire_lock);
19811 
19812 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19813 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19814 	else
19815 		re->ipv6RouteNextHop = gw_addr_v6;
19816 
19817 	/* remote(4), local(3), or discard(2) */
19818 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19819 		re->ipv6RouteType = 2;
19820 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19821 		re->ipv6RouteType = 3;
19822 	else
19823 		re->ipv6RouteType = 4;
19824 
19825 	re->ipv6RouteProtocol	= -1;
19826 	re->ipv6RoutePolicy	= 0;
19827 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19828 	re->ipv6RouteNextHopRDI	= 0;
19829 	re->ipv6RouteWeight	= 0;
19830 	re->ipv6RouteMetric	= 0;
19831 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19832 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19833 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19834 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19835 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19836 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19837 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19838 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19839 
19840 	if (ire->ire_flags & RTF_DYNAMIC) {
19841 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19842 	} else {
19843 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19844 	}
19845 
19846 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19847 	    (char *)re, (int)sizeof (*re))) {
19848 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19849 		    (uint_t)sizeof (*re)));
19850 	}
19851 
19852 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19853 		iaeptr->iae_routeidx = ird->ird_idx;
19854 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19855 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19856 	}
19857 
19858 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19859 	    (char *)iae, sacnt * sizeof (*iae))) {
19860 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19861 		    (unsigned)(sacnt * sizeof (*iae))));
19862 	}
19863 
19864 	/* bump route index for next pass */
19865 	ird->ird_idx++;
19866 
19867 	kmem_free(re, sizeof (*re));
19868 	if (sacnt != 0)
19869 		kmem_free(iae, sacnt * sizeof (*iae));
19870 
19871 	if (gcgrp != NULL)
19872 		rw_exit(&gcgrp->gcgrp_rwlock);
19873 }
19874 
19875 /*
19876  * ndp_walk routine to create ipv6NetToMediaEntryTable
19877  */
19878 static int
19879 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19880 {
19881 	ill_t				*ill;
19882 	mib2_ipv6NetToMediaEntry_t	ntme;
19883 	dl_unitdata_req_t		*dl;
19884 
19885 	ill = nce->nce_ill;
19886 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19887 		return (0);
19888 
19889 	/*
19890 	 * Neighbor cache entry attached to IRE with on-link
19891 	 * destination.
19892 	 */
19893 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19894 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19895 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19896 	    (nce->nce_res_mp != NULL)) {
19897 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19898 		ntme.ipv6NetToMediaPhysAddress.o_length =
19899 		    dl->dl_dest_addr_length;
19900 	} else {
19901 		ntme.ipv6NetToMediaPhysAddress.o_length =
19902 		    ill->ill_phys_addr_length;
19903 	}
19904 	if (nce->nce_res_mp != NULL) {
19905 		bcopy((char *)nce->nce_res_mp->b_rptr +
19906 		    NCE_LL_ADDR_OFFSET(ill),
19907 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19908 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19909 	} else {
19910 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19911 		    ill->ill_phys_addr_length);
19912 	}
19913 	/*
19914 	 * Note: Returns ND_* states. Should be:
19915 	 * reachable(1), stale(2), delay(3), probe(4),
19916 	 * invalid(5), unknown(6)
19917 	 */
19918 	ntme.ipv6NetToMediaState = nce->nce_state;
19919 	ntme.ipv6NetToMediaLastUpdated = 0;
19920 
19921 	/* other(1), dynamic(2), static(3), local(4) */
19922 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19923 		ntme.ipv6NetToMediaType = 4;
19924 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19925 		ntme.ipv6NetToMediaType = 1;
19926 	} else {
19927 		ntme.ipv6NetToMediaType = 2;
19928 	}
19929 
19930 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19931 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19932 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19933 		    (uint_t)sizeof (ntme)));
19934 	}
19935 	return (0);
19936 }
19937 
19938 /*
19939  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19940  */
19941 /* ARGSUSED */
19942 int
19943 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19944 {
19945 	switch (level) {
19946 	case MIB2_IP:
19947 	case MIB2_ICMP:
19948 		switch (name) {
19949 		default:
19950 			break;
19951 		}
19952 		return (1);
19953 	default:
19954 		return (1);
19955 	}
19956 }
19957 
19958 /*
19959  * When there exists both a 64- and 32-bit counter of a particular type
19960  * (i.e., InReceives), only the 64-bit counters are added.
19961  */
19962 void
19963 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19964 {
19965 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19966 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19967 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19968 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19969 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19970 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19971 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19972 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19973 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19974 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19975 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19976 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19977 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19978 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19979 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19980 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19981 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19982 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19983 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19984 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19985 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19986 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19987 	    o2->ipIfStatsInWrongIPVersion);
19988 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19989 	    o2->ipIfStatsInWrongIPVersion);
19990 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19991 	    o2->ipIfStatsOutSwitchIPVersion);
19992 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19993 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19994 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19995 	    o2->ipIfStatsHCInForwDatagrams);
19996 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19997 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19998 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19999 	    o2->ipIfStatsHCOutForwDatagrams);
20000 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20001 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20002 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20003 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20004 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20005 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20006 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20007 	    o2->ipIfStatsHCOutMcastOctets);
20008 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20009 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20010 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20011 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20012 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20013 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20014 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20015 }
20016 
20017 void
20018 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20019 {
20020 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20021 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20022 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20023 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20024 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20025 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20026 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20027 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20028 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20029 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20030 	    o2->ipv6IfIcmpInRouterSolicits);
20031 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20032 	    o2->ipv6IfIcmpInRouterAdvertisements);
20033 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20034 	    o2->ipv6IfIcmpInNeighborSolicits);
20035 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20036 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20037 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20038 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20039 	    o2->ipv6IfIcmpInGroupMembQueries);
20040 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20041 	    o2->ipv6IfIcmpInGroupMembResponses);
20042 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20043 	    o2->ipv6IfIcmpInGroupMembReductions);
20044 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20045 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20046 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20047 	    o2->ipv6IfIcmpOutDestUnreachs);
20048 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20049 	    o2->ipv6IfIcmpOutAdminProhibs);
20050 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20051 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20052 	    o2->ipv6IfIcmpOutParmProblems);
20053 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20054 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20055 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20056 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20057 	    o2->ipv6IfIcmpOutRouterSolicits);
20058 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20059 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20060 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20061 	    o2->ipv6IfIcmpOutNeighborSolicits);
20062 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20063 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20064 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20065 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20066 	    o2->ipv6IfIcmpOutGroupMembQueries);
20067 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20068 	    o2->ipv6IfIcmpOutGroupMembResponses);
20069 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20070 	    o2->ipv6IfIcmpOutGroupMembReductions);
20071 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20072 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20073 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20074 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20075 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20076 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20077 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20078 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20079 	    o2->ipv6IfIcmpInGroupMembTotal);
20080 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20081 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20082 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20083 	    o2->ipv6IfIcmpInGroupMembBadReports);
20084 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20085 	    o2->ipv6IfIcmpInGroupMembOurReports);
20086 }
20087 
20088 /*
20089  * Called before the options are updated to check if this packet will
20090  * be source routed from here.
20091  * This routine assumes that the options are well formed i.e. that they
20092  * have already been checked.
20093  */
20094 static boolean_t
20095 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20096 {
20097 	ipoptp_t	opts;
20098 	uchar_t		*opt;
20099 	uint8_t		optval;
20100 	uint8_t		optlen;
20101 	ipaddr_t	dst;
20102 	ire_t		*ire;
20103 
20104 	if (IS_SIMPLE_IPH(ipha)) {
20105 		ip2dbg(("not source routed\n"));
20106 		return (B_FALSE);
20107 	}
20108 	dst = ipha->ipha_dst;
20109 	for (optval = ipoptp_first(&opts, ipha);
20110 	    optval != IPOPT_EOL;
20111 	    optval = ipoptp_next(&opts)) {
20112 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20113 		opt = opts.ipoptp_cur;
20114 		optlen = opts.ipoptp_len;
20115 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20116 		    optval, optlen));
20117 		switch (optval) {
20118 			uint32_t off;
20119 		case IPOPT_SSRR:
20120 		case IPOPT_LSRR:
20121 			/*
20122 			 * If dst is one of our addresses and there are some
20123 			 * entries left in the source route return (true).
20124 			 */
20125 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20126 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20127 			if (ire == NULL) {
20128 				ip2dbg(("ip_source_routed: not next"
20129 				    " source route 0x%x\n",
20130 				    ntohl(dst)));
20131 				return (B_FALSE);
20132 			}
20133 			ire_refrele(ire);
20134 			off = opt[IPOPT_OFFSET];
20135 			off--;
20136 			if (optlen < IP_ADDR_LEN ||
20137 			    off > optlen - IP_ADDR_LEN) {
20138 				/* End of source route */
20139 				ip1dbg(("ip_source_routed: end of SR\n"));
20140 				return (B_FALSE);
20141 			}
20142 			return (B_TRUE);
20143 		}
20144 	}
20145 	ip2dbg(("not source routed\n"));
20146 	return (B_FALSE);
20147 }
20148 
20149 /*
20150  * Check if the packet contains any source route.
20151  */
20152 static boolean_t
20153 ip_source_route_included(ipha_t *ipha)
20154 {
20155 	ipoptp_t	opts;
20156 	uint8_t		optval;
20157 
20158 	if (IS_SIMPLE_IPH(ipha))
20159 		return (B_FALSE);
20160 	for (optval = ipoptp_first(&opts, ipha);
20161 	    optval != IPOPT_EOL;
20162 	    optval = ipoptp_next(&opts)) {
20163 		switch (optval) {
20164 		case IPOPT_SSRR:
20165 		case IPOPT_LSRR:
20166 			return (B_TRUE);
20167 		}
20168 	}
20169 	return (B_FALSE);
20170 }
20171 
20172 /*
20173  * Called when the IRE expiration timer fires.
20174  */
20175 void
20176 ip_trash_timer_expire(void *args)
20177 {
20178 	int			flush_flag = 0;
20179 	ire_expire_arg_t	iea;
20180 	ip_stack_t		*ipst = (ip_stack_t *)args;
20181 
20182 	iea.iea_ipst = ipst;	/* No netstack_hold */
20183 
20184 	/*
20185 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20186 	 * This lock makes sure that a new invocation of this function
20187 	 * that occurs due to an almost immediate timer firing will not
20188 	 * progress beyond this point until the current invocation is done
20189 	 */
20190 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20191 	ipst->ips_ip_ire_expire_id = 0;
20192 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20193 
20194 	/* Periodic timer */
20195 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20196 	    ipst->ips_ip_ire_arp_interval) {
20197 		/*
20198 		 * Remove all IRE_CACHE entries since they might
20199 		 * contain arp information.
20200 		 */
20201 		flush_flag |= FLUSH_ARP_TIME;
20202 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20203 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20204 	}
20205 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20206 	    ipst->ips_ip_ire_redir_interval) {
20207 		/* Remove all redirects */
20208 		flush_flag |= FLUSH_REDIRECT_TIME;
20209 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20210 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20211 	}
20212 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20213 	    ipst->ips_ip_ire_pathmtu_interval) {
20214 		/* Increase path mtu */
20215 		flush_flag |= FLUSH_MTU_TIME;
20216 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20217 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20218 	}
20219 
20220 	/*
20221 	 * Optimize for the case when there are no redirects in the
20222 	 * ftable, that is, no need to walk the ftable in that case.
20223 	 */
20224 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20225 		iea.iea_flush_flag = flush_flag;
20226 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20227 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20228 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20229 		    NULL, ALL_ZONES, ipst);
20230 	}
20231 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20232 	    ipst->ips_ip_redirect_cnt > 0) {
20233 		iea.iea_flush_flag = flush_flag;
20234 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20235 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20236 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20237 	}
20238 	if (flush_flag & FLUSH_MTU_TIME) {
20239 		/*
20240 		 * Walk all IPv6 IRE's and update them
20241 		 * Note that ARP and redirect timers are not
20242 		 * needed since NUD handles stale entries.
20243 		 */
20244 		flush_flag = FLUSH_MTU_TIME;
20245 		iea.iea_flush_flag = flush_flag;
20246 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20247 		    ALL_ZONES, ipst);
20248 	}
20249 
20250 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20251 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20252 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20253 
20254 	/*
20255 	 * Hold the lock to serialize timeout calls and prevent
20256 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20257 	 * for the timer to fire and a new invocation of this function
20258 	 * to start before the return value of timeout has been stored
20259 	 * in ip_ire_expire_id by the current invocation.
20260 	 */
20261 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20262 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20263 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20264 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20265 }
20266 
20267 /*
20268  * Called by the memory allocator subsystem directly, when the system
20269  * is running low on memory.
20270  */
20271 /* ARGSUSED */
20272 void
20273 ip_trash_ire_reclaim(void *args)
20274 {
20275 	netstack_handle_t nh;
20276 	netstack_t *ns;
20277 
20278 	netstack_next_init(&nh);
20279 	while ((ns = netstack_next(&nh)) != NULL) {
20280 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20281 		netstack_rele(ns);
20282 	}
20283 	netstack_next_fini(&nh);
20284 }
20285 
20286 static void
20287 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20288 {
20289 	ire_cache_count_t icc;
20290 	ire_cache_reclaim_t icr;
20291 	ncc_cache_count_t ncc;
20292 	nce_cache_reclaim_t ncr;
20293 	uint_t delete_cnt;
20294 	/*
20295 	 * Memory reclaim call back.
20296 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20297 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20298 	 * entries, determine what fraction to free for
20299 	 * each category of IRE_CACHE entries giving absolute priority
20300 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20301 	 * entry will be freed unless all offlink entries are freed).
20302 	 */
20303 	icc.icc_total = 0;
20304 	icc.icc_unused = 0;
20305 	icc.icc_offlink = 0;
20306 	icc.icc_pmtu = 0;
20307 	icc.icc_onlink = 0;
20308 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20309 
20310 	/*
20311 	 * Free NCEs for IPv6 like the onlink ires.
20312 	 */
20313 	ncc.ncc_total = 0;
20314 	ncc.ncc_host = 0;
20315 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20316 
20317 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20318 	    icc.icc_pmtu + icc.icc_onlink);
20319 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20320 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20321 	if (delete_cnt == 0)
20322 		return;
20323 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20324 	/* Always delete all unused offlink entries */
20325 	icr.icr_ipst = ipst;
20326 	icr.icr_unused = 1;
20327 	if (delete_cnt <= icc.icc_unused) {
20328 		/*
20329 		 * Only need to free unused entries.  In other words,
20330 		 * there are enough unused entries to free to meet our
20331 		 * target number of freed ire cache entries.
20332 		 */
20333 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20334 		ncr.ncr_host = 0;
20335 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20336 		/*
20337 		 * Only need to free unused entries, plus a fraction of offlink
20338 		 * entries.  It follows from the first if statement that
20339 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20340 		 */
20341 		delete_cnt -= icc.icc_unused;
20342 		/* Round up # deleted by truncating fraction */
20343 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20344 		icr.icr_pmtu = icr.icr_onlink = 0;
20345 		ncr.ncr_host = 0;
20346 	} else if (delete_cnt <=
20347 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20348 		/*
20349 		 * Free all unused and offlink entries, plus a fraction of
20350 		 * pmtu entries.  It follows from the previous if statement
20351 		 * that icc_pmtu is non-zero, and that
20352 		 * delete_cnt != icc_unused + icc_offlink.
20353 		 */
20354 		icr.icr_offlink = 1;
20355 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20356 		/* Round up # deleted by truncating fraction */
20357 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20358 		icr.icr_onlink = 0;
20359 		ncr.ncr_host = 0;
20360 	} else {
20361 		/*
20362 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20363 		 * of onlink entries.  If we're here, then we know that
20364 		 * icc_onlink is non-zero, and that
20365 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20366 		 */
20367 		icr.icr_offlink = icr.icr_pmtu = 1;
20368 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20369 		    icc.icc_pmtu;
20370 		/* Round up # deleted by truncating fraction */
20371 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20372 		/* Using the same delete fraction as for onlink IREs */
20373 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20374 	}
20375 #ifdef DEBUG
20376 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20377 	    "fractions %d/%d/%d/%d\n",
20378 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20379 	    icc.icc_unused, icc.icc_offlink,
20380 	    icc.icc_pmtu, icc.icc_onlink,
20381 	    icr.icr_unused, icr.icr_offlink,
20382 	    icr.icr_pmtu, icr.icr_onlink));
20383 #endif
20384 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20385 	if (ncr.ncr_host != 0)
20386 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20387 		    (uchar_t *)&ncr, ipst);
20388 #ifdef DEBUG
20389 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20390 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20391 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20392 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20393 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20394 	    icc.icc_pmtu, icc.icc_onlink));
20395 #endif
20396 }
20397 
20398 /*
20399  * ip_unbind is called when a copy of an unbind request is received from the
20400  * upper level protocol.  We remove this conn from any fanout hash list it is
20401  * on, and zero out the bind information.  No reply is expected up above.
20402  */
20403 void
20404 ip_unbind(conn_t *connp)
20405 {
20406 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20407 
20408 	if (is_system_labeled() && connp->conn_anon_port) {
20409 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20410 		    connp->conn_mlp_type, connp->conn_ulp,
20411 		    ntohs(connp->conn_lport), B_FALSE);
20412 		connp->conn_anon_port = 0;
20413 	}
20414 	connp->conn_mlp_type = mlptSingle;
20415 
20416 	ipcl_hash_remove(connp);
20417 
20418 }
20419 
20420 /*
20421  * Write side put procedure.  Outbound data, IOCTLs, responses from
20422  * resolvers, etc, come down through here.
20423  *
20424  * arg2 is always a queue_t *.
20425  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20426  * the zoneid.
20427  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20428  */
20429 void
20430 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20431 {
20432 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20433 }
20434 
20435 void
20436 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20437     ip_opt_info_t *infop)
20438 {
20439 	conn_t		*connp = NULL;
20440 	queue_t		*q = (queue_t *)arg2;
20441 	ipha_t		*ipha;
20442 #define	rptr	((uchar_t *)ipha)
20443 	ire_t		*ire = NULL;
20444 	ire_t		*sctp_ire = NULL;
20445 	uint32_t	v_hlen_tos_len;
20446 	ipaddr_t	dst;
20447 	mblk_t		*first_mp = NULL;
20448 	boolean_t	mctl_present;
20449 	ipsec_out_t	*io;
20450 	int		match_flags;
20451 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20452 	ipif_t		*dst_ipif;
20453 	boolean_t	multirt_need_resolve = B_FALSE;
20454 	mblk_t		*copy_mp = NULL;
20455 	int		err;
20456 	zoneid_t	zoneid;
20457 	boolean_t	need_decref = B_FALSE;
20458 	boolean_t	ignore_dontroute = B_FALSE;
20459 	boolean_t	ignore_nexthop = B_FALSE;
20460 	boolean_t	ip_nexthop = B_FALSE;
20461 	ipaddr_t	nexthop_addr;
20462 	ip_stack_t	*ipst;
20463 
20464 #ifdef	_BIG_ENDIAN
20465 #define	V_HLEN	(v_hlen_tos_len >> 24)
20466 #else
20467 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20468 #endif
20469 
20470 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20471 	    "ip_wput_start: q %p", q);
20472 
20473 	/*
20474 	 * ip_wput fast path
20475 	 */
20476 
20477 	/* is packet from ARP ? */
20478 	if (q->q_next != NULL) {
20479 		zoneid = (zoneid_t)(uintptr_t)arg;
20480 		goto qnext;
20481 	}
20482 
20483 	connp = (conn_t *)arg;
20484 	ASSERT(connp != NULL);
20485 	zoneid = connp->conn_zoneid;
20486 	ipst = connp->conn_netstack->netstack_ip;
20487 	ASSERT(ipst != NULL);
20488 
20489 	/* is queue flow controlled? */
20490 	if ((q->q_first != NULL || connp->conn_draining) &&
20491 	    (caller == IP_WPUT)) {
20492 		ASSERT(!need_decref);
20493 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20494 		(void) putq(q, mp);
20495 		return;
20496 	}
20497 
20498 	/* Multidata transmit? */
20499 	if (DB_TYPE(mp) == M_MULTIDATA) {
20500 		/*
20501 		 * We should never get here, since all Multidata messages
20502 		 * originating from tcp should have been directed over to
20503 		 * tcp_multisend() in the first place.
20504 		 */
20505 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20506 		freemsg(mp);
20507 		return;
20508 	} else if (DB_TYPE(mp) != M_DATA)
20509 		goto notdata;
20510 
20511 	if (mp->b_flag & MSGHASREF) {
20512 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20513 		mp->b_flag &= ~MSGHASREF;
20514 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20515 		need_decref = B_TRUE;
20516 	}
20517 	ipha = (ipha_t *)mp->b_rptr;
20518 
20519 	/* is IP header non-aligned or mblk smaller than basic IP header */
20520 #ifndef SAFETY_BEFORE_SPEED
20521 	if (!OK_32PTR(rptr) ||
20522 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20523 		goto hdrtoosmall;
20524 #endif
20525 
20526 	ASSERT(OK_32PTR(ipha));
20527 
20528 	/*
20529 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20530 	 * wrong version, we'll catch it again in ip_output_v6.
20531 	 *
20532 	 * Note that this is *only* locally-generated output here, and never
20533 	 * forwarded data, and that we need to deal only with transports that
20534 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20535 	 * label.)
20536 	 */
20537 	if (is_system_labeled() &&
20538 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20539 	    !connp->conn_ulp_labeled) {
20540 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20541 		    connp->conn_mac_exempt, ipst);
20542 		ipha = (ipha_t *)mp->b_rptr;
20543 		if (err != 0) {
20544 			first_mp = mp;
20545 			if (err == EINVAL)
20546 				goto icmp_parameter_problem;
20547 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20548 			goto discard_pkt;
20549 		}
20550 	}
20551 
20552 	ASSERT(infop != NULL);
20553 
20554 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20555 		/*
20556 		 * IP_PKTINFO ancillary option is present.
20557 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20558 		 * allows using address of any zone as the source address.
20559 		 */
20560 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20561 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20562 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20563 		if (ire == NULL)
20564 			goto drop_pkt;
20565 		ire_refrele(ire);
20566 		ire = NULL;
20567 	}
20568 
20569 	/*
20570 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20571 	 */
20572 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20573 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20574 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20575 
20576 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20577 			goto drop_pkt;
20578 		/*
20579 		 * check that there is an ipif belonging
20580 		 * to our zone. IPCL_ZONEID is not used because
20581 		 * IP_ALLZONES option is valid only when the ill is
20582 		 * accessible from all zones i.e has a valid ipif in
20583 		 * all zones.
20584 		 */
20585 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20586 			goto drop_pkt;
20587 		}
20588 	}
20589 
20590 	/*
20591 	 * If there is a policy, try to attach an ipsec_out in
20592 	 * the front. At the end, first_mp either points to a
20593 	 * M_DATA message or IPSEC_OUT message linked to a
20594 	 * M_DATA message. We have to do it now as we might
20595 	 * lose the "conn" if we go through ip_newroute.
20596 	 */
20597 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20598 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20599 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20600 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20601 			if (need_decref)
20602 				CONN_DEC_REF(connp);
20603 			return;
20604 		} else {
20605 			ASSERT(mp->b_datap->db_type == M_CTL);
20606 			first_mp = mp;
20607 			mp = mp->b_cont;
20608 			mctl_present = B_TRUE;
20609 		}
20610 	} else {
20611 		first_mp = mp;
20612 		mctl_present = B_FALSE;
20613 	}
20614 
20615 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20616 
20617 	/* is wrong version or IP options present */
20618 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20619 		goto version_hdrlen_check;
20620 	dst = ipha->ipha_dst;
20621 
20622 	/* If IP_BOUND_IF has been set, use that ill. */
20623 	if (connp->conn_outgoing_ill != NULL) {
20624 		xmit_ill = conn_get_held_ill(connp,
20625 		    &connp->conn_outgoing_ill, &err);
20626 		if (err == ILL_LOOKUP_FAILED)
20627 			goto drop_pkt;
20628 
20629 		goto send_from_ill;
20630 	}
20631 
20632 	/* is packet multicast? */
20633 	if (CLASSD(dst))
20634 		goto multicast;
20635 
20636 	/*
20637 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20638 	 * takes precedence over conn_dontroute and conn_nexthop_set
20639 	 */
20640 	if (xmit_ill != NULL)
20641 		goto send_from_ill;
20642 
20643 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20644 		/*
20645 		 * If the destination is a broadcast, local, or loopback
20646 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20647 		 * standard path.
20648 		 */
20649 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20650 		if ((ire == NULL) || (ire->ire_type &
20651 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20652 			if (ire != NULL) {
20653 				ire_refrele(ire);
20654 				/* No more access to ire */
20655 				ire = NULL;
20656 			}
20657 			/*
20658 			 * bypass routing checks and go directly to interface.
20659 			 */
20660 			if (connp->conn_dontroute)
20661 				goto dontroute;
20662 
20663 			ASSERT(connp->conn_nexthop_set);
20664 			ip_nexthop = B_TRUE;
20665 			nexthop_addr = connp->conn_nexthop_v4;
20666 			goto send_from_ill;
20667 		}
20668 
20669 		/* Must be a broadcast, a loopback or a local ire */
20670 		ire_refrele(ire);
20671 		/* No more access to ire */
20672 		ire = NULL;
20673 	}
20674 
20675 	/*
20676 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20677 	 * this for the tcp global queue and listen end point
20678 	 * as it does not really have a real destination to
20679 	 * talk to.  This is also true for SCTP.
20680 	 */
20681 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20682 	    !connp->conn_fully_bound) {
20683 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20684 		if (ire == NULL)
20685 			goto noirefound;
20686 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20687 		    "ip_wput_end: q %p (%S)", q, "end");
20688 
20689 		/*
20690 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20691 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20692 		 */
20693 		if (ire->ire_flags & RTF_MULTIRT) {
20694 
20695 			/*
20696 			 * Force the TTL of multirouted packets if required.
20697 			 * The TTL of such packets is bounded by the
20698 			 * ip_multirt_ttl ndd variable.
20699 			 */
20700 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20701 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20702 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20703 				    "(was %d), dst 0x%08x\n",
20704 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20705 				    ntohl(ire->ire_addr)));
20706 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20707 			}
20708 			/*
20709 			 * We look at this point if there are pending
20710 			 * unresolved routes. ire_multirt_resolvable()
20711 			 * checks in O(n) that all IRE_OFFSUBNET ire
20712 			 * entries for the packet's destination and
20713 			 * flagged RTF_MULTIRT are currently resolved.
20714 			 * If some remain unresolved, we make a copy
20715 			 * of the current message. It will be used
20716 			 * to initiate additional route resolutions.
20717 			 */
20718 			multirt_need_resolve =
20719 			    ire_multirt_need_resolve(ire->ire_addr,
20720 			    msg_getlabel(first_mp), ipst);
20721 			ip2dbg(("ip_wput[TCP]: ire %p, "
20722 			    "multirt_need_resolve %d, first_mp %p\n",
20723 			    (void *)ire, multirt_need_resolve,
20724 			    (void *)first_mp));
20725 			if (multirt_need_resolve) {
20726 				copy_mp = copymsg(first_mp);
20727 				if (copy_mp != NULL) {
20728 					MULTIRT_DEBUG_TAG(copy_mp);
20729 				}
20730 			}
20731 		}
20732 
20733 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20734 
20735 		/*
20736 		 * Try to resolve another multiroute if
20737 		 * ire_multirt_need_resolve() deemed it necessary.
20738 		 */
20739 		if (copy_mp != NULL)
20740 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20741 		if (need_decref)
20742 			CONN_DEC_REF(connp);
20743 		return;
20744 	}
20745 
20746 	/*
20747 	 * Access to conn_ire_cache. (protected by conn_lock)
20748 	 *
20749 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20750 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20751 	 * send a packet or two with the IRE_CACHE that is going away.
20752 	 * Access to the ire requires an ire refhold on the ire prior to
20753 	 * its use since an interface unplumb thread may delete the cached
20754 	 * ire and release the refhold at any time.
20755 	 *
20756 	 * Caching an ire in the conn_ire_cache
20757 	 *
20758 	 * o Caching an ire pointer in the conn requires a strict check for
20759 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20760 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20761 	 * in the conn is done after making sure under the bucket lock that the
20762 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20763 	 * caching an ire after the unplumb thread has cleaned up the conn.
20764 	 * If the conn does not send a packet subsequently the unplumb thread
20765 	 * will be hanging waiting for the ire count to drop to zero.
20766 	 *
20767 	 * o We also need to atomically test for a null conn_ire_cache and
20768 	 * set the conn_ire_cache under the the protection of the conn_lock
20769 	 * to avoid races among concurrent threads trying to simultaneously
20770 	 * cache an ire in the conn_ire_cache.
20771 	 */
20772 	mutex_enter(&connp->conn_lock);
20773 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20774 
20775 	if (ire != NULL && ire->ire_addr == dst &&
20776 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20777 
20778 		IRE_REFHOLD(ire);
20779 		mutex_exit(&connp->conn_lock);
20780 
20781 	} else {
20782 		boolean_t cached = B_FALSE;
20783 		connp->conn_ire_cache = NULL;
20784 		mutex_exit(&connp->conn_lock);
20785 		/* Release the old ire */
20786 		if (ire != NULL && sctp_ire == NULL)
20787 			IRE_REFRELE_NOTR(ire);
20788 
20789 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20790 		if (ire == NULL)
20791 			goto noirefound;
20792 		IRE_REFHOLD_NOTR(ire);
20793 
20794 		mutex_enter(&connp->conn_lock);
20795 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20796 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20797 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20798 				if (connp->conn_ulp == IPPROTO_TCP)
20799 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20800 				connp->conn_ire_cache = ire;
20801 				cached = B_TRUE;
20802 			}
20803 			rw_exit(&ire->ire_bucket->irb_lock);
20804 		}
20805 		mutex_exit(&connp->conn_lock);
20806 
20807 		/*
20808 		 * We can continue to use the ire but since it was
20809 		 * not cached, we should drop the extra reference.
20810 		 */
20811 		if (!cached)
20812 			IRE_REFRELE_NOTR(ire);
20813 	}
20814 
20815 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20816 	    "ip_wput_end: q %p (%S)", q, "end");
20817 
20818 	/*
20819 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20820 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20821 	 */
20822 	if (ire->ire_flags & RTF_MULTIRT) {
20823 		/*
20824 		 * Force the TTL of multirouted packets if required.
20825 		 * The TTL of such packets is bounded by the
20826 		 * ip_multirt_ttl ndd variable.
20827 		 */
20828 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20829 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20830 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20831 			    "(was %d), dst 0x%08x\n",
20832 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20833 			    ntohl(ire->ire_addr)));
20834 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20835 		}
20836 
20837 		/*
20838 		 * At this point, we check to see if there are any pending
20839 		 * unresolved routes. ire_multirt_resolvable()
20840 		 * checks in O(n) that all IRE_OFFSUBNET ire
20841 		 * entries for the packet's destination and
20842 		 * flagged RTF_MULTIRT are currently resolved.
20843 		 * If some remain unresolved, we make a copy
20844 		 * of the current message. It will be used
20845 		 * to initiate additional route resolutions.
20846 		 */
20847 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20848 		    msg_getlabel(first_mp), ipst);
20849 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20850 		    "multirt_need_resolve %d, first_mp %p\n",
20851 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20852 		if (multirt_need_resolve) {
20853 			copy_mp = copymsg(first_mp);
20854 			if (copy_mp != NULL) {
20855 				MULTIRT_DEBUG_TAG(copy_mp);
20856 			}
20857 		}
20858 	}
20859 
20860 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20861 
20862 	/*
20863 	 * Try to resolve another multiroute if
20864 	 * ire_multirt_resolvable() deemed it necessary
20865 	 */
20866 	if (copy_mp != NULL)
20867 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20868 	if (need_decref)
20869 		CONN_DEC_REF(connp);
20870 	return;
20871 
20872 qnext:
20873 	/*
20874 	 * Upper Level Protocols pass down complete IP datagrams
20875 	 * as M_DATA messages.	Everything else is a sideshow.
20876 	 *
20877 	 * 1) We could be re-entering ip_wput because of ip_neworute
20878 	 *    in which case we could have a IPSEC_OUT message. We
20879 	 *    need to pass through ip_wput like other datagrams and
20880 	 *    hence cannot branch to ip_wput_nondata.
20881 	 *
20882 	 * 2) ARP, AH, ESP, and other clients who are on the module
20883 	 *    instance of IP stream, give us something to deal with.
20884 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20885 	 *
20886 	 * 3) ICMP replies also could come here.
20887 	 */
20888 	ipst = ILLQ_TO_IPST(q);
20889 
20890 	if (DB_TYPE(mp) != M_DATA) {
20891 notdata:
20892 		if (DB_TYPE(mp) == M_CTL) {
20893 			/*
20894 			 * M_CTL messages are used by ARP, AH and ESP to
20895 			 * communicate with IP. We deal with IPSEC_IN and
20896 			 * IPSEC_OUT here. ip_wput_nondata handles other
20897 			 * cases.
20898 			 */
20899 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20900 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20901 				first_mp = mp->b_cont;
20902 				first_mp->b_flag &= ~MSGHASREF;
20903 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20904 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20905 				CONN_DEC_REF(connp);
20906 				connp = NULL;
20907 			}
20908 			if (ii->ipsec_info_type == IPSEC_IN) {
20909 				/*
20910 				 * Either this message goes back to
20911 				 * IPsec for further processing or to
20912 				 * ULP after policy checks.
20913 				 */
20914 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20915 				return;
20916 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20917 				io = (ipsec_out_t *)ii;
20918 				if (io->ipsec_out_proc_begin) {
20919 					/*
20920 					 * IPsec processing has already started.
20921 					 * Complete it.
20922 					 * IPQoS notes: We don't care what is
20923 					 * in ipsec_out_ill_index since this
20924 					 * won't be processed for IPQoS policies
20925 					 * in ipsec_out_process.
20926 					 */
20927 					ipsec_out_process(q, mp, NULL,
20928 					    io->ipsec_out_ill_index);
20929 					return;
20930 				} else {
20931 					connp = (q->q_next != NULL) ?
20932 					    NULL : Q_TO_CONN(q);
20933 					first_mp = mp;
20934 					mp = mp->b_cont;
20935 					mctl_present = B_TRUE;
20936 				}
20937 				zoneid = io->ipsec_out_zoneid;
20938 				ASSERT(zoneid != ALL_ZONES);
20939 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20940 				/*
20941 				 * It's an IPsec control message requesting
20942 				 * an SADB update to be sent to the IPsec
20943 				 * hardware acceleration capable ills.
20944 				 */
20945 				ipsec_ctl_t *ipsec_ctl =
20946 				    (ipsec_ctl_t *)mp->b_rptr;
20947 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20948 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20949 				mblk_t *cmp = mp->b_cont;
20950 
20951 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20952 				ASSERT(cmp != NULL);
20953 
20954 				freeb(mp);
20955 				ill_ipsec_capab_send_all(satype, cmp, sa,
20956 				    ipst->ips_netstack);
20957 				return;
20958 			} else {
20959 				/*
20960 				 * This must be ARP or special TSOL signaling.
20961 				 */
20962 				ip_wput_nondata(NULL, q, mp, NULL);
20963 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20964 				    "ip_wput_end: q %p (%S)", q, "nondata");
20965 				return;
20966 			}
20967 		} else {
20968 			/*
20969 			 * This must be non-(ARP/AH/ESP) messages.
20970 			 */
20971 			ASSERT(!need_decref);
20972 			ip_wput_nondata(NULL, q, mp, NULL);
20973 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20974 			    "ip_wput_end: q %p (%S)", q, "nondata");
20975 			return;
20976 		}
20977 	} else {
20978 		first_mp = mp;
20979 		mctl_present = B_FALSE;
20980 	}
20981 
20982 	ASSERT(first_mp != NULL);
20983 
20984 	if (mctl_present) {
20985 		io = (ipsec_out_t *)first_mp->b_rptr;
20986 		if (io->ipsec_out_ip_nexthop) {
20987 			/*
20988 			 * We may have lost the conn context if we are
20989 			 * coming here from ip_newroute(). Copy the
20990 			 * nexthop information.
20991 			 */
20992 			ip_nexthop = B_TRUE;
20993 			nexthop_addr = io->ipsec_out_nexthop_addr;
20994 
20995 			ipha = (ipha_t *)mp->b_rptr;
20996 			dst = ipha->ipha_dst;
20997 			goto send_from_ill;
20998 		}
20999 	}
21000 
21001 	ASSERT(xmit_ill == NULL);
21002 
21003 	/* We have a complete IP datagram heading outbound. */
21004 	ipha = (ipha_t *)mp->b_rptr;
21005 
21006 #ifndef SPEED_BEFORE_SAFETY
21007 	/*
21008 	 * Make sure we have a full-word aligned message and that at least
21009 	 * a simple IP header is accessible in the first message.  If not,
21010 	 * try a pullup.  For labeled systems we need to always take this
21011 	 * path as M_CTLs are "notdata" but have trailing data to process.
21012 	 */
21013 	if (!OK_32PTR(rptr) ||
21014 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21015 hdrtoosmall:
21016 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21017 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21018 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21019 			if (first_mp == NULL)
21020 				first_mp = mp;
21021 			goto discard_pkt;
21022 		}
21023 
21024 		/* This function assumes that mp points to an IPv4 packet. */
21025 		if (is_system_labeled() && q->q_next == NULL &&
21026 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21027 		    !connp->conn_ulp_labeled) {
21028 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
21029 			    connp->conn_mac_exempt, ipst);
21030 			ipha = (ipha_t *)mp->b_rptr;
21031 			if (first_mp != NULL)
21032 				first_mp->b_cont = mp;
21033 			if (err != 0) {
21034 				if (first_mp == NULL)
21035 					first_mp = mp;
21036 				if (err == EINVAL)
21037 					goto icmp_parameter_problem;
21038 				ip2dbg(("ip_wput: label check failed (%d)\n",
21039 				    err));
21040 				goto discard_pkt;
21041 			}
21042 		}
21043 
21044 		ipha = (ipha_t *)mp->b_rptr;
21045 		if (first_mp == NULL) {
21046 			ASSERT(xmit_ill == NULL);
21047 			/*
21048 			 * If we got here because of "goto hdrtoosmall"
21049 			 * We need to attach a IPSEC_OUT.
21050 			 */
21051 			if (connp->conn_out_enforce_policy) {
21052 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21053 				    NULL, ipha->ipha_protocol,
21054 				    ipst->ips_netstack)) == NULL)) {
21055 					BUMP_MIB(&ipst->ips_ip_mib,
21056 					    ipIfStatsOutDiscards);
21057 					if (need_decref)
21058 						CONN_DEC_REF(connp);
21059 					return;
21060 				} else {
21061 					ASSERT(mp->b_datap->db_type == M_CTL);
21062 					first_mp = mp;
21063 					mp = mp->b_cont;
21064 					mctl_present = B_TRUE;
21065 				}
21066 			} else {
21067 				first_mp = mp;
21068 				mctl_present = B_FALSE;
21069 			}
21070 		}
21071 	}
21072 #endif
21073 
21074 	/* Most of the code below is written for speed, not readability */
21075 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21076 
21077 	/*
21078 	 * If ip_newroute() fails, we're going to need a full
21079 	 * header for the icmp wraparound.
21080 	 */
21081 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21082 		uint_t	v_hlen;
21083 version_hdrlen_check:
21084 		ASSERT(first_mp != NULL);
21085 		v_hlen = V_HLEN;
21086 		/*
21087 		 * siphon off IPv6 packets coming down from transport
21088 		 * layer modules here.
21089 		 * Note: high-order bit carries NUD reachability confirmation
21090 		 */
21091 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21092 			/*
21093 			 * FIXME: assume that callers of ip_output* call
21094 			 * the right version?
21095 			 */
21096 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21097 			ASSERT(xmit_ill == NULL);
21098 			if (need_decref)
21099 				mp->b_flag |= MSGHASREF;
21100 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21101 			return;
21102 		}
21103 
21104 		if ((v_hlen >> 4) != IP_VERSION) {
21105 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21106 			    "ip_wput_end: q %p (%S)", q, "badvers");
21107 			goto discard_pkt;
21108 		}
21109 		/*
21110 		 * Is the header length at least 20 bytes?
21111 		 *
21112 		 * Are there enough bytes accessible in the header?  If
21113 		 * not, try a pullup.
21114 		 */
21115 		v_hlen &= 0xF;
21116 		v_hlen <<= 2;
21117 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21118 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21119 			    "ip_wput_end: q %p (%S)", q, "badlen");
21120 			goto discard_pkt;
21121 		}
21122 		if (v_hlen > (mp->b_wptr - rptr)) {
21123 			if (!pullupmsg(mp, v_hlen)) {
21124 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21125 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21126 				goto discard_pkt;
21127 			}
21128 			ipha = (ipha_t *)mp->b_rptr;
21129 		}
21130 		/*
21131 		 * Move first entry from any source route into ipha_dst and
21132 		 * verify the options
21133 		 */
21134 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21135 		    zoneid, ipst)) {
21136 			ASSERT(xmit_ill == NULL);
21137 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21138 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21139 			    "ip_wput_end: q %p (%S)", q, "badopts");
21140 			if (need_decref)
21141 				CONN_DEC_REF(connp);
21142 			return;
21143 		}
21144 	}
21145 	dst = ipha->ipha_dst;
21146 
21147 	/*
21148 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21149 	 * we have to run the packet through ip_newroute which will take
21150 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21151 	 * a resolver, or assigning a default gateway, etc.
21152 	 */
21153 	if (CLASSD(dst)) {
21154 		ipif_t	*ipif;
21155 		uint32_t setsrc = 0;
21156 
21157 multicast:
21158 		ASSERT(first_mp != NULL);
21159 		ip2dbg(("ip_wput: CLASSD\n"));
21160 		if (connp == NULL) {
21161 			/*
21162 			 * Use the first good ipif on the ill.
21163 			 * XXX Should this ever happen? (Appears
21164 			 * to show up with just ppp and no ethernet due
21165 			 * to in.rdisc.)
21166 			 * However, ire_send should be able to
21167 			 * call ip_wput_ire directly.
21168 			 *
21169 			 * XXX Also, this can happen for ICMP and other packets
21170 			 * with multicast source addresses.  Perhaps we should
21171 			 * fix things so that we drop the packet in question,
21172 			 * but for now, just run with it.
21173 			 */
21174 			ill_t *ill = (ill_t *)q->q_ptr;
21175 
21176 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21177 			if (ipif == NULL) {
21178 				if (need_decref)
21179 					CONN_DEC_REF(connp);
21180 				freemsg(first_mp);
21181 				return;
21182 			}
21183 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21184 			    ntohl(dst), ill->ill_name));
21185 		} else {
21186 			/*
21187 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21188 			 * and IP_MULTICAST_IF.  The block comment above this
21189 			 * function explains the locking mechanism used here.
21190 			 */
21191 			if (xmit_ill == NULL) {
21192 				xmit_ill = conn_get_held_ill(connp,
21193 				    &connp->conn_outgoing_ill, &err);
21194 				if (err == ILL_LOOKUP_FAILED) {
21195 					ip1dbg(("ip_wput: No ill for "
21196 					    "IP_BOUND_IF\n"));
21197 					BUMP_MIB(&ipst->ips_ip_mib,
21198 					    ipIfStatsOutNoRoutes);
21199 					goto drop_pkt;
21200 				}
21201 			}
21202 
21203 			if (xmit_ill == NULL) {
21204 				ipif = conn_get_held_ipif(connp,
21205 				    &connp->conn_multicast_ipif, &err);
21206 				if (err == IPIF_LOOKUP_FAILED) {
21207 					ip1dbg(("ip_wput: No ipif for "
21208 					    "multicast\n"));
21209 					BUMP_MIB(&ipst->ips_ip_mib,
21210 					    ipIfStatsOutNoRoutes);
21211 					goto drop_pkt;
21212 				}
21213 			}
21214 			if (xmit_ill != NULL) {
21215 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21216 				if (ipif == NULL) {
21217 					ip1dbg(("ip_wput: No ipif for "
21218 					    "xmit_ill\n"));
21219 					BUMP_MIB(&ipst->ips_ip_mib,
21220 					    ipIfStatsOutNoRoutes);
21221 					goto drop_pkt;
21222 				}
21223 			} else if (ipif == NULL || ipif->ipif_isv6) {
21224 				/*
21225 				 * We must do this ipif determination here
21226 				 * else we could pass through ip_newroute
21227 				 * and come back here without the conn context.
21228 				 *
21229 				 * Note: we do late binding i.e. we bind to
21230 				 * the interface when the first packet is sent.
21231 				 * For performance reasons we do not rebind on
21232 				 * each packet but keep the binding until the
21233 				 * next IP_MULTICAST_IF option.
21234 				 *
21235 				 * conn_multicast_{ipif,ill} are shared between
21236 				 * IPv4 and IPv6 and AF_INET6 sockets can
21237 				 * send both IPv4 and IPv6 packets. Hence
21238 				 * we have to check that "isv6" matches above.
21239 				 */
21240 				if (ipif != NULL)
21241 					ipif_refrele(ipif);
21242 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21243 				if (ipif == NULL) {
21244 					ip1dbg(("ip_wput: No ipif for "
21245 					    "multicast\n"));
21246 					BUMP_MIB(&ipst->ips_ip_mib,
21247 					    ipIfStatsOutNoRoutes);
21248 					goto drop_pkt;
21249 				}
21250 				err = conn_set_held_ipif(connp,
21251 				    &connp->conn_multicast_ipif, ipif);
21252 				if (err == IPIF_LOOKUP_FAILED) {
21253 					ipif_refrele(ipif);
21254 					ip1dbg(("ip_wput: No ipif for "
21255 					    "multicast\n"));
21256 					BUMP_MIB(&ipst->ips_ip_mib,
21257 					    ipIfStatsOutNoRoutes);
21258 					goto drop_pkt;
21259 				}
21260 			}
21261 		}
21262 		ASSERT(!ipif->ipif_isv6);
21263 		/*
21264 		 * As we may lose the conn by the time we reach ip_wput_ire,
21265 		 * we copy conn_multicast_loop and conn_dontroute on to an
21266 		 * ipsec_out. In case if this datagram goes out secure,
21267 		 * we need the ill_index also. Copy that also into the
21268 		 * ipsec_out.
21269 		 */
21270 		if (mctl_present) {
21271 			io = (ipsec_out_t *)first_mp->b_rptr;
21272 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21273 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21274 		} else {
21275 			ASSERT(mp == first_mp);
21276 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21277 			    BPRI_HI)) == NULL) {
21278 				ipif_refrele(ipif);
21279 				first_mp = mp;
21280 				goto discard_pkt;
21281 			}
21282 			first_mp->b_datap->db_type = M_CTL;
21283 			first_mp->b_wptr += sizeof (ipsec_info_t);
21284 			/* ipsec_out_secure is B_FALSE now */
21285 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21286 			io = (ipsec_out_t *)first_mp->b_rptr;
21287 			io->ipsec_out_type = IPSEC_OUT;
21288 			io->ipsec_out_len = sizeof (ipsec_out_t);
21289 			io->ipsec_out_use_global_policy = B_TRUE;
21290 			io->ipsec_out_ns = ipst->ips_netstack;
21291 			first_mp->b_cont = mp;
21292 			mctl_present = B_TRUE;
21293 		}
21294 
21295 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21296 		io->ipsec_out_ill_index =
21297 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21298 
21299 		if (connp != NULL) {
21300 			io->ipsec_out_multicast_loop =
21301 			    connp->conn_multicast_loop;
21302 			io->ipsec_out_dontroute = connp->conn_dontroute;
21303 			io->ipsec_out_zoneid = connp->conn_zoneid;
21304 		}
21305 		/*
21306 		 * If the application uses IP_MULTICAST_IF with
21307 		 * different logical addresses of the same ILL, we
21308 		 * need to make sure that the soruce address of
21309 		 * the packet matches the logical IP address used
21310 		 * in the option. We do it by initializing ipha_src
21311 		 * here. This should keep IPsec also happy as
21312 		 * when we return from IPsec processing, we don't
21313 		 * have to worry about getting the right address on
21314 		 * the packet. Thus it is sufficient to look for
21315 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21316 		 * MATCH_IRE_IPIF.
21317 		 *
21318 		 * NOTE : We need to do it for non-secure case also as
21319 		 * this might go out secure if there is a global policy
21320 		 * match in ip_wput_ire.
21321 		 *
21322 		 * As we do not have the ire yet, it is possible that
21323 		 * we set the source address here and then later discover
21324 		 * that the ire implies the source address to be assigned
21325 		 * through the RTF_SETSRC flag.
21326 		 * In that case, the setsrc variable will remind us
21327 		 * that overwritting the source address by the one
21328 		 * of the RTF_SETSRC-flagged ire is allowed.
21329 		 */
21330 		if (ipha->ipha_src == INADDR_ANY &&
21331 		    (connp == NULL || !connp->conn_unspec_src)) {
21332 			ipha->ipha_src = ipif->ipif_src_addr;
21333 			setsrc = RTF_SETSRC;
21334 		}
21335 		/*
21336 		 * Find an IRE which matches the destination and the outgoing
21337 		 * queue (i.e. the outgoing interface.)
21338 		 * For loopback use a unicast IP address for
21339 		 * the ire lookup.
21340 		 */
21341 		if (IS_LOOPBACK(ipif->ipif_ill))
21342 			dst = ipif->ipif_lcl_addr;
21343 
21344 		/*
21345 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21346 		 * We don't need to lookup ire in ctable as the packet
21347 		 * needs to be sent to the destination through the specified
21348 		 * ill irrespective of ires in the cache table.
21349 		 */
21350 		ire = NULL;
21351 		if (xmit_ill == NULL) {
21352 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21353 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21354 		}
21355 
21356 		if (ire == NULL) {
21357 			/*
21358 			 * Multicast loopback and multicast forwarding is
21359 			 * done in ip_wput_ire.
21360 			 *
21361 			 * Mark this packet to make it be delivered to
21362 			 * ip_wput_ire after the new ire has been
21363 			 * created.
21364 			 *
21365 			 * The call to ip_newroute_ipif takes into account
21366 			 * the setsrc reminder. In any case, we take care
21367 			 * of the RTF_MULTIRT flag.
21368 			 */
21369 			mp->b_prev = mp->b_next = NULL;
21370 			if (xmit_ill == NULL ||
21371 			    xmit_ill->ill_ipif_up_count > 0) {
21372 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21373 				    setsrc | RTF_MULTIRT, zoneid, infop);
21374 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21375 				    "ip_wput_end: q %p (%S)", q, "noire");
21376 			} else {
21377 				freemsg(first_mp);
21378 			}
21379 			ipif_refrele(ipif);
21380 			if (xmit_ill != NULL)
21381 				ill_refrele(xmit_ill);
21382 			if (need_decref)
21383 				CONN_DEC_REF(connp);
21384 			return;
21385 		}
21386 
21387 		ipif_refrele(ipif);
21388 		ipif = NULL;
21389 		ASSERT(xmit_ill == NULL);
21390 
21391 		/*
21392 		 * Honor the RTF_SETSRC flag for multicast packets,
21393 		 * if allowed by the setsrc reminder.
21394 		 */
21395 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21396 			ipha->ipha_src = ire->ire_src_addr;
21397 		}
21398 
21399 		/*
21400 		 * Unconditionally force the TTL to 1 for
21401 		 * multirouted multicast packets:
21402 		 * multirouted multicast should not cross
21403 		 * multicast routers.
21404 		 */
21405 		if (ire->ire_flags & RTF_MULTIRT) {
21406 			if (ipha->ipha_ttl > 1) {
21407 				ip2dbg(("ip_wput: forcing multicast "
21408 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21409 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21410 				ipha->ipha_ttl = 1;
21411 			}
21412 		}
21413 	} else {
21414 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21415 		if ((ire != NULL) && (ire->ire_type &
21416 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21417 			ignore_dontroute = B_TRUE;
21418 			ignore_nexthop = B_TRUE;
21419 		}
21420 		if (ire != NULL) {
21421 			ire_refrele(ire);
21422 			ire = NULL;
21423 		}
21424 		/*
21425 		 * Guard against coming in from arp in which case conn is NULL.
21426 		 * Also guard against non M_DATA with dontroute set but
21427 		 * destined to local, loopback or broadcast addresses.
21428 		 */
21429 		if (connp != NULL && connp->conn_dontroute &&
21430 		    !ignore_dontroute) {
21431 dontroute:
21432 			/*
21433 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21434 			 * routing protocols from seeing false direct
21435 			 * connectivity.
21436 			 */
21437 			ipha->ipha_ttl = 1;
21438 			/* If suitable ipif not found, drop packet */
21439 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21440 			if (dst_ipif == NULL) {
21441 noroute:
21442 				ip1dbg(("ip_wput: no route for dst using"
21443 				    " SO_DONTROUTE\n"));
21444 				BUMP_MIB(&ipst->ips_ip_mib,
21445 				    ipIfStatsOutNoRoutes);
21446 				mp->b_prev = mp->b_next = NULL;
21447 				if (first_mp == NULL)
21448 					first_mp = mp;
21449 				goto drop_pkt;
21450 			} else {
21451 				/*
21452 				 * If suitable ipif has been found, set
21453 				 * xmit_ill to the corresponding
21454 				 * ipif_ill because we'll be using the
21455 				 * send_from_ill logic below.
21456 				 */
21457 				ASSERT(xmit_ill == NULL);
21458 				xmit_ill = dst_ipif->ipif_ill;
21459 				mutex_enter(&xmit_ill->ill_lock);
21460 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21461 					mutex_exit(&xmit_ill->ill_lock);
21462 					xmit_ill = NULL;
21463 					ipif_refrele(dst_ipif);
21464 					goto noroute;
21465 				}
21466 				ill_refhold_locked(xmit_ill);
21467 				mutex_exit(&xmit_ill->ill_lock);
21468 				ipif_refrele(dst_ipif);
21469 			}
21470 		}
21471 
21472 send_from_ill:
21473 		if (xmit_ill != NULL) {
21474 			ipif_t *ipif;
21475 
21476 			/*
21477 			 * Mark this packet as originated locally
21478 			 */
21479 			mp->b_prev = mp->b_next = NULL;
21480 
21481 			/*
21482 			 * Could be SO_DONTROUTE case also.
21483 			 * Verify that at least one ipif is up on the ill.
21484 			 */
21485 			if (xmit_ill->ill_ipif_up_count == 0) {
21486 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21487 				    xmit_ill->ill_name));
21488 				goto drop_pkt;
21489 			}
21490 
21491 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21492 			if (ipif == NULL) {
21493 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21494 				    xmit_ill->ill_name));
21495 				goto drop_pkt;
21496 			}
21497 
21498 			match_flags = 0;
21499 			if (IS_UNDER_IPMP(xmit_ill))
21500 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21501 
21502 			/*
21503 			 * Look for a ire that is part of the group,
21504 			 * if found use it else call ip_newroute_ipif.
21505 			 * IPCL_ZONEID is not used for matching because
21506 			 * IP_ALLZONES option is valid only when the
21507 			 * ill is accessible from all zones i.e has a
21508 			 * valid ipif in all zones.
21509 			 */
21510 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21511 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21512 			    msg_getlabel(mp), match_flags, ipst);
21513 			/*
21514 			 * If an ire exists use it or else create
21515 			 * an ire but don't add it to the cache.
21516 			 * Adding an ire may cause issues with
21517 			 * asymmetric routing.
21518 			 * In case of multiroute always act as if
21519 			 * ire does not exist.
21520 			 */
21521 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21522 				if (ire != NULL)
21523 					ire_refrele(ire);
21524 				ip_newroute_ipif(q, first_mp, ipif,
21525 				    dst, connp, 0, zoneid, infop);
21526 				ipif_refrele(ipif);
21527 				ip1dbg(("ip_output: xmit_ill via %s\n",
21528 				    xmit_ill->ill_name));
21529 				ill_refrele(xmit_ill);
21530 				if (need_decref)
21531 					CONN_DEC_REF(connp);
21532 				return;
21533 			}
21534 			ipif_refrele(ipif);
21535 		} else if (ip_nexthop || (connp != NULL &&
21536 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21537 			if (!ip_nexthop) {
21538 				ip_nexthop = B_TRUE;
21539 				nexthop_addr = connp->conn_nexthop_v4;
21540 			}
21541 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21542 			    MATCH_IRE_GW;
21543 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21544 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21545 		} else {
21546 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21547 			    ipst);
21548 		}
21549 		if (!ire) {
21550 			if (ip_nexthop && !ignore_nexthop) {
21551 				if (mctl_present) {
21552 					io = (ipsec_out_t *)first_mp->b_rptr;
21553 					ASSERT(first_mp->b_datap->db_type ==
21554 					    M_CTL);
21555 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21556 				} else {
21557 					ASSERT(mp == first_mp);
21558 					first_mp = allocb(
21559 					    sizeof (ipsec_info_t), BPRI_HI);
21560 					if (first_mp == NULL) {
21561 						first_mp = mp;
21562 						goto discard_pkt;
21563 					}
21564 					first_mp->b_datap->db_type = M_CTL;
21565 					first_mp->b_wptr +=
21566 					    sizeof (ipsec_info_t);
21567 					/* ipsec_out_secure is B_FALSE now */
21568 					bzero(first_mp->b_rptr,
21569 					    sizeof (ipsec_info_t));
21570 					io = (ipsec_out_t *)first_mp->b_rptr;
21571 					io->ipsec_out_type = IPSEC_OUT;
21572 					io->ipsec_out_len =
21573 					    sizeof (ipsec_out_t);
21574 					io->ipsec_out_use_global_policy =
21575 					    B_TRUE;
21576 					io->ipsec_out_ns = ipst->ips_netstack;
21577 					first_mp->b_cont = mp;
21578 					mctl_present = B_TRUE;
21579 				}
21580 				io->ipsec_out_ip_nexthop = ip_nexthop;
21581 				io->ipsec_out_nexthop_addr = nexthop_addr;
21582 			}
21583 noirefound:
21584 			/*
21585 			 * Mark this packet as having originated on
21586 			 * this machine.  This will be noted in
21587 			 * ire_add_then_send, which needs to know
21588 			 * whether to run it back through ip_wput or
21589 			 * ip_rput following successful resolution.
21590 			 */
21591 			mp->b_prev = NULL;
21592 			mp->b_next = NULL;
21593 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21594 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21595 			    "ip_wput_end: q %p (%S)", q, "newroute");
21596 			if (xmit_ill != NULL)
21597 				ill_refrele(xmit_ill);
21598 			if (need_decref)
21599 				CONN_DEC_REF(connp);
21600 			return;
21601 		}
21602 	}
21603 
21604 	/* We now know where we are going with it. */
21605 
21606 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21607 	    "ip_wput_end: q %p (%S)", q, "end");
21608 
21609 	/*
21610 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21611 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21612 	 */
21613 	if (ire->ire_flags & RTF_MULTIRT) {
21614 		/*
21615 		 * Force the TTL of multirouted packets if required.
21616 		 * The TTL of such packets is bounded by the
21617 		 * ip_multirt_ttl ndd variable.
21618 		 */
21619 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21620 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21621 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21622 			    "(was %d), dst 0x%08x\n",
21623 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21624 			    ntohl(ire->ire_addr)));
21625 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21626 		}
21627 		/*
21628 		 * At this point, we check to see if there are any pending
21629 		 * unresolved routes. ire_multirt_resolvable()
21630 		 * checks in O(n) that all IRE_OFFSUBNET ire
21631 		 * entries for the packet's destination and
21632 		 * flagged RTF_MULTIRT are currently resolved.
21633 		 * If some remain unresolved, we make a copy
21634 		 * of the current message. It will be used
21635 		 * to initiate additional route resolutions.
21636 		 */
21637 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21638 		    msg_getlabel(first_mp), ipst);
21639 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21640 		    "multirt_need_resolve %d, first_mp %p\n",
21641 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21642 		if (multirt_need_resolve) {
21643 			copy_mp = copymsg(first_mp);
21644 			if (copy_mp != NULL) {
21645 				MULTIRT_DEBUG_TAG(copy_mp);
21646 			}
21647 		}
21648 	}
21649 
21650 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21651 	/*
21652 	 * Try to resolve another multiroute if
21653 	 * ire_multirt_resolvable() deemed it necessary.
21654 	 * At this point, we need to distinguish
21655 	 * multicasts from other packets. For multicasts,
21656 	 * we call ip_newroute_ipif() and request that both
21657 	 * multirouting and setsrc flags are checked.
21658 	 */
21659 	if (copy_mp != NULL) {
21660 		if (CLASSD(dst)) {
21661 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21662 			if (ipif) {
21663 				ASSERT(infop->ip_opt_ill_index == 0);
21664 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21665 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21666 				ipif_refrele(ipif);
21667 			} else {
21668 				MULTIRT_DEBUG_UNTAG(copy_mp);
21669 				freemsg(copy_mp);
21670 				copy_mp = NULL;
21671 			}
21672 		} else {
21673 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21674 		}
21675 	}
21676 	if (xmit_ill != NULL)
21677 		ill_refrele(xmit_ill);
21678 	if (need_decref)
21679 		CONN_DEC_REF(connp);
21680 	return;
21681 
21682 icmp_parameter_problem:
21683 	/* could not have originated externally */
21684 	ASSERT(mp->b_prev == NULL);
21685 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21686 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21687 		/* it's the IP header length that's in trouble */
21688 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21689 		first_mp = NULL;
21690 	}
21691 
21692 discard_pkt:
21693 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21694 drop_pkt:
21695 	ip1dbg(("ip_wput: dropped packet\n"));
21696 	if (ire != NULL)
21697 		ire_refrele(ire);
21698 	if (need_decref)
21699 		CONN_DEC_REF(connp);
21700 	freemsg(first_mp);
21701 	if (xmit_ill != NULL)
21702 		ill_refrele(xmit_ill);
21703 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21704 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21705 }
21706 
21707 /*
21708  * If this is a conn_t queue, then we pass in the conn. This includes the
21709  * zoneid.
21710  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21711  * in which case we use the global zoneid since those are all part of
21712  * the global zone.
21713  */
21714 void
21715 ip_wput(queue_t *q, mblk_t *mp)
21716 {
21717 	if (CONN_Q(q))
21718 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21719 	else
21720 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21721 }
21722 
21723 /*
21724  *
21725  * The following rules must be observed when accessing any ipif or ill
21726  * that has been cached in the conn. Typically conn_outgoing_ill,
21727  * conn_multicast_ipif and conn_multicast_ill.
21728  *
21729  * Access: The ipif or ill pointed to from the conn can be accessed under
21730  * the protection of the conn_lock or after it has been refheld under the
21731  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21732  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21733  * The reason for this is that a concurrent unplumb could actually be
21734  * cleaning up these cached pointers by walking the conns and might have
21735  * finished cleaning up the conn in question. The macros check that an
21736  * unplumb has not yet started on the ipif or ill.
21737  *
21738  * Caching: An ipif or ill pointer may be cached in the conn only after
21739  * making sure that an unplumb has not started. So the caching is done
21740  * while holding both the conn_lock and the ill_lock and after using the
21741  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21742  * flag before starting the cleanup of conns.
21743  *
21744  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21745  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21746  * or a reference to the ipif or a reference to an ire that references the
21747  * ipif. An ipif only changes its ill when migrating from an underlying ill
21748  * to an IPMP ill in ipif_up().
21749  */
21750 ipif_t *
21751 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21752 {
21753 	ipif_t	*ipif;
21754 	ill_t	*ill;
21755 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21756 
21757 	*err = 0;
21758 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21759 	mutex_enter(&connp->conn_lock);
21760 	ipif = *ipifp;
21761 	if (ipif != NULL) {
21762 		ill = ipif->ipif_ill;
21763 		mutex_enter(&ill->ill_lock);
21764 		if (IPIF_CAN_LOOKUP(ipif)) {
21765 			ipif_refhold_locked(ipif);
21766 			mutex_exit(&ill->ill_lock);
21767 			mutex_exit(&connp->conn_lock);
21768 			rw_exit(&ipst->ips_ill_g_lock);
21769 			return (ipif);
21770 		} else {
21771 			*err = IPIF_LOOKUP_FAILED;
21772 		}
21773 		mutex_exit(&ill->ill_lock);
21774 	}
21775 	mutex_exit(&connp->conn_lock);
21776 	rw_exit(&ipst->ips_ill_g_lock);
21777 	return (NULL);
21778 }
21779 
21780 ill_t *
21781 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21782 {
21783 	ill_t	*ill;
21784 
21785 	*err = 0;
21786 	mutex_enter(&connp->conn_lock);
21787 	ill = *illp;
21788 	if (ill != NULL) {
21789 		mutex_enter(&ill->ill_lock);
21790 		if (ILL_CAN_LOOKUP(ill)) {
21791 			ill_refhold_locked(ill);
21792 			mutex_exit(&ill->ill_lock);
21793 			mutex_exit(&connp->conn_lock);
21794 			return (ill);
21795 		} else {
21796 			*err = ILL_LOOKUP_FAILED;
21797 		}
21798 		mutex_exit(&ill->ill_lock);
21799 	}
21800 	mutex_exit(&connp->conn_lock);
21801 	return (NULL);
21802 }
21803 
21804 static int
21805 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21806 {
21807 	ill_t	*ill;
21808 
21809 	ill = ipif->ipif_ill;
21810 	mutex_enter(&connp->conn_lock);
21811 	mutex_enter(&ill->ill_lock);
21812 	if (IPIF_CAN_LOOKUP(ipif)) {
21813 		*ipifp = ipif;
21814 		mutex_exit(&ill->ill_lock);
21815 		mutex_exit(&connp->conn_lock);
21816 		return (0);
21817 	}
21818 	mutex_exit(&ill->ill_lock);
21819 	mutex_exit(&connp->conn_lock);
21820 	return (IPIF_LOOKUP_FAILED);
21821 }
21822 
21823 /*
21824  * This is called if the outbound datagram needs fragmentation.
21825  *
21826  * NOTE : This function does not ire_refrele the ire argument passed in.
21827  */
21828 static void
21829 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21830     ip_stack_t *ipst, conn_t *connp)
21831 {
21832 	ipha_t		*ipha;
21833 	mblk_t		*mp;
21834 	uint32_t	v_hlen_tos_len;
21835 	uint32_t	max_frag;
21836 	uint32_t	frag_flag;
21837 	boolean_t	dont_use;
21838 
21839 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21840 		mp = ipsec_mp->b_cont;
21841 	} else {
21842 		mp = ipsec_mp;
21843 	}
21844 
21845 	ipha = (ipha_t *)mp->b_rptr;
21846 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21847 
21848 #ifdef	_BIG_ENDIAN
21849 #define	V_HLEN	(v_hlen_tos_len >> 24)
21850 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21851 #else
21852 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21853 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21854 #endif
21855 
21856 #ifndef SPEED_BEFORE_SAFETY
21857 	/*
21858 	 * Check that ipha_length is consistent with
21859 	 * the mblk length
21860 	 */
21861 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21862 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21863 		    LENGTH, msgdsize(mp)));
21864 		freemsg(ipsec_mp);
21865 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21866 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21867 		    "packet length mismatch");
21868 		return;
21869 	}
21870 #endif
21871 	/*
21872 	 * Don't use frag_flag if pre-built packet or source
21873 	 * routed or if multicast (since multicast packets do not solicit
21874 	 * ICMP "packet too big" messages). Get the values of
21875 	 * max_frag and frag_flag atomically by acquiring the
21876 	 * ire_lock.
21877 	 */
21878 	mutex_enter(&ire->ire_lock);
21879 	max_frag = ire->ire_max_frag;
21880 	frag_flag = ire->ire_frag_flag;
21881 	mutex_exit(&ire->ire_lock);
21882 
21883 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21884 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21885 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21886 
21887 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21888 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21889 }
21890 
21891 /*
21892  * Used for deciding the MSS size for the upper layer. Thus
21893  * we need to check the outbound policy values in the conn.
21894  */
21895 int
21896 conn_ipsec_length(conn_t *connp)
21897 {
21898 	ipsec_latch_t *ipl;
21899 
21900 	ipl = connp->conn_latch;
21901 	if (ipl == NULL)
21902 		return (0);
21903 
21904 	if (ipl->ipl_out_policy == NULL)
21905 		return (0);
21906 
21907 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21908 }
21909 
21910 /*
21911  * Returns an estimate of the IPsec headers size. This is used if
21912  * we don't want to call into IPsec to get the exact size.
21913  */
21914 int
21915 ipsec_out_extra_length(mblk_t *ipsec_mp)
21916 {
21917 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21918 	ipsec_action_t *a;
21919 
21920 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21921 	if (!io->ipsec_out_secure)
21922 		return (0);
21923 
21924 	a = io->ipsec_out_act;
21925 
21926 	if (a == NULL) {
21927 		ASSERT(io->ipsec_out_policy != NULL);
21928 		a = io->ipsec_out_policy->ipsp_act;
21929 	}
21930 	ASSERT(a != NULL);
21931 
21932 	return (a->ipa_ovhd);
21933 }
21934 
21935 /*
21936  * Returns an estimate of the IPsec headers size. This is used if
21937  * we don't want to call into IPsec to get the exact size.
21938  */
21939 int
21940 ipsec_in_extra_length(mblk_t *ipsec_mp)
21941 {
21942 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21943 	ipsec_action_t *a;
21944 
21945 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21946 
21947 	a = ii->ipsec_in_action;
21948 	return (a == NULL ? 0 : a->ipa_ovhd);
21949 }
21950 
21951 /*
21952  * If there are any source route options, return the true final
21953  * destination. Otherwise, return the destination.
21954  */
21955 ipaddr_t
21956 ip_get_dst(ipha_t *ipha)
21957 {
21958 	ipoptp_t	opts;
21959 	uchar_t		*opt;
21960 	uint8_t		optval;
21961 	uint8_t		optlen;
21962 	ipaddr_t	dst;
21963 	uint32_t off;
21964 
21965 	dst = ipha->ipha_dst;
21966 
21967 	if (IS_SIMPLE_IPH(ipha))
21968 		return (dst);
21969 
21970 	for (optval = ipoptp_first(&opts, ipha);
21971 	    optval != IPOPT_EOL;
21972 	    optval = ipoptp_next(&opts)) {
21973 		opt = opts.ipoptp_cur;
21974 		optlen = opts.ipoptp_len;
21975 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21976 		switch (optval) {
21977 		case IPOPT_SSRR:
21978 		case IPOPT_LSRR:
21979 			off = opt[IPOPT_OFFSET];
21980 			/*
21981 			 * If one of the conditions is true, it means
21982 			 * end of options and dst already has the right
21983 			 * value.
21984 			 */
21985 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21986 				off = optlen - IP_ADDR_LEN;
21987 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21988 			}
21989 			return (dst);
21990 		default:
21991 			break;
21992 		}
21993 	}
21994 
21995 	return (dst);
21996 }
21997 
21998 mblk_t *
21999 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22000     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22001 {
22002 	ipsec_out_t	*io;
22003 	mblk_t		*first_mp;
22004 	boolean_t policy_present;
22005 	ip_stack_t	*ipst;
22006 	ipsec_stack_t	*ipss;
22007 
22008 	ASSERT(ire != NULL);
22009 	ipst = ire->ire_ipst;
22010 	ipss = ipst->ips_netstack->netstack_ipsec;
22011 
22012 	first_mp = mp;
22013 	if (mp->b_datap->db_type == M_CTL) {
22014 		io = (ipsec_out_t *)first_mp->b_rptr;
22015 		/*
22016 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22017 		 *
22018 		 * 1) There is per-socket policy (including cached global
22019 		 *    policy) or a policy on the IP-in-IP tunnel.
22020 		 * 2) There is no per-socket policy, but it is
22021 		 *    a multicast packet that needs to go out
22022 		 *    on a specific interface. This is the case
22023 		 *    where (ip_wput and ip_wput_multicast) attaches
22024 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22025 		 *
22026 		 * In case (2) we check with global policy to
22027 		 * see if there is a match and set the ill_index
22028 		 * appropriately so that we can lookup the ire
22029 		 * properly in ip_wput_ipsec_out.
22030 		 */
22031 
22032 		/*
22033 		 * ipsec_out_use_global_policy is set to B_FALSE
22034 		 * in ipsec_in_to_out(). Refer to that function for
22035 		 * details.
22036 		 */
22037 		if ((io->ipsec_out_latch == NULL) &&
22038 		    (io->ipsec_out_use_global_policy)) {
22039 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22040 			    ire, connp, unspec_src, zoneid));
22041 		}
22042 		if (!io->ipsec_out_secure) {
22043 			/*
22044 			 * If this is not a secure packet, drop
22045 			 * the IPSEC_OUT mp and treat it as a clear
22046 			 * packet. This happens when we are sending
22047 			 * a ICMP reply back to a clear packet. See
22048 			 * ipsec_in_to_out() for details.
22049 			 */
22050 			mp = first_mp->b_cont;
22051 			freeb(first_mp);
22052 		}
22053 		return (mp);
22054 	}
22055 	/*
22056 	 * See whether we need to attach a global policy here. We
22057 	 * don't depend on the conn (as it could be null) for deciding
22058 	 * what policy this datagram should go through because it
22059 	 * should have happened in ip_wput if there was some
22060 	 * policy. This normally happens for connections which are not
22061 	 * fully bound preventing us from caching policies in
22062 	 * ip_bind. Packets coming from the TCP listener/global queue
22063 	 * - which are non-hard_bound - could also be affected by
22064 	 * applying policy here.
22065 	 *
22066 	 * If this packet is coming from tcp global queue or listener,
22067 	 * we will be applying policy here.  This may not be *right*
22068 	 * if these packets are coming from the detached connection as
22069 	 * it could have gone in clear before. This happens only if a
22070 	 * TCP connection started when there is no policy and somebody
22071 	 * added policy before it became detached. Thus packets of the
22072 	 * detached connection could go out secure and the other end
22073 	 * would drop it because it will be expecting in clear. The
22074 	 * converse is not true i.e if somebody starts a TCP
22075 	 * connection and deletes the policy, all the packets will
22076 	 * still go out with the policy that existed before deleting
22077 	 * because ip_unbind sends up policy information which is used
22078 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22079 	 * TCP to attach a dummy IPSEC_OUT and set
22080 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22081 	 * affect performance for normal cases, we are not doing it.
22082 	 * Thus, set policy before starting any TCP connections.
22083 	 *
22084 	 * NOTE - We might apply policy even for a hard bound connection
22085 	 * - for which we cached policy in ip_bind - if somebody added
22086 	 * global policy after we inherited the policy in ip_bind.
22087 	 * This means that the packets that were going out in clear
22088 	 * previously would start going secure and hence get dropped
22089 	 * on the other side. To fix this, TCP attaches a dummy
22090 	 * ipsec_out and make sure that we don't apply global policy.
22091 	 */
22092 	if (ipha != NULL)
22093 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22094 	else
22095 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22096 	if (!policy_present)
22097 		return (mp);
22098 
22099 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22100 	    zoneid));
22101 }
22102 
22103 /*
22104  * This function does the ire_refrele of the ire passed in as the
22105  * argument. As this function looks up more ires i.e broadcast ires,
22106  * it needs to REFRELE them. Currently, for simplicity we don't
22107  * differentiate the one passed in and looked up here. We always
22108  * REFRELE.
22109  * IPQoS Notes:
22110  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22111  * IPsec packets are done in ipsec_out_process.
22112  */
22113 void
22114 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22115     zoneid_t zoneid)
22116 {
22117 	ipha_t		*ipha;
22118 #define	rptr	((uchar_t *)ipha)
22119 	queue_t		*stq;
22120 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22121 	uint32_t	v_hlen_tos_len;
22122 	uint32_t	ttl_protocol;
22123 	ipaddr_t	src;
22124 	ipaddr_t	dst;
22125 	uint32_t	cksum;
22126 	ipaddr_t	orig_src;
22127 	ire_t		*ire1;
22128 	mblk_t		*next_mp;
22129 	uint_t		hlen;
22130 	uint16_t	*up;
22131 	uint32_t	max_frag = ire->ire_max_frag;
22132 	ill_t		*ill = ire_to_ill(ire);
22133 	int		clusterwide;
22134 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22135 	int		ipsec_len;
22136 	mblk_t		*first_mp;
22137 	ipsec_out_t	*io;
22138 	boolean_t	conn_dontroute;		/* conn value for multicast */
22139 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22140 	boolean_t	multicast_forward;	/* Should we forward ? */
22141 	boolean_t	unspec_src;
22142 	ill_t		*conn_outgoing_ill = NULL;
22143 	ill_t		*ire_ill;
22144 	ill_t		*ire1_ill;
22145 	ill_t		*out_ill;
22146 	uint32_t 	ill_index = 0;
22147 	boolean_t	multirt_send = B_FALSE;
22148 	int		err;
22149 	ipxmit_state_t	pktxmit_state;
22150 	ip_stack_t	*ipst = ire->ire_ipst;
22151 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22152 
22153 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22154 	    "ip_wput_ire_start: q %p", q);
22155 
22156 	multicast_forward = B_FALSE;
22157 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22158 
22159 	if (ire->ire_flags & RTF_MULTIRT) {
22160 		/*
22161 		 * Multirouting case. The bucket where ire is stored
22162 		 * probably holds other RTF_MULTIRT flagged ire
22163 		 * to the destination. In this call to ip_wput_ire,
22164 		 * we attempt to send the packet through all
22165 		 * those ires. Thus, we first ensure that ire is the
22166 		 * first RTF_MULTIRT ire in the bucket,
22167 		 * before walking the ire list.
22168 		 */
22169 		ire_t *first_ire;
22170 		irb_t *irb = ire->ire_bucket;
22171 		ASSERT(irb != NULL);
22172 
22173 		/* Make sure we do not omit any multiroute ire. */
22174 		IRB_REFHOLD(irb);
22175 		for (first_ire = irb->irb_ire;
22176 		    first_ire != NULL;
22177 		    first_ire = first_ire->ire_next) {
22178 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22179 			    (first_ire->ire_addr == ire->ire_addr) &&
22180 			    !(first_ire->ire_marks &
22181 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22182 				break;
22183 		}
22184 
22185 		if ((first_ire != NULL) && (first_ire != ire)) {
22186 			IRE_REFHOLD(first_ire);
22187 			ire_refrele(ire);
22188 			ire = first_ire;
22189 			ill = ire_to_ill(ire);
22190 		}
22191 		IRB_REFRELE(irb);
22192 	}
22193 
22194 	/*
22195 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22196 	 * for performance we don't grab the mutexs in the fastpath
22197 	 */
22198 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22199 	    connp->conn_outgoing_ill != NULL) {
22200 		conn_outgoing_ill = conn_get_held_ill(connp,
22201 		    &connp->conn_outgoing_ill, &err);
22202 		if (err == ILL_LOOKUP_FAILED) {
22203 			ire_refrele(ire);
22204 			freemsg(mp);
22205 			return;
22206 		}
22207 	}
22208 
22209 	if (mp->b_datap->db_type != M_CTL) {
22210 		ipha = (ipha_t *)mp->b_rptr;
22211 	} else {
22212 		io = (ipsec_out_t *)mp->b_rptr;
22213 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22214 		ASSERT(zoneid == io->ipsec_out_zoneid);
22215 		ASSERT(zoneid != ALL_ZONES);
22216 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22217 		dst = ipha->ipha_dst;
22218 		/*
22219 		 * For the multicast case, ipsec_out carries conn_dontroute and
22220 		 * conn_multicast_loop as conn may not be available here. We
22221 		 * need this for multicast loopback and forwarding which is done
22222 		 * later in the code.
22223 		 */
22224 		if (CLASSD(dst)) {
22225 			conn_dontroute = io->ipsec_out_dontroute;
22226 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22227 			/*
22228 			 * If conn_dontroute is not set or conn_multicast_loop
22229 			 * is set, we need to do forwarding/loopback. For
22230 			 * datagrams from ip_wput_multicast, conn_dontroute is
22231 			 * set to B_TRUE and conn_multicast_loop is set to
22232 			 * B_FALSE so that we neither do forwarding nor
22233 			 * loopback.
22234 			 */
22235 			if (!conn_dontroute || conn_multicast_loop)
22236 				multicast_forward = B_TRUE;
22237 		}
22238 	}
22239 
22240 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22241 	    ire->ire_zoneid != ALL_ZONES) {
22242 		/*
22243 		 * When a zone sends a packet to another zone, we try to deliver
22244 		 * the packet under the same conditions as if the destination
22245 		 * was a real node on the network. To do so, we look for a
22246 		 * matching route in the forwarding table.
22247 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22248 		 * ip_newroute() does.
22249 		 * Note that IRE_LOCAL are special, since they are used
22250 		 * when the zoneid doesn't match in some cases. This means that
22251 		 * we need to handle ipha_src differently since ire_src_addr
22252 		 * belongs to the receiving zone instead of the sending zone.
22253 		 * When ip_restrict_interzone_loopback is set, then
22254 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22255 		 * for loopback between zones when the logical "Ethernet" would
22256 		 * have looped them back.
22257 		 */
22258 		ire_t *src_ire;
22259 
22260 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22261 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22262 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22263 		if (src_ire != NULL &&
22264 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22265 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22266 		    ire_local_same_lan(ire, src_ire))) {
22267 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22268 				ipha->ipha_src = src_ire->ire_src_addr;
22269 			ire_refrele(src_ire);
22270 		} else {
22271 			ire_refrele(ire);
22272 			if (conn_outgoing_ill != NULL)
22273 				ill_refrele(conn_outgoing_ill);
22274 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22275 			if (src_ire != NULL) {
22276 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22277 					ire_refrele(src_ire);
22278 					freemsg(mp);
22279 					return;
22280 				}
22281 				ire_refrele(src_ire);
22282 			}
22283 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22284 				/* Failed */
22285 				freemsg(mp);
22286 				return;
22287 			}
22288 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22289 			    ipst);
22290 			return;
22291 		}
22292 	}
22293 
22294 	if (mp->b_datap->db_type == M_CTL ||
22295 	    ipss->ipsec_outbound_v4_policy_present) {
22296 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22297 		    unspec_src, zoneid);
22298 		if (mp == NULL) {
22299 			ire_refrele(ire);
22300 			if (conn_outgoing_ill != NULL)
22301 				ill_refrele(conn_outgoing_ill);
22302 			return;
22303 		}
22304 		/*
22305 		 * Trusted Extensions supports all-zones interfaces, so
22306 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22307 		 * the global zone.
22308 		 */
22309 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22310 			io = (ipsec_out_t *)mp->b_rptr;
22311 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22312 			zoneid = io->ipsec_out_zoneid;
22313 		}
22314 	}
22315 
22316 	first_mp = mp;
22317 	ipsec_len = 0;
22318 
22319 	if (first_mp->b_datap->db_type == M_CTL) {
22320 		io = (ipsec_out_t *)first_mp->b_rptr;
22321 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22322 		mp = first_mp->b_cont;
22323 		ipsec_len = ipsec_out_extra_length(first_mp);
22324 		ASSERT(ipsec_len >= 0);
22325 		/* We already picked up the zoneid from the M_CTL above */
22326 		ASSERT(zoneid == io->ipsec_out_zoneid);
22327 		ASSERT(zoneid != ALL_ZONES);
22328 
22329 		/*
22330 		 * Drop M_CTL here if IPsec processing is not needed.
22331 		 * (Non-IPsec use of M_CTL extracted any information it
22332 		 * needed above).
22333 		 */
22334 		if (ipsec_len == 0) {
22335 			freeb(first_mp);
22336 			first_mp = mp;
22337 		}
22338 	}
22339 
22340 	/*
22341 	 * Fast path for ip_wput_ire
22342 	 */
22343 
22344 	ipha = (ipha_t *)mp->b_rptr;
22345 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22346 	dst = ipha->ipha_dst;
22347 
22348 	/*
22349 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22350 	 * if the socket is a SOCK_RAW type. The transport checksum should
22351 	 * be provided in the pre-built packet, so we don't need to compute it.
22352 	 * Also, other application set flags, like DF, should not be altered.
22353 	 * Other transport MUST pass down zero.
22354 	 */
22355 	ip_hdr_included = ipha->ipha_ident;
22356 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22357 
22358 	if (CLASSD(dst)) {
22359 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22360 		    ntohl(dst),
22361 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22362 		    ntohl(ire->ire_addr)));
22363 	}
22364 
22365 /* Macros to extract header fields from data already in registers */
22366 #ifdef	_BIG_ENDIAN
22367 #define	V_HLEN	(v_hlen_tos_len >> 24)
22368 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22369 #define	PROTO	(ttl_protocol & 0xFF)
22370 #else
22371 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22372 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22373 #define	PROTO	(ttl_protocol >> 8)
22374 #endif
22375 
22376 	orig_src = src = ipha->ipha_src;
22377 	/* (The loop back to "another" is explained down below.) */
22378 another:;
22379 	/*
22380 	 * Assign an ident value for this packet.  We assign idents on
22381 	 * a per destination basis out of the IRE.  There could be
22382 	 * other threads targeting the same destination, so we have to
22383 	 * arrange for a atomic increment.  Note that we use a 32-bit
22384 	 * atomic add because it has better performance than its
22385 	 * 16-bit sibling.
22386 	 *
22387 	 * If running in cluster mode and if the source address
22388 	 * belongs to a replicated service then vector through
22389 	 * cl_inet_ipident vector to allocate ip identifier
22390 	 * NOTE: This is a contract private interface with the
22391 	 * clustering group.
22392 	 */
22393 	clusterwide = 0;
22394 	if (cl_inet_ipident) {
22395 		ASSERT(cl_inet_isclusterwide);
22396 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22397 
22398 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22399 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22400 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22401 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22402 			    (uint8_t *)(uintptr_t)dst, NULL);
22403 			clusterwide = 1;
22404 		}
22405 	}
22406 	if (!clusterwide) {
22407 		ipha->ipha_ident =
22408 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22409 	}
22410 
22411 #ifndef _BIG_ENDIAN
22412 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22413 #endif
22414 
22415 	/*
22416 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22417 	 * This is needed to obey conn_unspec_src when packets go through
22418 	 * ip_newroute + arp.
22419 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22420 	 */
22421 	if (src == INADDR_ANY && !unspec_src) {
22422 		/*
22423 		 * Assign the appropriate source address from the IRE if none
22424 		 * was specified.
22425 		 */
22426 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22427 
22428 		src = ire->ire_src_addr;
22429 		if (connp == NULL) {
22430 			ip1dbg(("ip_wput_ire: no connp and no src "
22431 			    "address for dst 0x%x, using src 0x%x\n",
22432 			    ntohl(dst),
22433 			    ntohl(src)));
22434 		}
22435 		ipha->ipha_src = src;
22436 	}
22437 	stq = ire->ire_stq;
22438 
22439 	/*
22440 	 * We only allow ire chains for broadcasts since there will
22441 	 * be multiple IRE_CACHE entries for the same multicast
22442 	 * address (one per ipif).
22443 	 */
22444 	next_mp = NULL;
22445 
22446 	/* broadcast packet */
22447 	if (ire->ire_type == IRE_BROADCAST)
22448 		goto broadcast;
22449 
22450 	/* loopback ? */
22451 	if (stq == NULL)
22452 		goto nullstq;
22453 
22454 	/* The ill_index for outbound ILL */
22455 	ill_index = Q_TO_INDEX(stq);
22456 
22457 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22458 	ttl_protocol = ((uint16_t *)ipha)[4];
22459 
22460 	/* pseudo checksum (do it in parts for IP header checksum) */
22461 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22462 
22463 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22464 		queue_t *dev_q = stq->q_next;
22465 
22466 		/*
22467 		 * For DIRECT_CAPABLE, we do flow control at
22468 		 * the time of sending the packet. See
22469 		 * ILL_SEND_TX().
22470 		 */
22471 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22472 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22473 			goto blocked;
22474 
22475 		if ((PROTO == IPPROTO_UDP) &&
22476 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22477 			hlen = (V_HLEN & 0xF) << 2;
22478 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22479 			if (*up != 0) {
22480 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22481 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22482 				/* Software checksum? */
22483 				if (DB_CKSUMFLAGS(mp) == 0) {
22484 					IP_STAT(ipst, ip_out_sw_cksum);
22485 					IP_STAT_UPDATE(ipst,
22486 					    ip_udp_out_sw_cksum_bytes,
22487 					    LENGTH - hlen);
22488 				}
22489 			}
22490 		}
22491 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22492 		hlen = (V_HLEN & 0xF) << 2;
22493 		if (PROTO == IPPROTO_TCP) {
22494 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22495 			/*
22496 			 * The packet header is processed once and for all, even
22497 			 * in the multirouting case. We disable hardware
22498 			 * checksum if the packet is multirouted, as it will be
22499 			 * replicated via several interfaces, and not all of
22500 			 * them may have this capability.
22501 			 */
22502 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22503 			    LENGTH, max_frag, ipsec_len, cksum);
22504 			/* Software checksum? */
22505 			if (DB_CKSUMFLAGS(mp) == 0) {
22506 				IP_STAT(ipst, ip_out_sw_cksum);
22507 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22508 				    LENGTH - hlen);
22509 			}
22510 		} else {
22511 			sctp_hdr_t	*sctph;
22512 
22513 			ASSERT(PROTO == IPPROTO_SCTP);
22514 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22515 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22516 			/*
22517 			 * Zero out the checksum field to ensure proper
22518 			 * checksum calculation.
22519 			 */
22520 			sctph->sh_chksum = 0;
22521 #ifdef	DEBUG
22522 			if (!skip_sctp_cksum)
22523 #endif
22524 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22525 		}
22526 	}
22527 
22528 	/*
22529 	 * If this is a multicast packet and originated from ip_wput
22530 	 * we need to do loopback and forwarding checks. If it comes
22531 	 * from ip_wput_multicast, we SHOULD not do this.
22532 	 */
22533 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22534 
22535 	/* checksum */
22536 	cksum += ttl_protocol;
22537 
22538 	/* fragment the packet */
22539 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22540 		goto fragmentit;
22541 	/*
22542 	 * Don't use frag_flag if packet is pre-built or source
22543 	 * routed or if multicast (since multicast packets do
22544 	 * not solicit ICMP "packet too big" messages).
22545 	 */
22546 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22547 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22548 	    !ip_source_route_included(ipha)) &&
22549 	    !CLASSD(ipha->ipha_dst))
22550 		ipha->ipha_fragment_offset_and_flags |=
22551 		    htons(ire->ire_frag_flag);
22552 
22553 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22554 		/* calculate IP header checksum */
22555 		cksum += ipha->ipha_ident;
22556 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22557 		cksum += ipha->ipha_fragment_offset_and_flags;
22558 
22559 		/* IP options present */
22560 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22561 		if (hlen)
22562 			goto checksumoptions;
22563 
22564 		/* calculate hdr checksum */
22565 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22566 		cksum = ~(cksum + (cksum >> 16));
22567 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22568 	}
22569 	if (ipsec_len != 0) {
22570 		/*
22571 		 * We will do the rest of the processing after
22572 		 * we come back from IPsec in ip_wput_ipsec_out().
22573 		 */
22574 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22575 
22576 		io = (ipsec_out_t *)first_mp->b_rptr;
22577 		io->ipsec_out_ill_index =
22578 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22579 		ipsec_out_process(q, first_mp, ire, 0);
22580 		ire_refrele(ire);
22581 		if (conn_outgoing_ill != NULL)
22582 			ill_refrele(conn_outgoing_ill);
22583 		return;
22584 	}
22585 
22586 	/*
22587 	 * In most cases, the emission loop below is entered only
22588 	 * once. Only in the case where the ire holds the
22589 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22590 	 * flagged ires in the bucket, and send the packet
22591 	 * through all crossed RTF_MULTIRT routes.
22592 	 */
22593 	if (ire->ire_flags & RTF_MULTIRT) {
22594 		multirt_send = B_TRUE;
22595 	}
22596 	do {
22597 		if (multirt_send) {
22598 			irb_t *irb;
22599 			/*
22600 			 * We are in a multiple send case, need to get
22601 			 * the next ire and make a duplicate of the packet.
22602 			 * ire1 holds here the next ire to process in the
22603 			 * bucket. If multirouting is expected,
22604 			 * any non-RTF_MULTIRT ire that has the
22605 			 * right destination address is ignored.
22606 			 */
22607 			irb = ire->ire_bucket;
22608 			ASSERT(irb != NULL);
22609 
22610 			IRB_REFHOLD(irb);
22611 			for (ire1 = ire->ire_next;
22612 			    ire1 != NULL;
22613 			    ire1 = ire1->ire_next) {
22614 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22615 					continue;
22616 				if (ire1->ire_addr != ire->ire_addr)
22617 					continue;
22618 				if (ire1->ire_marks &
22619 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22620 					continue;
22621 
22622 				/* Got one */
22623 				IRE_REFHOLD(ire1);
22624 				break;
22625 			}
22626 			IRB_REFRELE(irb);
22627 
22628 			if (ire1 != NULL) {
22629 				next_mp = copyb(mp);
22630 				if ((next_mp == NULL) ||
22631 				    ((mp->b_cont != NULL) &&
22632 				    ((next_mp->b_cont =
22633 				    dupmsg(mp->b_cont)) == NULL))) {
22634 					freemsg(next_mp);
22635 					next_mp = NULL;
22636 					ire_refrele(ire1);
22637 					ire1 = NULL;
22638 				}
22639 			}
22640 
22641 			/* Last multiroute ire; don't loop anymore. */
22642 			if (ire1 == NULL) {
22643 				multirt_send = B_FALSE;
22644 			}
22645 		}
22646 
22647 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22648 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22649 		    mblk_t *, mp);
22650 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22651 		    ipst->ips_ipv4firewall_physical_out,
22652 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22653 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22654 
22655 		if (mp == NULL)
22656 			goto release_ire_and_ill;
22657 
22658 		if (ipst->ips_ipobs_enabled) {
22659 			zoneid_t szone;
22660 
22661 			/*
22662 			 * On the outbound path the destination zone will be
22663 			 * unknown as we're sending this packet out on the
22664 			 * wire.
22665 			 */
22666 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22667 			    ALL_ZONES);
22668 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22669 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22670 		}
22671 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22672 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22673 
22674 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22675 
22676 		if ((pktxmit_state == SEND_FAILED) ||
22677 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22678 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22679 			    "- packet dropped\n"));
22680 release_ire_and_ill:
22681 			ire_refrele(ire);
22682 			if (next_mp != NULL) {
22683 				freemsg(next_mp);
22684 				ire_refrele(ire1);
22685 			}
22686 			if (conn_outgoing_ill != NULL)
22687 				ill_refrele(conn_outgoing_ill);
22688 			return;
22689 		}
22690 
22691 		if (CLASSD(dst)) {
22692 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22693 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22694 			    LENGTH);
22695 		}
22696 
22697 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22698 		    "ip_wput_ire_end: q %p (%S)",
22699 		    q, "last copy out");
22700 		IRE_REFRELE(ire);
22701 
22702 		if (multirt_send) {
22703 			ASSERT(ire1);
22704 			/*
22705 			 * Proceed with the next RTF_MULTIRT ire,
22706 			 * Also set up the send-to queue accordingly.
22707 			 */
22708 			ire = ire1;
22709 			ire1 = NULL;
22710 			stq = ire->ire_stq;
22711 			mp = next_mp;
22712 			next_mp = NULL;
22713 			ipha = (ipha_t *)mp->b_rptr;
22714 			ill_index = Q_TO_INDEX(stq);
22715 			ill = (ill_t *)stq->q_ptr;
22716 		}
22717 	} while (multirt_send);
22718 	if (conn_outgoing_ill != NULL)
22719 		ill_refrele(conn_outgoing_ill);
22720 	return;
22721 
22722 	/*
22723 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22724 	 */
22725 broadcast:
22726 	{
22727 		/*
22728 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22729 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22730 		 * can be overridden stack-wide through the ip_broadcast_ttl
22731 		 * ndd tunable, or on a per-connection basis through the
22732 		 * IP_BROADCAST_TTL socket option.
22733 		 *
22734 		 * In the event that we are replying to incoming ICMP packets,
22735 		 * connp could be NULL.
22736 		 */
22737 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22738 		if (connp != NULL) {
22739 			if (connp->conn_dontroute)
22740 				ipha->ipha_ttl = 1;
22741 			else if (connp->conn_broadcast_ttl != 0)
22742 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22743 		}
22744 
22745 		/*
22746 		 * Note that we are not doing a IRB_REFHOLD here.
22747 		 * Actually we don't care if the list changes i.e
22748 		 * if somebody deletes an IRE from the list while
22749 		 * we drop the lock, the next time we come around
22750 		 * ire_next will be NULL and hence we won't send
22751 		 * out multiple copies which is fine.
22752 		 */
22753 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22754 		ire1 = ire->ire_next;
22755 		if (conn_outgoing_ill != NULL) {
22756 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22757 				ASSERT(ire1 == ire->ire_next);
22758 				if (ire1 != NULL && ire1->ire_addr == dst) {
22759 					ire_refrele(ire);
22760 					ire = ire1;
22761 					IRE_REFHOLD(ire);
22762 					ire1 = ire->ire_next;
22763 					continue;
22764 				}
22765 				rw_exit(&ire->ire_bucket->irb_lock);
22766 				/* Did not find a matching ill */
22767 				ip1dbg(("ip_wput_ire: broadcast with no "
22768 				    "matching IP_BOUND_IF ill %s dst %x\n",
22769 				    conn_outgoing_ill->ill_name, dst));
22770 				freemsg(first_mp);
22771 				if (ire != NULL)
22772 					ire_refrele(ire);
22773 				ill_refrele(conn_outgoing_ill);
22774 				return;
22775 			}
22776 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22777 			/*
22778 			 * If the next IRE has the same address and is not one
22779 			 * of the two copies that we need to send, try to see
22780 			 * whether this copy should be sent at all. This
22781 			 * assumes that we insert loopbacks first and then
22782 			 * non-loopbacks. This is acheived by inserting the
22783 			 * loopback always before non-loopback.
22784 			 * This is used to send a single copy of a broadcast
22785 			 * packet out all physical interfaces that have an
22786 			 * matching IRE_BROADCAST while also looping
22787 			 * back one copy (to ip_wput_local) for each
22788 			 * matching physical interface. However, we avoid
22789 			 * sending packets out different logical that match by
22790 			 * having ipif_up/ipif_down supress duplicate
22791 			 * IRE_BROADCASTS.
22792 			 *
22793 			 * This feature is currently used to get broadcasts
22794 			 * sent to multiple interfaces, when the broadcast
22795 			 * address being used applies to multiple interfaces.
22796 			 * For example, a whole net broadcast will be
22797 			 * replicated on every connected subnet of
22798 			 * the target net.
22799 			 *
22800 			 * Each zone has its own set of IRE_BROADCASTs, so that
22801 			 * we're able to distribute inbound packets to multiple
22802 			 * zones who share a broadcast address. We avoid looping
22803 			 * back outbound packets in different zones but on the
22804 			 * same ill, as the application would see duplicates.
22805 			 *
22806 			 * This logic assumes that ire_add_v4() groups the
22807 			 * IRE_BROADCAST entries so that those with the same
22808 			 * ire_addr are kept together.
22809 			 */
22810 			ire_ill = ire->ire_ipif->ipif_ill;
22811 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22812 				while (ire1 != NULL && ire1->ire_addr == dst) {
22813 					ire1_ill = ire1->ire_ipif->ipif_ill;
22814 					if (ire1_ill != ire_ill)
22815 						break;
22816 					ire1 = ire1->ire_next;
22817 				}
22818 			}
22819 		}
22820 		ASSERT(multirt_send == B_FALSE);
22821 		if (ire1 != NULL && ire1->ire_addr == dst) {
22822 			if ((ire->ire_flags & RTF_MULTIRT) &&
22823 			    (ire1->ire_flags & RTF_MULTIRT)) {
22824 				/*
22825 				 * We are in the multirouting case.
22826 				 * The message must be sent at least
22827 				 * on both ires. These ires have been
22828 				 * inserted AFTER the standard ones
22829 				 * in ip_rt_add(). There are thus no
22830 				 * other ire entries for the destination
22831 				 * address in the rest of the bucket
22832 				 * that do not have the RTF_MULTIRT
22833 				 * flag. We don't process a copy
22834 				 * of the message here. This will be
22835 				 * done in the final sending loop.
22836 				 */
22837 				multirt_send = B_TRUE;
22838 			} else {
22839 				next_mp = ip_copymsg(first_mp);
22840 				if (next_mp != NULL)
22841 					IRE_REFHOLD(ire1);
22842 			}
22843 		}
22844 		rw_exit(&ire->ire_bucket->irb_lock);
22845 	}
22846 
22847 	if (stq) {
22848 		/*
22849 		 * A non-NULL send-to queue means this packet is going
22850 		 * out of this machine.
22851 		 */
22852 		out_ill = (ill_t *)stq->q_ptr;
22853 
22854 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22855 		ttl_protocol = ((uint16_t *)ipha)[4];
22856 		/*
22857 		 * We accumulate the pseudo header checksum in cksum.
22858 		 * This is pretty hairy code, so watch close.  One
22859 		 * thing to keep in mind is that UDP and TCP have
22860 		 * stored their respective datagram lengths in their
22861 		 * checksum fields.  This lines things up real nice.
22862 		 */
22863 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22864 		    (src >> 16) + (src & 0xFFFF);
22865 		/*
22866 		 * We assume the udp checksum field contains the
22867 		 * length, so to compute the pseudo header checksum,
22868 		 * all we need is the protocol number and src/dst.
22869 		 */
22870 		/* Provide the checksums for UDP and TCP. */
22871 		if ((PROTO == IPPROTO_TCP) &&
22872 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22873 			/* hlen gets the number of uchar_ts in the IP header */
22874 			hlen = (V_HLEN & 0xF) << 2;
22875 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22876 			IP_STAT(ipst, ip_out_sw_cksum);
22877 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22878 			    LENGTH - hlen);
22879 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22880 		} else if (PROTO == IPPROTO_SCTP &&
22881 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22882 			sctp_hdr_t	*sctph;
22883 
22884 			hlen = (V_HLEN & 0xF) << 2;
22885 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22886 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22887 			sctph->sh_chksum = 0;
22888 #ifdef	DEBUG
22889 			if (!skip_sctp_cksum)
22890 #endif
22891 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22892 		} else {
22893 			queue_t	*dev_q = stq->q_next;
22894 
22895 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22896 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22897 blocked:
22898 				ipha->ipha_ident = ip_hdr_included;
22899 				/*
22900 				 * If we don't have a conn to apply
22901 				 * backpressure, free the message.
22902 				 * In the ire_send path, we don't know
22903 				 * the position to requeue the packet. Rather
22904 				 * than reorder packets, we just drop this
22905 				 * packet.
22906 				 */
22907 				if (ipst->ips_ip_output_queue &&
22908 				    connp != NULL &&
22909 				    caller != IRE_SEND) {
22910 					if (caller == IP_WSRV) {
22911 						idl_tx_list_t *idl_txl;
22912 
22913 						idl_txl =
22914 						    &ipst->ips_idl_tx_list[0];
22915 						connp->conn_did_putbq = 1;
22916 						(void) putbq(connp->conn_wq,
22917 						    first_mp);
22918 						conn_drain_insert(connp,
22919 						    idl_txl);
22920 						/*
22921 						 * This is the service thread,
22922 						 * and the queue is already
22923 						 * noenabled. The check for
22924 						 * canput and the putbq is not
22925 						 * atomic. So we need to check
22926 						 * again.
22927 						 */
22928 						if (canput(stq->q_next))
22929 							connp->conn_did_putbq
22930 							    = 0;
22931 						IP_STAT(ipst, ip_conn_flputbq);
22932 					} else {
22933 						/*
22934 						 * We are not the service proc.
22935 						 * ip_wsrv will be scheduled or
22936 						 * is already running.
22937 						 */
22938 
22939 						(void) putq(connp->conn_wq,
22940 						    first_mp);
22941 					}
22942 				} else {
22943 					out_ill = (ill_t *)stq->q_ptr;
22944 					BUMP_MIB(out_ill->ill_ip_mib,
22945 					    ipIfStatsOutDiscards);
22946 					freemsg(first_mp);
22947 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22948 					    "ip_wput_ire_end: q %p (%S)",
22949 					    q, "discard");
22950 				}
22951 				ire_refrele(ire);
22952 				if (next_mp) {
22953 					ire_refrele(ire1);
22954 					freemsg(next_mp);
22955 				}
22956 				if (conn_outgoing_ill != NULL)
22957 					ill_refrele(conn_outgoing_ill);
22958 				return;
22959 			}
22960 			if ((PROTO == IPPROTO_UDP) &&
22961 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22962 				/*
22963 				 * hlen gets the number of uchar_ts in the
22964 				 * IP header
22965 				 */
22966 				hlen = (V_HLEN & 0xF) << 2;
22967 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22968 				max_frag = ire->ire_max_frag;
22969 				if (*up != 0) {
22970 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22971 					    up, PROTO, hlen, LENGTH, max_frag,
22972 					    ipsec_len, cksum);
22973 					/* Software checksum? */
22974 					if (DB_CKSUMFLAGS(mp) == 0) {
22975 						IP_STAT(ipst, ip_out_sw_cksum);
22976 						IP_STAT_UPDATE(ipst,
22977 						    ip_udp_out_sw_cksum_bytes,
22978 						    LENGTH - hlen);
22979 					}
22980 				}
22981 			}
22982 		}
22983 		/*
22984 		 * Need to do this even when fragmenting. The local
22985 		 * loopback can be done without computing checksums
22986 		 * but forwarding out other interface must be done
22987 		 * after the IP checksum (and ULP checksums) have been
22988 		 * computed.
22989 		 *
22990 		 * NOTE : multicast_forward is set only if this packet
22991 		 * originated from ip_wput. For packets originating from
22992 		 * ip_wput_multicast, it is not set.
22993 		 */
22994 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22995 multi_loopback:
22996 			ip2dbg(("ip_wput: multicast, loop %d\n",
22997 			    conn_multicast_loop));
22998 
22999 			/*  Forget header checksum offload */
23000 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23001 
23002 			/*
23003 			 * Local loopback of multicasts?  Check the
23004 			 * ill.
23005 			 *
23006 			 * Note that the loopback function will not come
23007 			 * in through ip_rput - it will only do the
23008 			 * client fanout thus we need to do an mforward
23009 			 * as well.  The is different from the BSD
23010 			 * logic.
23011 			 */
23012 			if (ill != NULL) {
23013 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
23014 				    ALL_ZONES) != NULL) {
23015 					/*
23016 					 * Pass along the virtual output q.
23017 					 * ip_wput_local() will distribute the
23018 					 * packet to all the matching zones,
23019 					 * except the sending zone when
23020 					 * IP_MULTICAST_LOOP is false.
23021 					 */
23022 					ip_multicast_loopback(q, ill, first_mp,
23023 					    conn_multicast_loop ? 0 :
23024 					    IP_FF_NO_MCAST_LOOP, zoneid);
23025 				}
23026 			}
23027 			if (ipha->ipha_ttl == 0) {
23028 				/*
23029 				 * 0 => only to this host i.e. we are
23030 				 * done. We are also done if this was the
23031 				 * loopback interface since it is sufficient
23032 				 * to loopback one copy of a multicast packet.
23033 				 */
23034 				freemsg(first_mp);
23035 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23036 				    "ip_wput_ire_end: q %p (%S)",
23037 				    q, "loopback");
23038 				ire_refrele(ire);
23039 				if (conn_outgoing_ill != NULL)
23040 					ill_refrele(conn_outgoing_ill);
23041 				return;
23042 			}
23043 			/*
23044 			 * ILLF_MULTICAST is checked in ip_newroute
23045 			 * i.e. we don't need to check it here since
23046 			 * all IRE_CACHEs come from ip_newroute.
23047 			 * For multicast traffic, SO_DONTROUTE is interpreted
23048 			 * to mean only send the packet out the interface
23049 			 * (optionally specified with IP_MULTICAST_IF)
23050 			 * and do not forward it out additional interfaces.
23051 			 * RSVP and the rsvp daemon is an example of a
23052 			 * protocol and user level process that
23053 			 * handles it's own routing. Hence, it uses the
23054 			 * SO_DONTROUTE option to accomplish this.
23055 			 */
23056 
23057 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23058 			    ill != NULL) {
23059 				/* Unconditionally redo the checksum */
23060 				ipha->ipha_hdr_checksum = 0;
23061 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23062 
23063 				/*
23064 				 * If this needs to go out secure, we need
23065 				 * to wait till we finish the IPsec
23066 				 * processing.
23067 				 */
23068 				if (ipsec_len == 0 &&
23069 				    ip_mforward(ill, ipha, mp)) {
23070 					freemsg(first_mp);
23071 					ip1dbg(("ip_wput: mforward failed\n"));
23072 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23073 					    "ip_wput_ire_end: q %p (%S)",
23074 					    q, "mforward failed");
23075 					ire_refrele(ire);
23076 					if (conn_outgoing_ill != NULL)
23077 						ill_refrele(conn_outgoing_ill);
23078 					return;
23079 				}
23080 			}
23081 		}
23082 		max_frag = ire->ire_max_frag;
23083 		cksum += ttl_protocol;
23084 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23085 			/* No fragmentation required for this one. */
23086 			/*
23087 			 * Don't use frag_flag if packet is pre-built or source
23088 			 * routed or if multicast (since multicast packets do
23089 			 * not solicit ICMP "packet too big" messages).
23090 			 */
23091 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23092 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23093 			    !ip_source_route_included(ipha)) &&
23094 			    !CLASSD(ipha->ipha_dst))
23095 				ipha->ipha_fragment_offset_and_flags |=
23096 				    htons(ire->ire_frag_flag);
23097 
23098 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23099 				/* Complete the IP header checksum. */
23100 				cksum += ipha->ipha_ident;
23101 				cksum += (v_hlen_tos_len >> 16)+
23102 				    (v_hlen_tos_len & 0xFFFF);
23103 				cksum += ipha->ipha_fragment_offset_and_flags;
23104 				hlen = (V_HLEN & 0xF) -
23105 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23106 				if (hlen) {
23107 checksumoptions:
23108 					/*
23109 					 * Account for the IP Options in the IP
23110 					 * header checksum.
23111 					 */
23112 					up = (uint16_t *)(rptr+
23113 					    IP_SIMPLE_HDR_LENGTH);
23114 					do {
23115 						cksum += up[0];
23116 						cksum += up[1];
23117 						up += 2;
23118 					} while (--hlen);
23119 				}
23120 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23121 				cksum = ~(cksum + (cksum >> 16));
23122 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23123 			}
23124 			if (ipsec_len != 0) {
23125 				ipsec_out_process(q, first_mp, ire, ill_index);
23126 				if (!next_mp) {
23127 					ire_refrele(ire);
23128 					if (conn_outgoing_ill != NULL)
23129 						ill_refrele(conn_outgoing_ill);
23130 					return;
23131 				}
23132 				goto next;
23133 			}
23134 
23135 			/*
23136 			 * multirt_send has already been handled
23137 			 * for broadcast, but not yet for multicast
23138 			 * or IP options.
23139 			 */
23140 			if (next_mp == NULL) {
23141 				if (ire->ire_flags & RTF_MULTIRT) {
23142 					multirt_send = B_TRUE;
23143 				}
23144 			}
23145 
23146 			/*
23147 			 * In most cases, the emission loop below is
23148 			 * entered only once. Only in the case where
23149 			 * the ire holds the RTF_MULTIRT flag, do we loop
23150 			 * to process all RTF_MULTIRT ires in the bucket,
23151 			 * and send the packet through all crossed
23152 			 * RTF_MULTIRT routes.
23153 			 */
23154 			do {
23155 				if (multirt_send) {
23156 					irb_t *irb;
23157 
23158 					irb = ire->ire_bucket;
23159 					ASSERT(irb != NULL);
23160 					/*
23161 					 * We are in a multiple send case,
23162 					 * need to get the next IRE and make
23163 					 * a duplicate of the packet.
23164 					 */
23165 					IRB_REFHOLD(irb);
23166 					for (ire1 = ire->ire_next;
23167 					    ire1 != NULL;
23168 					    ire1 = ire1->ire_next) {
23169 						if (!(ire1->ire_flags &
23170 						    RTF_MULTIRT))
23171 							continue;
23172 
23173 						if (ire1->ire_addr !=
23174 						    ire->ire_addr)
23175 							continue;
23176 
23177 						if (ire1->ire_marks &
23178 						    (IRE_MARK_CONDEMNED |
23179 						    IRE_MARK_TESTHIDDEN))
23180 							continue;
23181 
23182 						/* Got one */
23183 						IRE_REFHOLD(ire1);
23184 						break;
23185 					}
23186 					IRB_REFRELE(irb);
23187 
23188 					if (ire1 != NULL) {
23189 						next_mp = copyb(mp);
23190 						if ((next_mp == NULL) ||
23191 						    ((mp->b_cont != NULL) &&
23192 						    ((next_mp->b_cont =
23193 						    dupmsg(mp->b_cont))
23194 						    == NULL))) {
23195 							freemsg(next_mp);
23196 							next_mp = NULL;
23197 							ire_refrele(ire1);
23198 							ire1 = NULL;
23199 						}
23200 					}
23201 
23202 					/*
23203 					 * Last multiroute ire; don't loop
23204 					 * anymore. The emission is over
23205 					 * and next_mp is NULL.
23206 					 */
23207 					if (ire1 == NULL) {
23208 						multirt_send = B_FALSE;
23209 					}
23210 				}
23211 
23212 				out_ill = ire_to_ill(ire);
23213 				DTRACE_PROBE4(ip4__physical__out__start,
23214 				    ill_t *, NULL,
23215 				    ill_t *, out_ill,
23216 				    ipha_t *, ipha, mblk_t *, mp);
23217 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23218 				    ipst->ips_ipv4firewall_physical_out,
23219 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23220 				DTRACE_PROBE1(ip4__physical__out__end,
23221 				    mblk_t *, mp);
23222 				if (mp == NULL)
23223 					goto release_ire_and_ill_2;
23224 
23225 				ASSERT(ipsec_len == 0);
23226 				mp->b_prev =
23227 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23228 				DTRACE_PROBE2(ip__xmit__2,
23229 				    mblk_t *, mp, ire_t *, ire);
23230 				pktxmit_state = ip_xmit_v4(mp, ire,
23231 				    NULL, B_TRUE, connp);
23232 				if ((pktxmit_state == SEND_FAILED) ||
23233 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23234 release_ire_and_ill_2:
23235 					if (next_mp) {
23236 						freemsg(next_mp);
23237 						ire_refrele(ire1);
23238 					}
23239 					ire_refrele(ire);
23240 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23241 					    "ip_wput_ire_end: q %p (%S)",
23242 					    q, "discard MDATA");
23243 					if (conn_outgoing_ill != NULL)
23244 						ill_refrele(conn_outgoing_ill);
23245 					return;
23246 				}
23247 
23248 				if (CLASSD(dst)) {
23249 					BUMP_MIB(out_ill->ill_ip_mib,
23250 					    ipIfStatsHCOutMcastPkts);
23251 					UPDATE_MIB(out_ill->ill_ip_mib,
23252 					    ipIfStatsHCOutMcastOctets,
23253 					    LENGTH);
23254 				} else if (ire->ire_type == IRE_BROADCAST) {
23255 					BUMP_MIB(out_ill->ill_ip_mib,
23256 					    ipIfStatsHCOutBcastPkts);
23257 				}
23258 
23259 				if (multirt_send) {
23260 					/*
23261 					 * We are in a multiple send case,
23262 					 * need to re-enter the sending loop
23263 					 * using the next ire.
23264 					 */
23265 					ire_refrele(ire);
23266 					ire = ire1;
23267 					stq = ire->ire_stq;
23268 					mp = next_mp;
23269 					next_mp = NULL;
23270 					ipha = (ipha_t *)mp->b_rptr;
23271 					ill_index = Q_TO_INDEX(stq);
23272 				}
23273 			} while (multirt_send);
23274 
23275 			if (!next_mp) {
23276 				/*
23277 				 * Last copy going out (the ultra-common
23278 				 * case).  Note that we intentionally replicate
23279 				 * the putnext rather than calling it before
23280 				 * the next_mp check in hopes of a little
23281 				 * tail-call action out of the compiler.
23282 				 */
23283 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23284 				    "ip_wput_ire_end: q %p (%S)",
23285 				    q, "last copy out(1)");
23286 				ire_refrele(ire);
23287 				if (conn_outgoing_ill != NULL)
23288 					ill_refrele(conn_outgoing_ill);
23289 				return;
23290 			}
23291 			/* More copies going out below. */
23292 		} else {
23293 			int offset;
23294 fragmentit:
23295 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23296 			/*
23297 			 * If this would generate a icmp_frag_needed message,
23298 			 * we need to handle it before we do the IPsec
23299 			 * processing. Otherwise, we need to strip the IPsec
23300 			 * headers before we send up the message to the ULPs
23301 			 * which becomes messy and difficult.
23302 			 */
23303 			if (ipsec_len != 0) {
23304 				if ((max_frag < (unsigned int)(LENGTH +
23305 				    ipsec_len)) && (offset & IPH_DF)) {
23306 					out_ill = (ill_t *)stq->q_ptr;
23307 					BUMP_MIB(out_ill->ill_ip_mib,
23308 					    ipIfStatsOutFragFails);
23309 					BUMP_MIB(out_ill->ill_ip_mib,
23310 					    ipIfStatsOutFragReqds);
23311 					ipha->ipha_hdr_checksum = 0;
23312 					ipha->ipha_hdr_checksum =
23313 					    (uint16_t)ip_csum_hdr(ipha);
23314 					icmp_frag_needed(ire->ire_stq, first_mp,
23315 					    max_frag, zoneid, ipst);
23316 					if (!next_mp) {
23317 						ire_refrele(ire);
23318 						if (conn_outgoing_ill != NULL) {
23319 							ill_refrele(
23320 							    conn_outgoing_ill);
23321 						}
23322 						return;
23323 					}
23324 				} else {
23325 					/*
23326 					 * This won't cause a icmp_frag_needed
23327 					 * message. to be generated. Send it on
23328 					 * the wire. Note that this could still
23329 					 * cause fragmentation and all we
23330 					 * do is the generation of the message
23331 					 * to the ULP if needed before IPsec.
23332 					 */
23333 					if (!next_mp) {
23334 						ipsec_out_process(q, first_mp,
23335 						    ire, ill_index);
23336 						TRACE_2(TR_FAC_IP,
23337 						    TR_IP_WPUT_IRE_END,
23338 						    "ip_wput_ire_end: q %p "
23339 						    "(%S)", q,
23340 						    "last ipsec_out_process");
23341 						ire_refrele(ire);
23342 						if (conn_outgoing_ill != NULL) {
23343 							ill_refrele(
23344 							    conn_outgoing_ill);
23345 						}
23346 						return;
23347 					}
23348 					ipsec_out_process(q, first_mp,
23349 					    ire, ill_index);
23350 				}
23351 			} else {
23352 				/*
23353 				 * Initiate IPPF processing. For
23354 				 * fragmentable packets we finish
23355 				 * all QOS packet processing before
23356 				 * calling:
23357 				 * ip_wput_ire_fragmentit->ip_wput_frag
23358 				 */
23359 
23360 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23361 					ip_process(IPP_LOCAL_OUT, &mp,
23362 					    ill_index);
23363 					if (mp == NULL) {
23364 						out_ill = (ill_t *)stq->q_ptr;
23365 						BUMP_MIB(out_ill->ill_ip_mib,
23366 						    ipIfStatsOutDiscards);
23367 						if (next_mp != NULL) {
23368 							freemsg(next_mp);
23369 							ire_refrele(ire1);
23370 						}
23371 						ire_refrele(ire);
23372 						TRACE_2(TR_FAC_IP,
23373 						    TR_IP_WPUT_IRE_END,
23374 						    "ip_wput_ire: q %p (%S)",
23375 						    q, "discard MDATA");
23376 						if (conn_outgoing_ill != NULL) {
23377 							ill_refrele(
23378 							    conn_outgoing_ill);
23379 						}
23380 						return;
23381 					}
23382 				}
23383 				if (!next_mp) {
23384 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23385 					    "ip_wput_ire_end: q %p (%S)",
23386 					    q, "last fragmentation");
23387 					ip_wput_ire_fragmentit(mp, ire,
23388 					    zoneid, ipst, connp);
23389 					ire_refrele(ire);
23390 					if (conn_outgoing_ill != NULL)
23391 						ill_refrele(conn_outgoing_ill);
23392 					return;
23393 				}
23394 				ip_wput_ire_fragmentit(mp, ire,
23395 				    zoneid, ipst, connp);
23396 			}
23397 		}
23398 	} else {
23399 nullstq:
23400 		/* A NULL stq means the destination address is local. */
23401 		UPDATE_OB_PKT_COUNT(ire);
23402 		ire->ire_last_used_time = lbolt;
23403 		ASSERT(ire->ire_ipif != NULL);
23404 		if (!next_mp) {
23405 			/*
23406 			 * Is there an "in" and "out" for traffic local
23407 			 * to a host (loopback)?  The code in Solaris doesn't
23408 			 * explicitly draw a line in its code for in vs out,
23409 			 * so we've had to draw a line in the sand: ip_wput_ire
23410 			 * is considered to be the "output" side and
23411 			 * ip_wput_local to be the "input" side.
23412 			 */
23413 			out_ill = ire_to_ill(ire);
23414 
23415 			/*
23416 			 * DTrace this as ip:::send.  A blocked packet will
23417 			 * fire the send probe, but not the receive probe.
23418 			 */
23419 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23420 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23421 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23422 
23423 			DTRACE_PROBE4(ip4__loopback__out__start,
23424 			    ill_t *, NULL, ill_t *, out_ill,
23425 			    ipha_t *, ipha, mblk_t *, first_mp);
23426 
23427 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23428 			    ipst->ips_ipv4firewall_loopback_out,
23429 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23430 
23431 			DTRACE_PROBE1(ip4__loopback__out_end,
23432 			    mblk_t *, first_mp);
23433 
23434 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23435 			    "ip_wput_ire_end: q %p (%S)",
23436 			    q, "local address");
23437 
23438 			if (first_mp != NULL)
23439 				ip_wput_local(q, out_ill, ipha,
23440 				    first_mp, ire, 0, ire->ire_zoneid);
23441 			ire_refrele(ire);
23442 			if (conn_outgoing_ill != NULL)
23443 				ill_refrele(conn_outgoing_ill);
23444 			return;
23445 		}
23446 
23447 		out_ill = ire_to_ill(ire);
23448 
23449 		/*
23450 		 * DTrace this as ip:::send.  A blocked packet will fire the
23451 		 * send probe, but not the receive probe.
23452 		 */
23453 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23454 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23455 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23456 
23457 		DTRACE_PROBE4(ip4__loopback__out__start,
23458 		    ill_t *, NULL, ill_t *, out_ill,
23459 		    ipha_t *, ipha, mblk_t *, first_mp);
23460 
23461 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23462 		    ipst->ips_ipv4firewall_loopback_out,
23463 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23464 
23465 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23466 
23467 		if (first_mp != NULL)
23468 			ip_wput_local(q, out_ill, ipha,
23469 			    first_mp, ire, 0, ire->ire_zoneid);
23470 	}
23471 next:
23472 	/*
23473 	 * More copies going out to additional interfaces.
23474 	 * ire1 has already been held. We don't need the
23475 	 * "ire" anymore.
23476 	 */
23477 	ire_refrele(ire);
23478 	ire = ire1;
23479 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23480 	mp = next_mp;
23481 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23482 	ill = ire_to_ill(ire);
23483 	first_mp = mp;
23484 	if (ipsec_len != 0) {
23485 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23486 		mp = mp->b_cont;
23487 	}
23488 	dst = ire->ire_addr;
23489 	ipha = (ipha_t *)mp->b_rptr;
23490 	/*
23491 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23492 	 * Restore ipha_ident "no checksum" flag.
23493 	 */
23494 	src = orig_src;
23495 	ipha->ipha_ident = ip_hdr_included;
23496 	goto another;
23497 
23498 #undef	rptr
23499 #undef	Q_TO_INDEX
23500 }
23501 
23502 /*
23503  * Routine to allocate a message that is used to notify the ULP about MDT.
23504  * The caller may provide a pointer to the link-layer MDT capabilities,
23505  * or NULL if MDT is to be disabled on the stream.
23506  */
23507 mblk_t *
23508 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23509 {
23510 	mblk_t *mp;
23511 	ip_mdt_info_t *mdti;
23512 	ill_mdt_capab_t *idst;
23513 
23514 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23515 		DB_TYPE(mp) = M_CTL;
23516 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23517 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23518 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23519 		idst = &(mdti->mdt_capab);
23520 
23521 		/*
23522 		 * If the caller provides us with the capability, copy
23523 		 * it over into our notification message; otherwise
23524 		 * we zero out the capability portion.
23525 		 */
23526 		if (isrc != NULL)
23527 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23528 		else
23529 			bzero((caddr_t)idst, sizeof (*idst));
23530 	}
23531 	return (mp);
23532 }
23533 
23534 /*
23535  * Routine which determines whether MDT can be enabled on the destination
23536  * IRE and IPC combination, and if so, allocates and returns the MDT
23537  * notification mblk that may be used by ULP.  We also check if we need to
23538  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23539  * MDT usage in the past have been lifted.  This gets called during IP
23540  * and ULP binding.
23541  */
23542 mblk_t *
23543 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23544     ill_mdt_capab_t *mdt_cap)
23545 {
23546 	mblk_t *mp;
23547 	boolean_t rc = B_FALSE;
23548 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23549 
23550 	ASSERT(dst_ire != NULL);
23551 	ASSERT(connp != NULL);
23552 	ASSERT(mdt_cap != NULL);
23553 
23554 	/*
23555 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23556 	 * Multidata, which is handled in tcp_multisend().  This
23557 	 * is the reason why we do all these checks here, to ensure
23558 	 * that we don't enable Multidata for the cases which we
23559 	 * can't handle at the moment.
23560 	 */
23561 	do {
23562 		/* Only do TCP at the moment */
23563 		if (connp->conn_ulp != IPPROTO_TCP)
23564 			break;
23565 
23566 		/*
23567 		 * IPsec outbound policy present?  Note that we get here
23568 		 * after calling ipsec_conn_cache_policy() where the global
23569 		 * policy checking is performed.  conn_latch will be
23570 		 * non-NULL as long as there's a policy defined,
23571 		 * i.e. conn_out_enforce_policy may be NULL in such case
23572 		 * when the connection is non-secure, and hence we check
23573 		 * further if the latch refers to an outbound policy.
23574 		 */
23575 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23576 			break;
23577 
23578 		/* CGTP (multiroute) is enabled? */
23579 		if (dst_ire->ire_flags & RTF_MULTIRT)
23580 			break;
23581 
23582 		/* Outbound IPQoS enabled? */
23583 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23584 			/*
23585 			 * In this case, we disable MDT for this and all
23586 			 * future connections going over the interface.
23587 			 */
23588 			mdt_cap->ill_mdt_on = 0;
23589 			break;
23590 		}
23591 
23592 		/* socket option(s) present? */
23593 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23594 			break;
23595 
23596 		rc = B_TRUE;
23597 	/* CONSTCOND */
23598 	} while (0);
23599 
23600 	/* Remember the result */
23601 	connp->conn_mdt_ok = rc;
23602 
23603 	if (!rc)
23604 		return (NULL);
23605 	else if (!mdt_cap->ill_mdt_on) {
23606 		/*
23607 		 * If MDT has been previously turned off in the past, and we
23608 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23609 		 * then enable it for this interface.
23610 		 */
23611 		mdt_cap->ill_mdt_on = 1;
23612 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23613 		    "interface %s\n", ill_name));
23614 	}
23615 
23616 	/* Allocate the MDT info mblk */
23617 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23618 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23619 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23620 		return (NULL);
23621 	}
23622 	return (mp);
23623 }
23624 
23625 /*
23626  * Routine to allocate a message that is used to notify the ULP about LSO.
23627  * The caller may provide a pointer to the link-layer LSO capabilities,
23628  * or NULL if LSO is to be disabled on the stream.
23629  */
23630 mblk_t *
23631 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23632 {
23633 	mblk_t *mp;
23634 	ip_lso_info_t *lsoi;
23635 	ill_lso_capab_t *idst;
23636 
23637 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23638 		DB_TYPE(mp) = M_CTL;
23639 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23640 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23641 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23642 		idst = &(lsoi->lso_capab);
23643 
23644 		/*
23645 		 * If the caller provides us with the capability, copy
23646 		 * it over into our notification message; otherwise
23647 		 * we zero out the capability portion.
23648 		 */
23649 		if (isrc != NULL)
23650 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23651 		else
23652 			bzero((caddr_t)idst, sizeof (*idst));
23653 	}
23654 	return (mp);
23655 }
23656 
23657 /*
23658  * Routine which determines whether LSO can be enabled on the destination
23659  * IRE and IPC combination, and if so, allocates and returns the LSO
23660  * notification mblk that may be used by ULP.  We also check if we need to
23661  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23662  * LSO usage in the past have been lifted.  This gets called during IP
23663  * and ULP binding.
23664  */
23665 mblk_t *
23666 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23667     ill_lso_capab_t *lso_cap)
23668 {
23669 	mblk_t *mp;
23670 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23671 
23672 	ASSERT(dst_ire != NULL);
23673 	ASSERT(connp != NULL);
23674 	ASSERT(lso_cap != NULL);
23675 
23676 	connp->conn_lso_ok = B_TRUE;
23677 
23678 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23679 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23680 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23681 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23682 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23683 		connp->conn_lso_ok = B_FALSE;
23684 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23685 			/*
23686 			 * Disable LSO for this and all future connections going
23687 			 * over the interface.
23688 			 */
23689 			lso_cap->ill_lso_on = 0;
23690 		}
23691 	}
23692 
23693 	if (!connp->conn_lso_ok)
23694 		return (NULL);
23695 	else if (!lso_cap->ill_lso_on) {
23696 		/*
23697 		 * If LSO has been previously turned off in the past, and we
23698 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23699 		 * then enable it for this interface.
23700 		 */
23701 		lso_cap->ill_lso_on = 1;
23702 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23703 		    ill_name));
23704 	}
23705 
23706 	/* Allocate the LSO info mblk */
23707 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23708 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23709 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23710 
23711 	return (mp);
23712 }
23713 
23714 /*
23715  * Create destination address attribute, and fill it with the physical
23716  * destination address and SAP taken from the template DL_UNITDATA_REQ
23717  * message block.
23718  */
23719 boolean_t
23720 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23721 {
23722 	dl_unitdata_req_t *dlurp;
23723 	pattr_t *pa;
23724 	pattrinfo_t pa_info;
23725 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23726 	uint_t das_len, das_off;
23727 
23728 	ASSERT(dlmp != NULL);
23729 
23730 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23731 	das_len = dlurp->dl_dest_addr_length;
23732 	das_off = dlurp->dl_dest_addr_offset;
23733 
23734 	pa_info.type = PATTR_DSTADDRSAP;
23735 	pa_info.len = sizeof (**das) + das_len - 1;
23736 
23737 	/* create and associate the attribute */
23738 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23739 	if (pa != NULL) {
23740 		ASSERT(*das != NULL);
23741 		(*das)->addr_is_group = 0;
23742 		(*das)->addr_len = (uint8_t)das_len;
23743 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23744 	}
23745 
23746 	return (pa != NULL);
23747 }
23748 
23749 /*
23750  * Create hardware checksum attribute and fill it with the values passed.
23751  */
23752 boolean_t
23753 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23754     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23755 {
23756 	pattr_t *pa;
23757 	pattrinfo_t pa_info;
23758 
23759 	ASSERT(mmd != NULL);
23760 
23761 	pa_info.type = PATTR_HCKSUM;
23762 	pa_info.len = sizeof (pattr_hcksum_t);
23763 
23764 	/* create and associate the attribute */
23765 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23766 	if (pa != NULL) {
23767 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23768 
23769 		hck->hcksum_start_offset = start_offset;
23770 		hck->hcksum_stuff_offset = stuff_offset;
23771 		hck->hcksum_end_offset = end_offset;
23772 		hck->hcksum_flags = flags;
23773 	}
23774 	return (pa != NULL);
23775 }
23776 
23777 /*
23778  * Create zerocopy attribute and fill it with the specified flags
23779  */
23780 boolean_t
23781 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23782 {
23783 	pattr_t *pa;
23784 	pattrinfo_t pa_info;
23785 
23786 	ASSERT(mmd != NULL);
23787 	pa_info.type = PATTR_ZCOPY;
23788 	pa_info.len = sizeof (pattr_zcopy_t);
23789 
23790 	/* create and associate the attribute */
23791 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23792 	if (pa != NULL) {
23793 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23794 
23795 		zcopy->zcopy_flags = flags;
23796 	}
23797 	return (pa != NULL);
23798 }
23799 
23800 /*
23801  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23802  * block chain. We could rewrite to handle arbitrary message block chains but
23803  * that would make the code complicated and slow. Right now there three
23804  * restrictions:
23805  *
23806  *   1. The first message block must contain the complete IP header and
23807  *	at least 1 byte of payload data.
23808  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23809  *	so that we can use a single Multidata message.
23810  *   3. No frag must be distributed over two or more message blocks so
23811  *	that we don't need more than two packet descriptors per frag.
23812  *
23813  * The above restrictions allow us to support userland applications (which
23814  * will send down a single message block) and NFS over UDP (which will
23815  * send down a chain of at most three message blocks).
23816  *
23817  * We also don't use MDT for payloads with less than or equal to
23818  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23819  */
23820 boolean_t
23821 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23822 {
23823 	int	blocks;
23824 	ssize_t	total, missing, size;
23825 
23826 	ASSERT(mp != NULL);
23827 	ASSERT(hdr_len > 0);
23828 
23829 	size = MBLKL(mp) - hdr_len;
23830 	if (size <= 0)
23831 		return (B_FALSE);
23832 
23833 	/* The first mblk contains the header and some payload. */
23834 	blocks = 1;
23835 	total = size;
23836 	size %= len;
23837 	missing = (size == 0) ? 0 : (len - size);
23838 	mp = mp->b_cont;
23839 
23840 	while (mp != NULL) {
23841 		/*
23842 		 * Give up if we encounter a zero length message block.
23843 		 * In practice, this should rarely happen and therefore
23844 		 * not worth the trouble of freeing and re-linking the
23845 		 * mblk from the chain to handle such case.
23846 		 */
23847 		if ((size = MBLKL(mp)) == 0)
23848 			return (B_FALSE);
23849 
23850 		/* Too many payload buffers for a single Multidata message? */
23851 		if (++blocks > MULTIDATA_MAX_PBUFS)
23852 			return (B_FALSE);
23853 
23854 		total += size;
23855 		/* Is a frag distributed over two or more message blocks? */
23856 		if (missing > size)
23857 			return (B_FALSE);
23858 		size -= missing;
23859 
23860 		size %= len;
23861 		missing = (size == 0) ? 0 : (len - size);
23862 
23863 		mp = mp->b_cont;
23864 	}
23865 
23866 	return (total > ip_wput_frag_mdt_min);
23867 }
23868 
23869 /*
23870  * Outbound IPv4 fragmentation routine using MDT.
23871  */
23872 static void
23873 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23874     uint32_t frag_flag, int offset)
23875 {
23876 	ipha_t		*ipha_orig;
23877 	int		i1, ip_data_end;
23878 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23879 	mblk_t		*hdr_mp, *md_mp = NULL;
23880 	unsigned char	*hdr_ptr, *pld_ptr;
23881 	multidata_t	*mmd;
23882 	ip_pdescinfo_t	pdi;
23883 	ill_t		*ill;
23884 	ip_stack_t	*ipst = ire->ire_ipst;
23885 
23886 	ASSERT(DB_TYPE(mp) == M_DATA);
23887 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23888 
23889 	ill = ire_to_ill(ire);
23890 	ASSERT(ill != NULL);
23891 
23892 	ipha_orig = (ipha_t *)mp->b_rptr;
23893 	mp->b_rptr += sizeof (ipha_t);
23894 
23895 	/* Calculate how many packets we will send out */
23896 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23897 	pkts = (i1 + len - 1) / len;
23898 	ASSERT(pkts > 1);
23899 
23900 	/* Allocate a message block which will hold all the IP Headers. */
23901 	wroff = ipst->ips_ip_wroff_extra;
23902 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23903 
23904 	i1 = pkts * hdr_chunk_len;
23905 	/*
23906 	 * Create the header buffer, Multidata and destination address
23907 	 * and SAP attribute that should be associated with it.
23908 	 */
23909 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23910 	    ((hdr_mp->b_wptr += i1),
23911 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23912 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23913 		freemsg(mp);
23914 		if (md_mp == NULL) {
23915 			freemsg(hdr_mp);
23916 		} else {
23917 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23918 			freemsg(md_mp);
23919 		}
23920 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23921 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23922 		return;
23923 	}
23924 	IP_STAT(ipst, ip_frag_mdt_allocd);
23925 
23926 	/*
23927 	 * Add a payload buffer to the Multidata; this operation must not
23928 	 * fail, or otherwise our logic in this routine is broken.  There
23929 	 * is no memory allocation done by the routine, so any returned
23930 	 * failure simply tells us that we've done something wrong.
23931 	 *
23932 	 * A failure tells us that either we're adding the same payload
23933 	 * buffer more than once, or we're trying to add more buffers than
23934 	 * allowed.  None of the above cases should happen, and we panic
23935 	 * because either there's horrible heap corruption, and/or
23936 	 * programming mistake.
23937 	 */
23938 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23939 		goto pbuf_panic;
23940 
23941 	hdr_ptr = hdr_mp->b_rptr;
23942 	pld_ptr = mp->b_rptr;
23943 
23944 	/* Establish the ending byte offset, based on the starting offset. */
23945 	offset <<= 3;
23946 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23947 	    IP_SIMPLE_HDR_LENGTH;
23948 
23949 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23950 
23951 	while (pld_ptr < mp->b_wptr) {
23952 		ipha_t		*ipha;
23953 		uint16_t	offset_and_flags;
23954 		uint16_t	ip_len;
23955 		int		error;
23956 
23957 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23958 		ipha = (ipha_t *)(hdr_ptr + wroff);
23959 		ASSERT(OK_32PTR(ipha));
23960 		*ipha = *ipha_orig;
23961 
23962 		if (ip_data_end - offset > len) {
23963 			offset_and_flags = IPH_MF;
23964 		} else {
23965 			/*
23966 			 * Last frag. Set len to the length of this last piece.
23967 			 */
23968 			len = ip_data_end - offset;
23969 			/* A frag of a frag might have IPH_MF non-zero */
23970 			offset_and_flags =
23971 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23972 			    IPH_MF;
23973 		}
23974 		offset_and_flags |= (uint16_t)(offset >> 3);
23975 		offset_and_flags |= (uint16_t)frag_flag;
23976 		/* Store the offset and flags in the IP header. */
23977 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23978 
23979 		/* Store the length in the IP header. */
23980 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23981 		ipha->ipha_length = htons(ip_len);
23982 
23983 		/*
23984 		 * Set the IP header checksum.  Note that mp is just
23985 		 * the header, so this is easy to pass to ip_csum.
23986 		 */
23987 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23988 
23989 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
23990 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
23991 		    NULL, int, 0);
23992 
23993 		/*
23994 		 * Record offset and size of header and data of the next packet
23995 		 * in the multidata message.
23996 		 */
23997 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23998 		PDESC_PLD_INIT(&pdi);
23999 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24000 		ASSERT(i1 > 0);
24001 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24002 		if (i1 == len) {
24003 			pld_ptr += len;
24004 		} else {
24005 			i1 = len - i1;
24006 			mp = mp->b_cont;
24007 			ASSERT(mp != NULL);
24008 			ASSERT(MBLKL(mp) >= i1);
24009 			/*
24010 			 * Attach the next payload message block to the
24011 			 * multidata message.
24012 			 */
24013 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24014 				goto pbuf_panic;
24015 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24016 			pld_ptr = mp->b_rptr + i1;
24017 		}
24018 
24019 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24020 		    KM_NOSLEEP)) == NULL) {
24021 			/*
24022 			 * Any failure other than ENOMEM indicates that we
24023 			 * have passed in invalid pdesc info or parameters
24024 			 * to mmd_addpdesc, which must not happen.
24025 			 *
24026 			 * EINVAL is a result of failure on boundary checks
24027 			 * against the pdesc info contents.  It should not
24028 			 * happen, and we panic because either there's
24029 			 * horrible heap corruption, and/or programming
24030 			 * mistake.
24031 			 */
24032 			if (error != ENOMEM) {
24033 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24034 				    "pdesc logic error detected for "
24035 				    "mmd %p pinfo %p (%d)\n",
24036 				    (void *)mmd, (void *)&pdi, error);
24037 				/* NOTREACHED */
24038 			}
24039 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24040 			/* Free unattached payload message blocks as well */
24041 			md_mp->b_cont = mp->b_cont;
24042 			goto free_mmd;
24043 		}
24044 
24045 		/* Advance fragment offset. */
24046 		offset += len;
24047 
24048 		/* Advance to location for next header in the buffer. */
24049 		hdr_ptr += hdr_chunk_len;
24050 
24051 		/* Did we reach the next payload message block? */
24052 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24053 			mp = mp->b_cont;
24054 			/*
24055 			 * Attach the next message block with payload
24056 			 * data to the multidata message.
24057 			 */
24058 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24059 				goto pbuf_panic;
24060 			pld_ptr = mp->b_rptr;
24061 		}
24062 	}
24063 
24064 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24065 	ASSERT(mp->b_wptr == pld_ptr);
24066 
24067 	/* Update IP statistics */
24068 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24069 
24070 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24071 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24072 
24073 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24074 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24075 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24076 
24077 	if (pkt_type == OB_PKT) {
24078 		ire->ire_ob_pkt_count += pkts;
24079 		if (ire->ire_ipif != NULL)
24080 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24081 	} else {
24082 		/* The type is IB_PKT in the forwarding path. */
24083 		ire->ire_ib_pkt_count += pkts;
24084 		ASSERT(!IRE_IS_LOCAL(ire));
24085 		if (ire->ire_type & IRE_BROADCAST) {
24086 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24087 		} else {
24088 			UPDATE_MIB(ill->ill_ip_mib,
24089 			    ipIfStatsHCOutForwDatagrams, pkts);
24090 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24091 		}
24092 	}
24093 	ire->ire_last_used_time = lbolt;
24094 	/* Send it down */
24095 	putnext(ire->ire_stq, md_mp);
24096 	return;
24097 
24098 pbuf_panic:
24099 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24100 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24101 	    pbuf_idx);
24102 	/* NOTREACHED */
24103 }
24104 
24105 /*
24106  * Outbound IP fragmentation routine.
24107  *
24108  * NOTE : This routine does not ire_refrele the ire that is passed in
24109  * as the argument.
24110  */
24111 static void
24112 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24113     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24114 {
24115 	int		i1;
24116 	mblk_t		*ll_hdr_mp;
24117 	int 		ll_hdr_len;
24118 	int		hdr_len;
24119 	mblk_t		*hdr_mp;
24120 	ipha_t		*ipha;
24121 	int		ip_data_end;
24122 	int		len;
24123 	mblk_t		*mp = mp_orig, *mp1;
24124 	int		offset;
24125 	queue_t		*q;
24126 	uint32_t	v_hlen_tos_len;
24127 	mblk_t		*first_mp;
24128 	boolean_t	mctl_present;
24129 	ill_t		*ill;
24130 	ill_t		*out_ill;
24131 	mblk_t		*xmit_mp;
24132 	mblk_t		*carve_mp;
24133 	ire_t		*ire1 = NULL;
24134 	ire_t		*save_ire = NULL;
24135 	mblk_t  	*next_mp = NULL;
24136 	boolean_t	last_frag = B_FALSE;
24137 	boolean_t	multirt_send = B_FALSE;
24138 	ire_t		*first_ire = NULL;
24139 	irb_t		*irb = NULL;
24140 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24141 
24142 	ill = ire_to_ill(ire);
24143 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24144 
24145 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24146 
24147 	if (max_frag == 0) {
24148 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24149 		    " -  dropping packet\n"));
24150 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24151 		freemsg(mp);
24152 		return;
24153 	}
24154 
24155 	/*
24156 	 * IPsec does not allow hw accelerated packets to be fragmented
24157 	 * This check is made in ip_wput_ipsec_out prior to coming here
24158 	 * via ip_wput_ire_fragmentit.
24159 	 *
24160 	 * If at this point we have an ire whose ARP request has not
24161 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24162 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24163 	 * This packet and all fragmentable packets for this ire will
24164 	 * continue to get dropped while ire_nce->nce_state remains in
24165 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24166 	 * ND_REACHABLE, all subsquent large packets for this ire will
24167 	 * get fragemented and sent out by this function.
24168 	 */
24169 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24170 		/* If nce_state is ND_INITIAL, trigger ARP query */
24171 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24172 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24173 		    " -  dropping packet\n"));
24174 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24175 		freemsg(mp);
24176 		return;
24177 	}
24178 
24179 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24180 	    "ip_wput_frag_start:");
24181 
24182 	if (mp->b_datap->db_type == M_CTL) {
24183 		first_mp = mp;
24184 		mp_orig = mp = mp->b_cont;
24185 		mctl_present = B_TRUE;
24186 	} else {
24187 		first_mp = mp;
24188 		mctl_present = B_FALSE;
24189 	}
24190 
24191 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24192 	ipha = (ipha_t *)mp->b_rptr;
24193 
24194 	/*
24195 	 * If the Don't Fragment flag is on, generate an ICMP destination
24196 	 * unreachable, fragmentation needed.
24197 	 */
24198 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24199 	if (offset & IPH_DF) {
24200 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24201 		if (is_system_labeled()) {
24202 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24203 			    ire->ire_max_frag - max_frag, AF_INET);
24204 		}
24205 		/*
24206 		 * Need to compute hdr checksum if called from ip_wput_ire.
24207 		 * Note that ip_rput_forward verifies the checksum before
24208 		 * calling this routine so in that case this is a noop.
24209 		 */
24210 		ipha->ipha_hdr_checksum = 0;
24211 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24212 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24213 		    ipst);
24214 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24215 		    "ip_wput_frag_end:(%S)",
24216 		    "don't fragment");
24217 		return;
24218 	}
24219 	/*
24220 	 * Labeled systems adjust max_frag if they add a label
24221 	 * to send the correct path mtu.  We need the real mtu since we
24222 	 * are fragmenting the packet after label adjustment.
24223 	 */
24224 	if (is_system_labeled())
24225 		max_frag = ire->ire_max_frag;
24226 	if (mctl_present)
24227 		freeb(first_mp);
24228 	/*
24229 	 * Establish the starting offset.  May not be zero if we are fragging
24230 	 * a fragment that is being forwarded.
24231 	 */
24232 	offset = offset & IPH_OFFSET;
24233 
24234 	/* TODO why is this test needed? */
24235 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24236 	if (((max_frag - LENGTH) & ~7) < 8) {
24237 		/* TODO: notify ulp somehow */
24238 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24239 		freemsg(mp);
24240 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24241 		    "ip_wput_frag_end:(%S)",
24242 		    "len < 8");
24243 		return;
24244 	}
24245 
24246 	hdr_len = (V_HLEN & 0xF) << 2;
24247 
24248 	ipha->ipha_hdr_checksum = 0;
24249 
24250 	/*
24251 	 * Establish the number of bytes maximum per frag, after putting
24252 	 * in the header.
24253 	 */
24254 	len = (max_frag - hdr_len) & ~7;
24255 
24256 	/* Check if we can use MDT to send out the frags. */
24257 	ASSERT(!IRE_IS_LOCAL(ire));
24258 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24259 	    ipst->ips_ip_multidata_outbound &&
24260 	    !(ire->ire_flags & RTF_MULTIRT) &&
24261 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24262 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24263 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24264 		ASSERT(ill->ill_mdt_capab != NULL);
24265 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24266 			/*
24267 			 * If MDT has been previously turned off in the past,
24268 			 * and we currently can do MDT (due to IPQoS policy
24269 			 * removal, etc.) then enable it for this interface.
24270 			 */
24271 			ill->ill_mdt_capab->ill_mdt_on = 1;
24272 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24273 			    ill->ill_name));
24274 		}
24275 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24276 		    offset);
24277 		return;
24278 	}
24279 
24280 	/* Get a copy of the header for the trailing frags */
24281 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24282 	    mp);
24283 	if (!hdr_mp) {
24284 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24285 		freemsg(mp);
24286 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24287 		    "ip_wput_frag_end:(%S)",
24288 		    "couldn't copy hdr");
24289 		return;
24290 	}
24291 
24292 	/* Store the starting offset, with the MoreFrags flag. */
24293 	i1 = offset | IPH_MF | frag_flag;
24294 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24295 
24296 	/* Establish the ending byte offset, based on the starting offset. */
24297 	offset <<= 3;
24298 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24299 
24300 	/* Store the length of the first fragment in the IP header. */
24301 	i1 = len + hdr_len;
24302 	ASSERT(i1 <= IP_MAXPACKET);
24303 	ipha->ipha_length = htons((uint16_t)i1);
24304 
24305 	/*
24306 	 * Compute the IP header checksum for the first frag.  We have to
24307 	 * watch out that we stop at the end of the header.
24308 	 */
24309 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24310 
24311 	/*
24312 	 * Now carve off the first frag.  Note that this will include the
24313 	 * original IP header.
24314 	 */
24315 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24316 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24317 		freeb(hdr_mp);
24318 		freemsg(mp_orig);
24319 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24320 		    "ip_wput_frag_end:(%S)",
24321 		    "couldn't carve first");
24322 		return;
24323 	}
24324 
24325 	/*
24326 	 * Multirouting case. Each fragment is replicated
24327 	 * via all non-condemned RTF_MULTIRT routes
24328 	 * currently resolved.
24329 	 * We ensure that first_ire is the first RTF_MULTIRT
24330 	 * ire in the bucket.
24331 	 */
24332 	if (ire->ire_flags & RTF_MULTIRT) {
24333 		irb = ire->ire_bucket;
24334 		ASSERT(irb != NULL);
24335 
24336 		multirt_send = B_TRUE;
24337 
24338 		/* Make sure we do not omit any multiroute ire. */
24339 		IRB_REFHOLD(irb);
24340 		for (first_ire = irb->irb_ire;
24341 		    first_ire != NULL;
24342 		    first_ire = first_ire->ire_next) {
24343 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24344 			    (first_ire->ire_addr == ire->ire_addr) &&
24345 			    !(first_ire->ire_marks &
24346 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24347 				break;
24348 		}
24349 
24350 		if (first_ire != NULL) {
24351 			if (first_ire != ire) {
24352 				IRE_REFHOLD(first_ire);
24353 				/*
24354 				 * Do not release the ire passed in
24355 				 * as the argument.
24356 				 */
24357 				ire = first_ire;
24358 			} else {
24359 				first_ire = NULL;
24360 			}
24361 		}
24362 		IRB_REFRELE(irb);
24363 
24364 		/*
24365 		 * Save the first ire; we will need to restore it
24366 		 * for the trailing frags.
24367 		 * We REFHOLD save_ire, as each iterated ire will be
24368 		 * REFRELEd.
24369 		 */
24370 		save_ire = ire;
24371 		IRE_REFHOLD(save_ire);
24372 	}
24373 
24374 	/*
24375 	 * First fragment emission loop.
24376 	 * In most cases, the emission loop below is entered only
24377 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24378 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24379 	 * bucket, and send the fragment through all crossed
24380 	 * RTF_MULTIRT routes.
24381 	 */
24382 	do {
24383 		if (ire->ire_flags & RTF_MULTIRT) {
24384 			/*
24385 			 * We are in a multiple send case, need to get
24386 			 * the next ire and make a copy of the packet.
24387 			 * ire1 holds here the next ire to process in the
24388 			 * bucket. If multirouting is expected,
24389 			 * any non-RTF_MULTIRT ire that has the
24390 			 * right destination address is ignored.
24391 			 *
24392 			 * We have to take into account the MTU of
24393 			 * each walked ire. max_frag is set by the
24394 			 * the caller and generally refers to
24395 			 * the primary ire entry. Here we ensure that
24396 			 * no route with a lower MTU will be used, as
24397 			 * fragments are carved once for all ires,
24398 			 * then replicated.
24399 			 */
24400 			ASSERT(irb != NULL);
24401 			IRB_REFHOLD(irb);
24402 			for (ire1 = ire->ire_next;
24403 			    ire1 != NULL;
24404 			    ire1 = ire1->ire_next) {
24405 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24406 					continue;
24407 				if (ire1->ire_addr != ire->ire_addr)
24408 					continue;
24409 				if (ire1->ire_marks &
24410 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24411 					continue;
24412 				/*
24413 				 * Ensure we do not exceed the MTU
24414 				 * of the next route.
24415 				 */
24416 				if (ire1->ire_max_frag < max_frag) {
24417 					ip_multirt_bad_mtu(ire1, max_frag);
24418 					continue;
24419 				}
24420 
24421 				/* Got one. */
24422 				IRE_REFHOLD(ire1);
24423 				break;
24424 			}
24425 			IRB_REFRELE(irb);
24426 
24427 			if (ire1 != NULL) {
24428 				next_mp = copyb(mp);
24429 				if ((next_mp == NULL) ||
24430 				    ((mp->b_cont != NULL) &&
24431 				    ((next_mp->b_cont =
24432 				    dupmsg(mp->b_cont)) == NULL))) {
24433 					freemsg(next_mp);
24434 					next_mp = NULL;
24435 					ire_refrele(ire1);
24436 					ire1 = NULL;
24437 				}
24438 			}
24439 
24440 			/* Last multiroute ire; don't loop anymore. */
24441 			if (ire1 == NULL) {
24442 				multirt_send = B_FALSE;
24443 			}
24444 		}
24445 
24446 		ll_hdr_len = 0;
24447 		LOCK_IRE_FP_MP(ire);
24448 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24449 		if (ll_hdr_mp != NULL) {
24450 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24451 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24452 		} else {
24453 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24454 		}
24455 
24456 		/* If there is a transmit header, get a copy for this frag. */
24457 		/*
24458 		 * TODO: should check db_ref before calling ip_carve_mp since
24459 		 * it might give us a dup.
24460 		 */
24461 		if (!ll_hdr_mp) {
24462 			/* No xmit header. */
24463 			xmit_mp = mp;
24464 
24465 		/* We have a link-layer header that can fit in our mblk. */
24466 		} else if (mp->b_datap->db_ref == 1 &&
24467 		    ll_hdr_len != 0 &&
24468 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24469 			/* M_DATA fastpath */
24470 			mp->b_rptr -= ll_hdr_len;
24471 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24472 			xmit_mp = mp;
24473 
24474 		/* Corner case if copyb has failed */
24475 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24476 			UNLOCK_IRE_FP_MP(ire);
24477 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24478 			freeb(hdr_mp);
24479 			freemsg(mp);
24480 			freemsg(mp_orig);
24481 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24482 			    "ip_wput_frag_end:(%S)",
24483 			    "discard");
24484 
24485 			if (multirt_send) {
24486 				ASSERT(ire1);
24487 				ASSERT(next_mp);
24488 
24489 				freemsg(next_mp);
24490 				ire_refrele(ire1);
24491 			}
24492 			if (save_ire != NULL)
24493 				IRE_REFRELE(save_ire);
24494 
24495 			if (first_ire != NULL)
24496 				ire_refrele(first_ire);
24497 			return;
24498 
24499 		/*
24500 		 * Case of res_mp OR the fastpath mp can't fit
24501 		 * in the mblk
24502 		 */
24503 		} else {
24504 			xmit_mp->b_cont = mp;
24505 
24506 			/*
24507 			 * Get priority marking, if any.
24508 			 * We propagate the CoS marking from the
24509 			 * original packet that went to QoS processing
24510 			 * in ip_wput_ire to the newly carved mp.
24511 			 */
24512 			if (DB_TYPE(xmit_mp) == M_DATA)
24513 				xmit_mp->b_band = mp->b_band;
24514 		}
24515 		UNLOCK_IRE_FP_MP(ire);
24516 
24517 		q = ire->ire_stq;
24518 		out_ill = (ill_t *)q->q_ptr;
24519 
24520 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24521 
24522 		DTRACE_PROBE4(ip4__physical__out__start,
24523 		    ill_t *, NULL, ill_t *, out_ill,
24524 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24525 
24526 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24527 		    ipst->ips_ipv4firewall_physical_out,
24528 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24529 
24530 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24531 
24532 		if (xmit_mp != NULL) {
24533 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24534 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24535 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24536 
24537 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24538 
24539 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24540 			UPDATE_MIB(out_ill->ill_ip_mib,
24541 			    ipIfStatsHCOutOctets, i1);
24542 
24543 			if (pkt_type != OB_PKT) {
24544 				/*
24545 				 * Update the packet count and MIB stats
24546 				 * of trailing RTF_MULTIRT ires.
24547 				 */
24548 				UPDATE_OB_PKT_COUNT(ire);
24549 				BUMP_MIB(out_ill->ill_ip_mib,
24550 				    ipIfStatsOutFragReqds);
24551 			}
24552 		}
24553 
24554 		if (multirt_send) {
24555 			/*
24556 			 * We are in a multiple send case; look for
24557 			 * the next ire and re-enter the loop.
24558 			 */
24559 			ASSERT(ire1);
24560 			ASSERT(next_mp);
24561 			/* REFRELE the current ire before looping */
24562 			ire_refrele(ire);
24563 			ire = ire1;
24564 			ire1 = NULL;
24565 			mp = next_mp;
24566 			next_mp = NULL;
24567 		}
24568 	} while (multirt_send);
24569 
24570 	ASSERT(ire1 == NULL);
24571 
24572 	/* Restore the original ire; we need it for the trailing frags */
24573 	if (save_ire != NULL) {
24574 		/* REFRELE the last iterated ire */
24575 		ire_refrele(ire);
24576 		/* save_ire has been REFHOLDed */
24577 		ire = save_ire;
24578 		save_ire = NULL;
24579 		q = ire->ire_stq;
24580 	}
24581 
24582 	if (pkt_type == OB_PKT) {
24583 		UPDATE_OB_PKT_COUNT(ire);
24584 	} else {
24585 		out_ill = (ill_t *)q->q_ptr;
24586 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24587 		UPDATE_IB_PKT_COUNT(ire);
24588 	}
24589 
24590 	/* Advance the offset to the second frag starting point. */
24591 	offset += len;
24592 	/*
24593 	 * Update hdr_len from the copied header - there might be less options
24594 	 * in the later fragments.
24595 	 */
24596 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24597 	/* Loop until done. */
24598 	for (;;) {
24599 		uint16_t	offset_and_flags;
24600 		uint16_t	ip_len;
24601 
24602 		if (ip_data_end - offset > len) {
24603 			/*
24604 			 * Carve off the appropriate amount from the original
24605 			 * datagram.
24606 			 */
24607 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24608 				mp = NULL;
24609 				break;
24610 			}
24611 			/*
24612 			 * More frags after this one.  Get another copy
24613 			 * of the header.
24614 			 */
24615 			if (carve_mp->b_datap->db_ref == 1 &&
24616 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24617 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24618 				/* Inline IP header */
24619 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24620 				    hdr_mp->b_rptr;
24621 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24622 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24623 				mp = carve_mp;
24624 			} else {
24625 				if (!(mp = copyb(hdr_mp))) {
24626 					freemsg(carve_mp);
24627 					break;
24628 				}
24629 				/* Get priority marking, if any. */
24630 				mp->b_band = carve_mp->b_band;
24631 				mp->b_cont = carve_mp;
24632 			}
24633 			ipha = (ipha_t *)mp->b_rptr;
24634 			offset_and_flags = IPH_MF;
24635 		} else {
24636 			/*
24637 			 * Last frag.  Consume the header. Set len to
24638 			 * the length of this last piece.
24639 			 */
24640 			len = ip_data_end - offset;
24641 
24642 			/*
24643 			 * Carve off the appropriate amount from the original
24644 			 * datagram.
24645 			 */
24646 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24647 				mp = NULL;
24648 				break;
24649 			}
24650 			if (carve_mp->b_datap->db_ref == 1 &&
24651 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24652 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24653 				/* Inline IP header */
24654 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24655 				    hdr_mp->b_rptr;
24656 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24657 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24658 				mp = carve_mp;
24659 				freeb(hdr_mp);
24660 				hdr_mp = mp;
24661 			} else {
24662 				mp = hdr_mp;
24663 				/* Get priority marking, if any. */
24664 				mp->b_band = carve_mp->b_band;
24665 				mp->b_cont = carve_mp;
24666 			}
24667 			ipha = (ipha_t *)mp->b_rptr;
24668 			/* A frag of a frag might have IPH_MF non-zero */
24669 			offset_and_flags =
24670 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24671 			    IPH_MF;
24672 		}
24673 		offset_and_flags |= (uint16_t)(offset >> 3);
24674 		offset_and_flags |= (uint16_t)frag_flag;
24675 		/* Store the offset and flags in the IP header. */
24676 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24677 
24678 		/* Store the length in the IP header. */
24679 		ip_len = (uint16_t)(len + hdr_len);
24680 		ipha->ipha_length = htons(ip_len);
24681 
24682 		/*
24683 		 * Set the IP header checksum.	Note that mp is just
24684 		 * the header, so this is easy to pass to ip_csum.
24685 		 */
24686 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24687 
24688 		/* Attach a transmit header, if any, and ship it. */
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,
24694 			    ipIfStatsHCOutForwDatagrams);
24695 			UPDATE_IB_PKT_COUNT(ire);
24696 		}
24697 
24698 		if (ire->ire_flags & RTF_MULTIRT) {
24699 			irb = ire->ire_bucket;
24700 			ASSERT(irb != NULL);
24701 
24702 			multirt_send = B_TRUE;
24703 
24704 			/*
24705 			 * Save the original ire; we will need to restore it
24706 			 * for the tailing frags.
24707 			 */
24708 			save_ire = ire;
24709 			IRE_REFHOLD(save_ire);
24710 		}
24711 		/*
24712 		 * Emission loop for this fragment, similar
24713 		 * to what is done for the first fragment.
24714 		 */
24715 		do {
24716 			if (multirt_send) {
24717 				/*
24718 				 * We are in a multiple send case, need to get
24719 				 * the next ire and make a copy of the packet.
24720 				 */
24721 				ASSERT(irb != NULL);
24722 				IRB_REFHOLD(irb);
24723 				for (ire1 = ire->ire_next;
24724 				    ire1 != NULL;
24725 				    ire1 = ire1->ire_next) {
24726 					if (!(ire1->ire_flags & RTF_MULTIRT))
24727 						continue;
24728 					if (ire1->ire_addr != ire->ire_addr)
24729 						continue;
24730 					if (ire1->ire_marks &
24731 					    (IRE_MARK_CONDEMNED |
24732 					    IRE_MARK_TESTHIDDEN))
24733 						continue;
24734 					/*
24735 					 * Ensure we do not exceed the MTU
24736 					 * of the next route.
24737 					 */
24738 					if (ire1->ire_max_frag < max_frag) {
24739 						ip_multirt_bad_mtu(ire1,
24740 						    max_frag);
24741 						continue;
24742 					}
24743 
24744 					/* Got one. */
24745 					IRE_REFHOLD(ire1);
24746 					break;
24747 				}
24748 				IRB_REFRELE(irb);
24749 
24750 				if (ire1 != NULL) {
24751 					next_mp = copyb(mp);
24752 					if ((next_mp == NULL) ||
24753 					    ((mp->b_cont != NULL) &&
24754 					    ((next_mp->b_cont =
24755 					    dupmsg(mp->b_cont)) == NULL))) {
24756 						freemsg(next_mp);
24757 						next_mp = NULL;
24758 						ire_refrele(ire1);
24759 						ire1 = NULL;
24760 					}
24761 				}
24762 
24763 				/* Last multiroute ire; don't loop anymore. */
24764 				if (ire1 == NULL) {
24765 					multirt_send = B_FALSE;
24766 				}
24767 			}
24768 
24769 			/* Update transmit header */
24770 			ll_hdr_len = 0;
24771 			LOCK_IRE_FP_MP(ire);
24772 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24773 			if (ll_hdr_mp != NULL) {
24774 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24775 				ll_hdr_len = MBLKL(ll_hdr_mp);
24776 			} else {
24777 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24778 			}
24779 
24780 			if (!ll_hdr_mp) {
24781 				xmit_mp = mp;
24782 
24783 			/*
24784 			 * We have link-layer header that can fit in
24785 			 * our mblk.
24786 			 */
24787 			} else if (mp->b_datap->db_ref == 1 &&
24788 			    ll_hdr_len != 0 &&
24789 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24790 				/* M_DATA fastpath */
24791 				mp->b_rptr -= ll_hdr_len;
24792 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24793 				    ll_hdr_len);
24794 				xmit_mp = mp;
24795 
24796 			/*
24797 			 * Case of res_mp OR the fastpath mp can't fit
24798 			 * in the mblk
24799 			 */
24800 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24801 				xmit_mp->b_cont = mp;
24802 				/* Get priority marking, if any. */
24803 				if (DB_TYPE(xmit_mp) == M_DATA)
24804 					xmit_mp->b_band = mp->b_band;
24805 
24806 			/* Corner case if copyb failed */
24807 			} else {
24808 				/*
24809 				 * Exit both the replication and
24810 				 * fragmentation loops.
24811 				 */
24812 				UNLOCK_IRE_FP_MP(ire);
24813 				goto drop_pkt;
24814 			}
24815 			UNLOCK_IRE_FP_MP(ire);
24816 
24817 			mp1 = mp;
24818 			out_ill = (ill_t *)q->q_ptr;
24819 
24820 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24821 
24822 			DTRACE_PROBE4(ip4__physical__out__start,
24823 			    ill_t *, NULL, ill_t *, out_ill,
24824 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24825 
24826 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24827 			    ipst->ips_ipv4firewall_physical_out,
24828 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24829 
24830 			DTRACE_PROBE1(ip4__physical__out__end,
24831 			    mblk_t *, xmit_mp);
24832 
24833 			if (mp != mp1 && hdr_mp == mp1)
24834 				hdr_mp = mp;
24835 			if (mp != mp1 && mp_orig == mp1)
24836 				mp_orig = mp;
24837 
24838 			if (xmit_mp != NULL) {
24839 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24840 				    NULL, void_ip_t *, ipha,
24841 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24842 				    ipha, ip6_t *, NULL, int, 0);
24843 
24844 				ILL_SEND_TX(out_ill, ire, connp,
24845 				    xmit_mp, 0, connp);
24846 
24847 				BUMP_MIB(out_ill->ill_ip_mib,
24848 				    ipIfStatsHCOutTransmits);
24849 				UPDATE_MIB(out_ill->ill_ip_mib,
24850 				    ipIfStatsHCOutOctets, ip_len);
24851 
24852 				if (pkt_type != OB_PKT) {
24853 					/*
24854 					 * Update the packet count of trailing
24855 					 * RTF_MULTIRT ires.
24856 					 */
24857 					UPDATE_OB_PKT_COUNT(ire);
24858 				}
24859 			}
24860 
24861 			/* All done if we just consumed the hdr_mp. */
24862 			if (mp == hdr_mp) {
24863 				last_frag = B_TRUE;
24864 				BUMP_MIB(out_ill->ill_ip_mib,
24865 				    ipIfStatsOutFragOKs);
24866 			}
24867 
24868 			if (multirt_send) {
24869 				/*
24870 				 * We are in a multiple send case; look for
24871 				 * the next ire and re-enter the loop.
24872 				 */
24873 				ASSERT(ire1);
24874 				ASSERT(next_mp);
24875 				/* REFRELE the current ire before looping */
24876 				ire_refrele(ire);
24877 				ire = ire1;
24878 				ire1 = NULL;
24879 				q = ire->ire_stq;
24880 				mp = next_mp;
24881 				next_mp = NULL;
24882 			}
24883 		} while (multirt_send);
24884 		/*
24885 		 * Restore the original ire; we need it for the
24886 		 * trailing frags
24887 		 */
24888 		if (save_ire != NULL) {
24889 			ASSERT(ire1 == NULL);
24890 			/* REFRELE the last iterated ire */
24891 			ire_refrele(ire);
24892 			/* save_ire has been REFHOLDed */
24893 			ire = save_ire;
24894 			q = ire->ire_stq;
24895 			save_ire = NULL;
24896 		}
24897 
24898 		if (last_frag) {
24899 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24900 			    "ip_wput_frag_end:(%S)",
24901 			    "consumed hdr_mp");
24902 
24903 			if (first_ire != NULL)
24904 				ire_refrele(first_ire);
24905 			return;
24906 		}
24907 		/* Otherwise, advance and loop. */
24908 		offset += len;
24909 	}
24910 
24911 drop_pkt:
24912 	/* Clean up following allocation failure. */
24913 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24914 	freemsg(mp);
24915 	if (mp != hdr_mp)
24916 		freeb(hdr_mp);
24917 	if (mp != mp_orig)
24918 		freemsg(mp_orig);
24919 
24920 	if (save_ire != NULL)
24921 		IRE_REFRELE(save_ire);
24922 	if (first_ire != NULL)
24923 		ire_refrele(first_ire);
24924 
24925 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24926 	    "ip_wput_frag_end:(%S)",
24927 	    "end--alloc failure");
24928 }
24929 
24930 /*
24931  * Copy the header plus those options which have the copy bit set
24932  * src is the template to make sure we preserve the cred for TX purposes.
24933  */
24934 static mblk_t *
24935 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24936     mblk_t *src)
24937 {
24938 	mblk_t	*mp;
24939 	uchar_t	*up;
24940 
24941 	/*
24942 	 * Quick check if we need to look for options without the copy bit
24943 	 * set
24944 	 */
24945 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24946 	if (!mp)
24947 		return (mp);
24948 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24949 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24950 		bcopy(rptr, mp->b_rptr, hdr_len);
24951 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24952 		return (mp);
24953 	}
24954 	up  = mp->b_rptr;
24955 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24956 	up += IP_SIMPLE_HDR_LENGTH;
24957 	rptr += IP_SIMPLE_HDR_LENGTH;
24958 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24959 	while (hdr_len > 0) {
24960 		uint32_t optval;
24961 		uint32_t optlen;
24962 
24963 		optval = *rptr;
24964 		if (optval == IPOPT_EOL)
24965 			break;
24966 		if (optval == IPOPT_NOP)
24967 			optlen = 1;
24968 		else
24969 			optlen = rptr[1];
24970 		if (optval & IPOPT_COPY) {
24971 			bcopy(rptr, up, optlen);
24972 			up += optlen;
24973 		}
24974 		rptr += optlen;
24975 		hdr_len -= optlen;
24976 	}
24977 	/*
24978 	 * Make sure that we drop an even number of words by filling
24979 	 * with EOL to the next word boundary.
24980 	 */
24981 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24982 	    hdr_len & 0x3; hdr_len++)
24983 		*up++ = IPOPT_EOL;
24984 	mp->b_wptr = up;
24985 	/* Update header length */
24986 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24987 	return (mp);
24988 }
24989 
24990 /*
24991  * Delivery to local recipients including fanout to multiple recipients.
24992  * Does not do checksumming of UDP/TCP.
24993  * Note: q should be the read side queue for either the ill or conn.
24994  * Note: rq should be the read side q for the lower (ill) stream.
24995  * We don't send packets to IPPF processing, thus the last argument
24996  * to all the fanout calls are B_FALSE.
24997  */
24998 void
24999 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25000     int fanout_flags, zoneid_t zoneid)
25001 {
25002 	uint32_t	protocol;
25003 	mblk_t		*first_mp;
25004 	boolean_t	mctl_present;
25005 	int		ire_type;
25006 #define	rptr	((uchar_t *)ipha)
25007 	ip_stack_t	*ipst = ill->ill_ipst;
25008 
25009 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25010 	    "ip_wput_local_start: q %p", q);
25011 
25012 	if (ire != NULL) {
25013 		ire_type = ire->ire_type;
25014 	} else {
25015 		/*
25016 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25017 		 * packet is not multicast, we can't tell the ire type.
25018 		 */
25019 		ASSERT(CLASSD(ipha->ipha_dst));
25020 		ire_type = IRE_BROADCAST;
25021 	}
25022 
25023 	first_mp = mp;
25024 	if (first_mp->b_datap->db_type == M_CTL) {
25025 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25026 		if (!io->ipsec_out_secure) {
25027 			/*
25028 			 * This ipsec_out_t was allocated in ip_wput
25029 			 * for multicast packets to store the ill_index.
25030 			 * As this is being delivered locally, we don't
25031 			 * need this anymore.
25032 			 */
25033 			mp = first_mp->b_cont;
25034 			freeb(first_mp);
25035 			first_mp = mp;
25036 			mctl_present = B_FALSE;
25037 		} else {
25038 			/*
25039 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25040 			 * security properties for the looped-back packet.
25041 			 */
25042 			mctl_present = B_TRUE;
25043 			mp = first_mp->b_cont;
25044 			ASSERT(mp != NULL);
25045 			ipsec_out_to_in(first_mp);
25046 		}
25047 	} else {
25048 		mctl_present = B_FALSE;
25049 	}
25050 
25051 	DTRACE_PROBE4(ip4__loopback__in__start,
25052 	    ill_t *, ill, ill_t *, NULL,
25053 	    ipha_t *, ipha, mblk_t *, first_mp);
25054 
25055 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25056 	    ipst->ips_ipv4firewall_loopback_in,
25057 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25058 
25059 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25060 
25061 	if (first_mp == NULL)
25062 		return;
25063 
25064 	if (ipst->ips_ipobs_enabled) {
25065 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25066 		zoneid_t stackzoneid = netstackid_to_zoneid(
25067 		    ipst->ips_netstack->netstack_stackid);
25068 
25069 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25070 		/*
25071 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25072 		 * address.  Restrict the lookup below to the destination zone.
25073 		 */
25074 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25075 			lookup_zoneid = zoneid;
25076 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25077 		    lookup_zoneid);
25078 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25079 		    IPV4_VERSION, 0, ipst);
25080 	}
25081 
25082 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25083 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25084 	    int, 1);
25085 
25086 	ipst->ips_loopback_packets++;
25087 
25088 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25089 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25090 	if (!IS_SIMPLE_IPH(ipha)) {
25091 		ip_wput_local_options(ipha, ipst);
25092 	}
25093 
25094 	protocol = ipha->ipha_protocol;
25095 	switch (protocol) {
25096 	case IPPROTO_ICMP: {
25097 		ire_t		*ire_zone;
25098 		ilm_t		*ilm;
25099 		mblk_t		*mp1;
25100 		zoneid_t	last_zoneid;
25101 		ilm_walker_t	ilw;
25102 
25103 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25104 			ASSERT(ire_type == IRE_BROADCAST);
25105 			/*
25106 			 * In the multicast case, applications may have joined
25107 			 * the group from different zones, so we need to deliver
25108 			 * the packet to each of them. Loop through the
25109 			 * multicast memberships structures (ilm) on the receive
25110 			 * ill and send a copy of the packet up each matching
25111 			 * one. However, we don't do this for multicasts sent on
25112 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25113 			 * they must stay in the sender's zone.
25114 			 *
25115 			 * ilm_add_v6() ensures that ilms in the same zone are
25116 			 * contiguous in the ill_ilm list. We use this property
25117 			 * to avoid sending duplicates needed when two
25118 			 * applications in the same zone join the same group on
25119 			 * different logical interfaces: we ignore the ilm if
25120 			 * it's zoneid is the same as the last matching one.
25121 			 * In addition, the sending of the packet for
25122 			 * ire_zoneid is delayed until all of the other ilms
25123 			 * have been exhausted.
25124 			 */
25125 			last_zoneid = -1;
25126 			ilm = ilm_walker_start(&ilw, ill);
25127 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25128 				if (ipha->ipha_dst != ilm->ilm_addr ||
25129 				    ilm->ilm_zoneid == last_zoneid ||
25130 				    ilm->ilm_zoneid == zoneid ||
25131 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25132 					continue;
25133 				mp1 = ip_copymsg(first_mp);
25134 				if (mp1 == NULL)
25135 					continue;
25136 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25137 				    0, 0, mctl_present, B_FALSE, ill,
25138 				    ilm->ilm_zoneid);
25139 				last_zoneid = ilm->ilm_zoneid;
25140 			}
25141 			ilm_walker_finish(&ilw);
25142 			/*
25143 			 * Loopback case: the sending endpoint has
25144 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25145 			 * dispatch the multicast packet to the sending zone.
25146 			 */
25147 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25148 				freemsg(first_mp);
25149 				return;
25150 			}
25151 		} else if (ire_type == IRE_BROADCAST) {
25152 			/*
25153 			 * In the broadcast case, there may be many zones
25154 			 * which need a copy of the packet delivered to them.
25155 			 * There is one IRE_BROADCAST per broadcast address
25156 			 * and per zone; we walk those using a helper function.
25157 			 * In addition, the sending of the packet for zoneid is
25158 			 * delayed until all of the other ires have been
25159 			 * processed.
25160 			 */
25161 			IRB_REFHOLD(ire->ire_bucket);
25162 			ire_zone = NULL;
25163 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25164 			    ire)) != NULL) {
25165 				mp1 = ip_copymsg(first_mp);
25166 				if (mp1 == NULL)
25167 					continue;
25168 
25169 				UPDATE_IB_PKT_COUNT(ire_zone);
25170 				ire_zone->ire_last_used_time = lbolt;
25171 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25172 				    mctl_present, B_FALSE, ill,
25173 				    ire_zone->ire_zoneid);
25174 			}
25175 			IRB_REFRELE(ire->ire_bucket);
25176 		}
25177 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25178 		    0, mctl_present, B_FALSE, ill, zoneid);
25179 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25180 		    "ip_wput_local_end: q %p (%S)",
25181 		    q, "icmp");
25182 		return;
25183 	}
25184 	case IPPROTO_IGMP:
25185 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25186 			/* Bad packet - discarded by igmp_input */
25187 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25188 			    "ip_wput_local_end: q %p (%S)",
25189 			    q, "igmp_input--bad packet");
25190 			if (mctl_present)
25191 				freeb(first_mp);
25192 			return;
25193 		}
25194 		/*
25195 		 * igmp_input() may have returned the pulled up message.
25196 		 * So first_mp and ipha need to be reinitialized.
25197 		 */
25198 		ipha = (ipha_t *)mp->b_rptr;
25199 		if (mctl_present)
25200 			first_mp->b_cont = mp;
25201 		else
25202 			first_mp = mp;
25203 		/* deliver to local raw users */
25204 		break;
25205 	case IPPROTO_ENCAP:
25206 		/*
25207 		 * This case is covered by either ip_fanout_proto, or by
25208 		 * the above security processing for self-tunneled packets.
25209 		 */
25210 		break;
25211 	case IPPROTO_UDP: {
25212 		uint16_t	*up;
25213 		uint32_t	ports;
25214 
25215 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25216 		    UDP_PORTS_OFFSET);
25217 		/* Force a 'valid' checksum. */
25218 		up[3] = 0;
25219 
25220 		ports = *(uint32_t *)up;
25221 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25222 		    (ire_type == IRE_BROADCAST),
25223 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25224 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25225 		    ill, zoneid);
25226 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25227 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25228 		return;
25229 	}
25230 	case IPPROTO_TCP: {
25231 
25232 		/*
25233 		 * For TCP, discard broadcast packets.
25234 		 */
25235 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25236 			freemsg(first_mp);
25237 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25238 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25239 			return;
25240 		}
25241 
25242 		if (mp->b_datap->db_type == M_DATA) {
25243 			/*
25244 			 * M_DATA mblk, so init mblk (chain) for no struio().
25245 			 */
25246 			mblk_t	*mp1 = mp;
25247 
25248 			do {
25249 				mp1->b_datap->db_struioflag = 0;
25250 			} while ((mp1 = mp1->b_cont) != NULL);
25251 		}
25252 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25253 		    <= mp->b_wptr);
25254 		ip_fanout_tcp(q, first_mp, ill, ipha,
25255 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25256 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25257 		    mctl_present, B_FALSE, zoneid);
25258 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25259 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25260 		return;
25261 	}
25262 	case IPPROTO_SCTP:
25263 	{
25264 		uint32_t	ports;
25265 
25266 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25267 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25268 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25269 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25270 		return;
25271 	}
25272 
25273 	default:
25274 		break;
25275 	}
25276 	/*
25277 	 * Find a client for some other protocol.  We give
25278 	 * copies to multiple clients, if more than one is
25279 	 * bound.
25280 	 */
25281 	ip_fanout_proto(q, first_mp, ill, ipha,
25282 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25283 	    mctl_present, B_FALSE, ill, zoneid);
25284 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25285 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25286 #undef	rptr
25287 }
25288 
25289 /*
25290  * Update any source route, record route, or timestamp options.
25291  * Check that we are at end of strict source route.
25292  * The options have been sanity checked by ip_wput_options().
25293  */
25294 static void
25295 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25296 {
25297 	ipoptp_t	opts;
25298 	uchar_t		*opt;
25299 	uint8_t		optval;
25300 	uint8_t		optlen;
25301 	ipaddr_t	dst;
25302 	uint32_t	ts;
25303 	ire_t		*ire;
25304 	timestruc_t	now;
25305 
25306 	ip2dbg(("ip_wput_local_options\n"));
25307 	for (optval = ipoptp_first(&opts, ipha);
25308 	    optval != IPOPT_EOL;
25309 	    optval = ipoptp_next(&opts)) {
25310 		opt = opts.ipoptp_cur;
25311 		optlen = opts.ipoptp_len;
25312 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25313 		switch (optval) {
25314 			uint32_t off;
25315 		case IPOPT_SSRR:
25316 		case IPOPT_LSRR:
25317 			off = opt[IPOPT_OFFSET];
25318 			off--;
25319 			if (optlen < IP_ADDR_LEN ||
25320 			    off > optlen - IP_ADDR_LEN) {
25321 				/* End of source route */
25322 				break;
25323 			}
25324 			/*
25325 			 * This will only happen if two consecutive entries
25326 			 * in the source route contains our address or if
25327 			 * it is a packet with a loose source route which
25328 			 * reaches us before consuming the whole source route
25329 			 */
25330 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25331 			if (optval == IPOPT_SSRR) {
25332 				return;
25333 			}
25334 			/*
25335 			 * Hack: instead of dropping the packet truncate the
25336 			 * source route to what has been used by filling the
25337 			 * rest with IPOPT_NOP.
25338 			 */
25339 			opt[IPOPT_OLEN] = (uint8_t)off;
25340 			while (off < optlen) {
25341 				opt[off++] = IPOPT_NOP;
25342 			}
25343 			break;
25344 		case IPOPT_RR:
25345 			off = opt[IPOPT_OFFSET];
25346 			off--;
25347 			if (optlen < IP_ADDR_LEN ||
25348 			    off > optlen - IP_ADDR_LEN) {
25349 				/* No more room - ignore */
25350 				ip1dbg((
25351 				    "ip_wput_forward_options: end of RR\n"));
25352 				break;
25353 			}
25354 			dst = htonl(INADDR_LOOPBACK);
25355 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25356 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25357 			break;
25358 		case IPOPT_TS:
25359 			/* Insert timestamp if there is romm */
25360 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25361 			case IPOPT_TS_TSONLY:
25362 				off = IPOPT_TS_TIMELEN;
25363 				break;
25364 			case IPOPT_TS_PRESPEC:
25365 			case IPOPT_TS_PRESPEC_RFC791:
25366 				/* Verify that the address matched */
25367 				off = opt[IPOPT_OFFSET] - 1;
25368 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25369 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25370 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25371 				    ipst);
25372 				if (ire == NULL) {
25373 					/* Not for us */
25374 					break;
25375 				}
25376 				ire_refrele(ire);
25377 				/* FALLTHRU */
25378 			case IPOPT_TS_TSANDADDR:
25379 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25380 				break;
25381 			default:
25382 				/*
25383 				 * ip_*put_options should have already
25384 				 * dropped this packet.
25385 				 */
25386 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25387 				    "unknown IT - bug in ip_wput_options?\n");
25388 				return;	/* Keep "lint" happy */
25389 			}
25390 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25391 				/* Increase overflow counter */
25392 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25393 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25394 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25395 				    (off << 4);
25396 				break;
25397 			}
25398 			off = opt[IPOPT_OFFSET] - 1;
25399 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25400 			case IPOPT_TS_PRESPEC:
25401 			case IPOPT_TS_PRESPEC_RFC791:
25402 			case IPOPT_TS_TSANDADDR:
25403 				dst = htonl(INADDR_LOOPBACK);
25404 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25405 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25406 				/* FALLTHRU */
25407 			case IPOPT_TS_TSONLY:
25408 				off = opt[IPOPT_OFFSET] - 1;
25409 				/* Compute # of milliseconds since midnight */
25410 				gethrestime(&now);
25411 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25412 				    now.tv_nsec / (NANOSEC / MILLISEC);
25413 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25414 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25415 				break;
25416 			}
25417 			break;
25418 		}
25419 	}
25420 }
25421 
25422 /*
25423  * Send out a multicast packet on interface ipif.
25424  * The sender does not have an conn.
25425  * Caller verifies that this isn't a PHYI_LOOPBACK.
25426  */
25427 void
25428 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25429 {
25430 	ipha_t	*ipha;
25431 	ire_t	*ire;
25432 	ipaddr_t	dst;
25433 	mblk_t		*first_mp;
25434 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25435 
25436 	/* igmp_sendpkt always allocates a ipsec_out_t */
25437 	ASSERT(mp->b_datap->db_type == M_CTL);
25438 	ASSERT(!ipif->ipif_isv6);
25439 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25440 
25441 	first_mp = mp;
25442 	mp = first_mp->b_cont;
25443 	ASSERT(mp->b_datap->db_type == M_DATA);
25444 	ipha = (ipha_t *)mp->b_rptr;
25445 
25446 	/*
25447 	 * Find an IRE which matches the destination and the outgoing
25448 	 * queue (i.e. the outgoing interface.)
25449 	 */
25450 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25451 		dst = ipif->ipif_pp_dst_addr;
25452 	else
25453 		dst = ipha->ipha_dst;
25454 	/*
25455 	 * The source address has already been initialized by the
25456 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25457 	 * be sufficient rather than MATCH_IRE_IPIF.
25458 	 *
25459 	 * This function is used for sending IGMP packets.  For IPMP,
25460 	 * we sidestep IGMP snooping issues by sending all multicast
25461 	 * traffic on a single interface in the IPMP group.
25462 	 */
25463 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25464 	    MATCH_IRE_ILL, ipst);
25465 	if (!ire) {
25466 		/*
25467 		 * Mark this packet to make it be delivered to
25468 		 * ip_wput_ire after the new ire has been
25469 		 * created.
25470 		 */
25471 		mp->b_prev = NULL;
25472 		mp->b_next = NULL;
25473 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25474 		    zoneid, &zero_info);
25475 		return;
25476 	}
25477 
25478 	/*
25479 	 * Honor the RTF_SETSRC flag; this is the only case
25480 	 * where we force this addr whatever the current src addr is,
25481 	 * because this address is set by igmp_sendpkt(), and
25482 	 * cannot be specified by any user.
25483 	 */
25484 	if (ire->ire_flags & RTF_SETSRC) {
25485 		ipha->ipha_src = ire->ire_src_addr;
25486 	}
25487 
25488 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25489 }
25490 
25491 /*
25492  * NOTE : This function does not ire_refrele the ire argument passed in.
25493  *
25494  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25495  * failure. The nce_fp_mp can vanish any time in the case of
25496  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25497  * the ire_lock to access the nce_fp_mp in this case.
25498  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25499  * prepending a fastpath message IPQoS processing must precede it, we also set
25500  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25501  * (IPQoS might have set the b_band for CoS marking).
25502  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25503  * must follow it so that IPQoS can mark the dl_priority field for CoS
25504  * marking, if needed.
25505  */
25506 static mblk_t *
25507 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25508     uint32_t ill_index, ipha_t **iphap)
25509 {
25510 	uint_t	hlen;
25511 	ipha_t *ipha;
25512 	mblk_t *mp1;
25513 	boolean_t qos_done = B_FALSE;
25514 	uchar_t	*ll_hdr;
25515 	ip_stack_t	*ipst = ire->ire_ipst;
25516 
25517 #define	rptr	((uchar_t *)ipha)
25518 
25519 	ipha = (ipha_t *)mp->b_rptr;
25520 	hlen = 0;
25521 	LOCK_IRE_FP_MP(ire);
25522 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25523 		ASSERT(DB_TYPE(mp1) == M_DATA);
25524 		/* Initiate IPPF processing */
25525 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25526 			UNLOCK_IRE_FP_MP(ire);
25527 			ip_process(proc, &mp, ill_index);
25528 			if (mp == NULL)
25529 				return (NULL);
25530 
25531 			ipha = (ipha_t *)mp->b_rptr;
25532 			LOCK_IRE_FP_MP(ire);
25533 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25534 				qos_done = B_TRUE;
25535 				goto no_fp_mp;
25536 			}
25537 			ASSERT(DB_TYPE(mp1) == M_DATA);
25538 		}
25539 		hlen = MBLKL(mp1);
25540 		/*
25541 		 * Check if we have enough room to prepend fastpath
25542 		 * header
25543 		 */
25544 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25545 			ll_hdr = rptr - hlen;
25546 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25547 			/*
25548 			 * Set the b_rptr to the start of the link layer
25549 			 * header
25550 			 */
25551 			mp->b_rptr = ll_hdr;
25552 			mp1 = mp;
25553 		} else {
25554 			mp1 = copyb(mp1);
25555 			if (mp1 == NULL)
25556 				goto unlock_err;
25557 			mp1->b_band = mp->b_band;
25558 			mp1->b_cont = mp;
25559 			/*
25560 			 * XXX disable ICK_VALID and compute checksum
25561 			 * here; can happen if nce_fp_mp changes and
25562 			 * it can't be copied now due to insufficient
25563 			 * space. (unlikely, fp mp can change, but it
25564 			 * does not increase in length)
25565 			 */
25566 		}
25567 		UNLOCK_IRE_FP_MP(ire);
25568 	} else {
25569 no_fp_mp:
25570 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25571 		if (mp1 == NULL) {
25572 unlock_err:
25573 			UNLOCK_IRE_FP_MP(ire);
25574 			freemsg(mp);
25575 			return (NULL);
25576 		}
25577 		UNLOCK_IRE_FP_MP(ire);
25578 		mp1->b_cont = mp;
25579 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25580 			ip_process(proc, &mp1, ill_index);
25581 			if (mp1 == NULL)
25582 				return (NULL);
25583 
25584 			if (mp1->b_cont == NULL)
25585 				ipha = NULL;
25586 			else
25587 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25588 		}
25589 	}
25590 
25591 	*iphap = ipha;
25592 	return (mp1);
25593 #undef rptr
25594 }
25595 
25596 /*
25597  * Finish the outbound IPsec processing for an IPv6 packet. This function
25598  * is called from ipsec_out_process() if the IPsec packet was processed
25599  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25600  * asynchronously.
25601  */
25602 void
25603 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25604     ire_t *ire_arg)
25605 {
25606 	in6_addr_t *v6dstp;
25607 	ire_t *ire;
25608 	mblk_t *mp;
25609 	ip6_t *ip6h1;
25610 	uint_t	ill_index;
25611 	ipsec_out_t *io;
25612 	boolean_t hwaccel;
25613 	uint32_t flags = IP6_NO_IPPOLICY;
25614 	int match_flags;
25615 	zoneid_t zoneid;
25616 	boolean_t ill_need_rele = B_FALSE;
25617 	boolean_t ire_need_rele = B_FALSE;
25618 	ip_stack_t	*ipst;
25619 
25620 	mp = ipsec_mp->b_cont;
25621 	ip6h1 = (ip6_t *)mp->b_rptr;
25622 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25623 	ASSERT(io->ipsec_out_ns != NULL);
25624 	ipst = io->ipsec_out_ns->netstack_ip;
25625 	ill_index = io->ipsec_out_ill_index;
25626 	if (io->ipsec_out_reachable) {
25627 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25628 	}
25629 	hwaccel = io->ipsec_out_accelerated;
25630 	zoneid = io->ipsec_out_zoneid;
25631 	ASSERT(zoneid != ALL_ZONES);
25632 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25633 	/* Multicast addresses should have non-zero ill_index. */
25634 	v6dstp = &ip6h->ip6_dst;
25635 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25636 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25637 
25638 	if (ill == NULL && ill_index != 0) {
25639 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25640 		/* Failure case frees things for us. */
25641 		if (ill == NULL)
25642 			return;
25643 
25644 		ill_need_rele = B_TRUE;
25645 	}
25646 	ASSERT(mp != NULL);
25647 
25648 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25649 		boolean_t unspec_src;
25650 		ipif_t	*ipif;
25651 
25652 		/*
25653 		 * Use the ill_index to get the right ill.
25654 		 */
25655 		unspec_src = io->ipsec_out_unspec_src;
25656 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25657 		if (ipif == NULL) {
25658 			if (ill_need_rele)
25659 				ill_refrele(ill);
25660 			freemsg(ipsec_mp);
25661 			return;
25662 		}
25663 
25664 		if (ire_arg != NULL) {
25665 			ire = ire_arg;
25666 		} else {
25667 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25668 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25669 			ire_need_rele = B_TRUE;
25670 		}
25671 		if (ire != NULL) {
25672 			ipif_refrele(ipif);
25673 			/*
25674 			 * XXX Do the multicast forwarding now, as the IPsec
25675 			 * processing has been done.
25676 			 */
25677 			goto send;
25678 		}
25679 
25680 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25681 		mp->b_prev = NULL;
25682 		mp->b_next = NULL;
25683 
25684 		/*
25685 		 * If the IPsec packet was processed asynchronously,
25686 		 * drop it now.
25687 		 */
25688 		if (q == NULL) {
25689 			if (ill_need_rele)
25690 				ill_refrele(ill);
25691 			freemsg(ipsec_mp);
25692 			return;
25693 		}
25694 
25695 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25696 		    unspec_src, zoneid);
25697 		ipif_refrele(ipif);
25698 	} else {
25699 		if (ire_arg != NULL) {
25700 			ire = ire_arg;
25701 		} else {
25702 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25703 			ire_need_rele = B_TRUE;
25704 		}
25705 		if (ire != NULL)
25706 			goto send;
25707 		/*
25708 		 * ire disappeared underneath.
25709 		 *
25710 		 * What we need to do here is the ip_newroute
25711 		 * logic to get the ire without doing the IPsec
25712 		 * processing. Follow the same old path. But this
25713 		 * time, ip_wput or ire_add_then_send will call us
25714 		 * directly as all the IPsec operations are done.
25715 		 */
25716 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25717 		mp->b_prev = NULL;
25718 		mp->b_next = NULL;
25719 
25720 		/*
25721 		 * If the IPsec packet was processed asynchronously,
25722 		 * drop it now.
25723 		 */
25724 		if (q == NULL) {
25725 			if (ill_need_rele)
25726 				ill_refrele(ill);
25727 			freemsg(ipsec_mp);
25728 			return;
25729 		}
25730 
25731 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25732 		    zoneid, ipst);
25733 	}
25734 	if (ill != NULL && ill_need_rele)
25735 		ill_refrele(ill);
25736 	return;
25737 send:
25738 	if (ill != NULL && ill_need_rele)
25739 		ill_refrele(ill);
25740 
25741 	/* Local delivery */
25742 	if (ire->ire_stq == NULL) {
25743 		ill_t	*out_ill;
25744 		ASSERT(q != NULL);
25745 
25746 		/* PFHooks: LOOPBACK_OUT */
25747 		out_ill = ire_to_ill(ire);
25748 
25749 		/*
25750 		 * DTrace this as ip:::send.  A blocked packet will fire the
25751 		 * send probe, but not the receive probe.
25752 		 */
25753 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25754 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25755 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25756 
25757 		DTRACE_PROBE4(ip6__loopback__out__start,
25758 		    ill_t *, NULL, ill_t *, out_ill,
25759 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25760 
25761 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25762 		    ipst->ips_ipv6firewall_loopback_out,
25763 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25764 
25765 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25766 
25767 		if (ipsec_mp != NULL) {
25768 			ip_wput_local_v6(RD(q), out_ill,
25769 			    ip6h, ipsec_mp, ire, 0, zoneid);
25770 		}
25771 		if (ire_need_rele)
25772 			ire_refrele(ire);
25773 		return;
25774 	}
25775 	/*
25776 	 * Everything is done. Send it out on the wire.
25777 	 * We force the insertion of a fragment header using the
25778 	 * IPH_FRAG_HDR flag in two cases:
25779 	 * - after reception of an ICMPv6 "packet too big" message
25780 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25781 	 * - for multirouted IPv6 packets, so that the receiver can
25782 	 *   discard duplicates according to their fragment identifier
25783 	 */
25784 	/* XXX fix flow control problems. */
25785 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25786 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25787 		if (hwaccel) {
25788 			/*
25789 			 * hardware acceleration does not handle these
25790 			 * "slow path" cases.
25791 			 */
25792 			/* IPsec KSTATS: should bump bean counter here. */
25793 			if (ire_need_rele)
25794 				ire_refrele(ire);
25795 			freemsg(ipsec_mp);
25796 			return;
25797 		}
25798 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25799 		    (mp->b_cont ? msgdsize(mp) :
25800 		    mp->b_wptr - (uchar_t *)ip6h)) {
25801 			/* IPsec KSTATS: should bump bean counter here. */
25802 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25803 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25804 			    msgdsize(mp)));
25805 			if (ire_need_rele)
25806 				ire_refrele(ire);
25807 			freemsg(ipsec_mp);
25808 			return;
25809 		}
25810 		ASSERT(mp->b_prev == NULL);
25811 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25812 		    ntohs(ip6h->ip6_plen) +
25813 		    IPV6_HDR_LEN, ire->ire_max_frag));
25814 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25815 		    ire->ire_max_frag);
25816 	} else {
25817 		UPDATE_OB_PKT_COUNT(ire);
25818 		ire->ire_last_used_time = lbolt;
25819 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25820 	}
25821 	if (ire_need_rele)
25822 		ire_refrele(ire);
25823 	freeb(ipsec_mp);
25824 }
25825 
25826 void
25827 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25828 {
25829 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25830 	da_ipsec_t *hada;	/* data attributes */
25831 	ill_t *ill = (ill_t *)q->q_ptr;
25832 
25833 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25834 
25835 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25836 		/* IPsec KSTATS: Bump lose counter here! */
25837 		freemsg(mp);
25838 		return;
25839 	}
25840 
25841 	/*
25842 	 * It's an IPsec packet that must be
25843 	 * accelerated by the Provider, and the
25844 	 * outbound ill is IPsec acceleration capable.
25845 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25846 	 * to the ill.
25847 	 * IPsec KSTATS: should bump packet counter here.
25848 	 */
25849 
25850 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25851 	if (hada_mp == NULL) {
25852 		/* IPsec KSTATS: should bump packet counter here. */
25853 		freemsg(mp);
25854 		return;
25855 	}
25856 
25857 	hada_mp->b_datap->db_type = M_CTL;
25858 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25859 	hada_mp->b_cont = mp;
25860 
25861 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25862 	bzero(hada, sizeof (da_ipsec_t));
25863 	hada->da_type = IPHADA_M_CTL;
25864 
25865 	putnext(q, hada_mp);
25866 }
25867 
25868 /*
25869  * Finish the outbound IPsec processing. This function is called from
25870  * ipsec_out_process() if the IPsec packet was processed
25871  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25872  * asynchronously.
25873  */
25874 void
25875 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25876     ire_t *ire_arg)
25877 {
25878 	uint32_t v_hlen_tos_len;
25879 	ipaddr_t	dst;
25880 	ipif_t	*ipif = NULL;
25881 	ire_t *ire;
25882 	ire_t *ire1 = NULL;
25883 	mblk_t *next_mp = NULL;
25884 	uint32_t max_frag;
25885 	boolean_t multirt_send = B_FALSE;
25886 	mblk_t *mp;
25887 	ipha_t *ipha1;
25888 	uint_t	ill_index;
25889 	ipsec_out_t *io;
25890 	int match_flags;
25891 	irb_t *irb = NULL;
25892 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25893 	zoneid_t zoneid;
25894 	ipxmit_state_t	pktxmit_state;
25895 	ip_stack_t	*ipst;
25896 
25897 #ifdef	_BIG_ENDIAN
25898 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25899 #else
25900 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25901 #endif
25902 
25903 	mp = ipsec_mp->b_cont;
25904 	ipha1 = (ipha_t *)mp->b_rptr;
25905 	ASSERT(mp != NULL);
25906 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25907 	dst = ipha->ipha_dst;
25908 
25909 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25910 	ill_index = io->ipsec_out_ill_index;
25911 	zoneid = io->ipsec_out_zoneid;
25912 	ASSERT(zoneid != ALL_ZONES);
25913 	ipst = io->ipsec_out_ns->netstack_ip;
25914 	ASSERT(io->ipsec_out_ns != NULL);
25915 
25916 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25917 	if (ill == NULL && ill_index != 0) {
25918 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25919 		/* Failure case frees things for us. */
25920 		if (ill == NULL)
25921 			return;
25922 
25923 		ill_need_rele = B_TRUE;
25924 	}
25925 
25926 	if (CLASSD(dst)) {
25927 		boolean_t conn_dontroute;
25928 		/*
25929 		 * Use the ill_index to get the right ipif.
25930 		 */
25931 		conn_dontroute = io->ipsec_out_dontroute;
25932 		if (ill_index == 0)
25933 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25934 		else
25935 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25936 		if (ipif == NULL) {
25937 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25938 			    " multicast\n"));
25939 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25940 			freemsg(ipsec_mp);
25941 			goto done;
25942 		}
25943 		/*
25944 		 * ipha_src has already been intialized with the
25945 		 * value of the ipif in ip_wput. All we need now is
25946 		 * an ire to send this downstream.
25947 		 */
25948 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25949 		    msg_getlabel(mp), match_flags, ipst);
25950 		if (ire != NULL) {
25951 			ill_t *ill1;
25952 			/*
25953 			 * Do the multicast forwarding now, as the IPsec
25954 			 * processing has been done.
25955 			 */
25956 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25957 			    (ill1 = ire_to_ill(ire))) {
25958 				if (ip_mforward(ill1, ipha, mp)) {
25959 					freemsg(ipsec_mp);
25960 					ip1dbg(("ip_wput_ipsec_out: mforward "
25961 					    "failed\n"));
25962 					ire_refrele(ire);
25963 					goto done;
25964 				}
25965 			}
25966 			goto send;
25967 		}
25968 
25969 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25970 		mp->b_prev = NULL;
25971 		mp->b_next = NULL;
25972 
25973 		/*
25974 		 * If the IPsec packet was processed asynchronously,
25975 		 * drop it now.
25976 		 */
25977 		if (q == NULL) {
25978 			freemsg(ipsec_mp);
25979 			goto done;
25980 		}
25981 
25982 		/*
25983 		 * We may be using a wrong ipif to create the ire.
25984 		 * But it is okay as the source address is assigned
25985 		 * for the packet already. Next outbound packet would
25986 		 * create the IRE with the right IPIF in ip_wput.
25987 		 *
25988 		 * Also handle RTF_MULTIRT routes.
25989 		 */
25990 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25991 		    zoneid, &zero_info);
25992 	} else {
25993 		if (ire_arg != NULL) {
25994 			ire = ire_arg;
25995 			ire_need_rele = B_FALSE;
25996 		} else {
25997 			ire = ire_cache_lookup(dst, zoneid,
25998 			    msg_getlabel(mp), ipst);
25999 		}
26000 		if (ire != NULL) {
26001 			goto send;
26002 		}
26003 
26004 		/*
26005 		 * ire disappeared underneath.
26006 		 *
26007 		 * What we need to do here is the ip_newroute
26008 		 * logic to get the ire without doing the IPsec
26009 		 * processing. Follow the same old path. But this
26010 		 * time, ip_wput or ire_add_then_put will call us
26011 		 * directly as all the IPsec operations are done.
26012 		 */
26013 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26014 		mp->b_prev = NULL;
26015 		mp->b_next = NULL;
26016 
26017 		/*
26018 		 * If the IPsec packet was processed asynchronously,
26019 		 * drop it now.
26020 		 */
26021 		if (q == NULL) {
26022 			freemsg(ipsec_mp);
26023 			goto done;
26024 		}
26025 
26026 		/*
26027 		 * Since we're going through ip_newroute() again, we
26028 		 * need to make sure we don't:
26029 		 *
26030 		 *	1.) Trigger the ASSERT() with the ipha_ident
26031 		 *	    overloading.
26032 		 *	2.) Redo transport-layer checksumming, since we've
26033 		 *	    already done all that to get this far.
26034 		 *
26035 		 * The easiest way not do either of the above is to set
26036 		 * the ipha_ident field to IP_HDR_INCLUDED.
26037 		 */
26038 		ipha->ipha_ident = IP_HDR_INCLUDED;
26039 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26040 		    zoneid, ipst);
26041 	}
26042 	goto done;
26043 send:
26044 	if (ire->ire_stq == NULL) {
26045 		ill_t	*out_ill;
26046 		/*
26047 		 * Loopbacks go through ip_wput_local except for one case.
26048 		 * We come here if we generate a icmp_frag_needed message
26049 		 * after IPsec processing is over. When this function calls
26050 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26051 		 * icmp_frag_needed. The message generated comes back here
26052 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26053 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26054 		 * source address as it is usually set in ip_wput_ire. As
26055 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26056 		 * and we end up here. We can't enter ip_wput_ire once the
26057 		 * IPsec processing is over and hence we need to do it here.
26058 		 */
26059 		ASSERT(q != NULL);
26060 		UPDATE_OB_PKT_COUNT(ire);
26061 		ire->ire_last_used_time = lbolt;
26062 		if (ipha->ipha_src == 0)
26063 			ipha->ipha_src = ire->ire_src_addr;
26064 
26065 		/* PFHooks: LOOPBACK_OUT */
26066 		out_ill = ire_to_ill(ire);
26067 
26068 		/*
26069 		 * DTrace this as ip:::send.  A blocked packet will fire the
26070 		 * send probe, but not the receive probe.
26071 		 */
26072 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26073 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26074 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26075 
26076 		DTRACE_PROBE4(ip4__loopback__out__start,
26077 		    ill_t *, NULL, ill_t *, out_ill,
26078 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26079 
26080 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26081 		    ipst->ips_ipv4firewall_loopback_out,
26082 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26083 
26084 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26085 
26086 		if (ipsec_mp != NULL)
26087 			ip_wput_local(RD(q), out_ill,
26088 			    ipha, ipsec_mp, ire, 0, zoneid);
26089 		if (ire_need_rele)
26090 			ire_refrele(ire);
26091 		goto done;
26092 	}
26093 
26094 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26095 		/*
26096 		 * We are through with IPsec processing.
26097 		 * Fragment this and send it on the wire.
26098 		 */
26099 		if (io->ipsec_out_accelerated) {
26100 			/*
26101 			 * The packet has been accelerated but must
26102 			 * be fragmented. This should not happen
26103 			 * since AH and ESP must not accelerate
26104 			 * packets that need fragmentation, however
26105 			 * the configuration could have changed
26106 			 * since the AH or ESP processing.
26107 			 * Drop packet.
26108 			 * IPsec KSTATS: bump bean counter here.
26109 			 */
26110 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26111 			    "fragmented accelerated packet!\n"));
26112 			freemsg(ipsec_mp);
26113 		} else {
26114 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26115 			    zoneid, ipst, NULL);
26116 		}
26117 		if (ire_need_rele)
26118 			ire_refrele(ire);
26119 		goto done;
26120 	}
26121 
26122 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26123 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26124 	    (void *)ire->ire_ipif, (void *)ipif));
26125 
26126 	/*
26127 	 * Multiroute the secured packet.
26128 	 */
26129 	if (ire->ire_flags & RTF_MULTIRT) {
26130 		ire_t *first_ire;
26131 		irb = ire->ire_bucket;
26132 		ASSERT(irb != NULL);
26133 		/*
26134 		 * This ire has been looked up as the one that
26135 		 * goes through the given ipif;
26136 		 * make sure we do not omit any other multiroute ire
26137 		 * that may be present in the bucket before this one.
26138 		 */
26139 		IRB_REFHOLD(irb);
26140 		for (first_ire = irb->irb_ire;
26141 		    first_ire != NULL;
26142 		    first_ire = first_ire->ire_next) {
26143 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26144 			    (first_ire->ire_addr == ire->ire_addr) &&
26145 			    !(first_ire->ire_marks &
26146 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26147 				break;
26148 		}
26149 
26150 		if ((first_ire != NULL) && (first_ire != ire)) {
26151 			/*
26152 			 * Don't change the ire if the packet must
26153 			 * be fragmented if sent via this new one.
26154 			 */
26155 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26156 				IRE_REFHOLD(first_ire);
26157 				if (ire_need_rele)
26158 					ire_refrele(ire);
26159 				else
26160 					ire_need_rele = B_TRUE;
26161 				ire = first_ire;
26162 			}
26163 		}
26164 		IRB_REFRELE(irb);
26165 
26166 		multirt_send = B_TRUE;
26167 		max_frag = ire->ire_max_frag;
26168 	}
26169 
26170 	/*
26171 	 * In most cases, the emission loop below is entered only once.
26172 	 * Only in the case where the ire holds the RTF_MULTIRT
26173 	 * flag, we loop to process all RTF_MULTIRT ires in the
26174 	 * bucket, and send the packet through all crossed
26175 	 * RTF_MULTIRT routes.
26176 	 */
26177 	do {
26178 		if (multirt_send) {
26179 			/*
26180 			 * ire1 holds here the next ire to process in the
26181 			 * bucket. If multirouting is expected,
26182 			 * any non-RTF_MULTIRT ire that has the
26183 			 * right destination address is ignored.
26184 			 */
26185 			ASSERT(irb != NULL);
26186 			IRB_REFHOLD(irb);
26187 			for (ire1 = ire->ire_next;
26188 			    ire1 != NULL;
26189 			    ire1 = ire1->ire_next) {
26190 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26191 					continue;
26192 				if (ire1->ire_addr != ire->ire_addr)
26193 					continue;
26194 				if (ire1->ire_marks &
26195 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26196 					continue;
26197 				/* No loopback here */
26198 				if (ire1->ire_stq == NULL)
26199 					continue;
26200 				/*
26201 				 * Ensure we do not exceed the MTU
26202 				 * of the next route.
26203 				 */
26204 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26205 					ip_multirt_bad_mtu(ire1, max_frag);
26206 					continue;
26207 				}
26208 
26209 				IRE_REFHOLD(ire1);
26210 				break;
26211 			}
26212 			IRB_REFRELE(irb);
26213 			if (ire1 != NULL) {
26214 				/*
26215 				 * We are in a multiple send case, need to
26216 				 * make a copy of the packet.
26217 				 */
26218 				next_mp = copymsg(ipsec_mp);
26219 				if (next_mp == NULL) {
26220 					ire_refrele(ire1);
26221 					ire1 = NULL;
26222 				}
26223 			}
26224 		}
26225 		/*
26226 		 * Everything is done. Send it out on the wire
26227 		 *
26228 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26229 		 * either send it on the wire or, in the case of
26230 		 * HW acceleration, call ipsec_hw_putnext.
26231 		 */
26232 		if (ire->ire_nce &&
26233 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26234 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26235 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26236 			/*
26237 			 * If ire's link-layer is unresolved (this
26238 			 * would only happen if the incomplete ire
26239 			 * was added to cachetable via forwarding path)
26240 			 * don't bother going to ip_xmit_v4. Just drop the
26241 			 * packet.
26242 			 * There is a slight risk here, in that, if we
26243 			 * have the forwarding path create an incomplete
26244 			 * IRE, then until the IRE is completed, any
26245 			 * transmitted IPsec packets will be dropped
26246 			 * instead of being queued waiting for resolution.
26247 			 *
26248 			 * But the likelihood of a forwarding packet and a wput
26249 			 * packet sending to the same dst at the same time
26250 			 * and there not yet be an ARP entry for it is small.
26251 			 * Furthermore, if this actually happens, it might
26252 			 * be likely that wput would generate multiple
26253 			 * packets (and forwarding would also have a train
26254 			 * of packets) for that destination. If this is
26255 			 * the case, some of them would have been dropped
26256 			 * anyway, since ARP only queues a few packets while
26257 			 * waiting for resolution
26258 			 *
26259 			 * NOTE: We should really call ip_xmit_v4,
26260 			 * and let it queue the packet and send the
26261 			 * ARP query and have ARP come back thus:
26262 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26263 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26264 			 * hw accel work. But it's too complex to get
26265 			 * the IPsec hw  acceleration approach to fit
26266 			 * well with ip_xmit_v4 doing ARP without
26267 			 * doing IPsec simplification. For now, we just
26268 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26269 			 * that we can continue with the send on the next
26270 			 * attempt.
26271 			 *
26272 			 * XXX THis should be revisited, when
26273 			 * the IPsec/IP interaction is cleaned up
26274 			 */
26275 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26276 			    " - dropping packet\n"));
26277 			freemsg(ipsec_mp);
26278 			/*
26279 			 * Call ip_xmit_v4() to trigger ARP query
26280 			 * in case the nce_state is ND_INITIAL
26281 			 */
26282 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26283 			goto drop_pkt;
26284 		}
26285 
26286 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26287 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26288 		    mblk_t *, ipsec_mp);
26289 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26290 		    ipst->ips_ipv4firewall_physical_out, NULL,
26291 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26292 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26293 		if (ipsec_mp == NULL)
26294 			goto drop_pkt;
26295 
26296 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26297 		pktxmit_state = ip_xmit_v4(mp, ire,
26298 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26299 
26300 		if ((pktxmit_state ==  SEND_FAILED) ||
26301 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26302 
26303 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26304 drop_pkt:
26305 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26306 			    ipIfStatsOutDiscards);
26307 			if (ire_need_rele)
26308 				ire_refrele(ire);
26309 			if (ire1 != NULL) {
26310 				ire_refrele(ire1);
26311 				freemsg(next_mp);
26312 			}
26313 			goto done;
26314 		}
26315 
26316 		freeb(ipsec_mp);
26317 		if (ire_need_rele)
26318 			ire_refrele(ire);
26319 
26320 		if (ire1 != NULL) {
26321 			ire = ire1;
26322 			ire_need_rele = B_TRUE;
26323 			ASSERT(next_mp);
26324 			ipsec_mp = next_mp;
26325 			mp = ipsec_mp->b_cont;
26326 			ire1 = NULL;
26327 			next_mp = NULL;
26328 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26329 		} else {
26330 			multirt_send = B_FALSE;
26331 		}
26332 	} while (multirt_send);
26333 done:
26334 	if (ill != NULL && ill_need_rele)
26335 		ill_refrele(ill);
26336 	if (ipif != NULL)
26337 		ipif_refrele(ipif);
26338 }
26339 
26340 /*
26341  * Get the ill corresponding to the specified ire, and compare its
26342  * capabilities with the protocol and algorithms specified by the
26343  * the SA obtained from ipsec_out. If they match, annotate the
26344  * ipsec_out structure to indicate that the packet needs acceleration.
26345  *
26346  *
26347  * A packet is eligible for outbound hardware acceleration if the
26348  * following conditions are satisfied:
26349  *
26350  * 1. the packet will not be fragmented
26351  * 2. the provider supports the algorithm
26352  * 3. there is no pending control message being exchanged
26353  * 4. snoop is not attached
26354  * 5. the destination address is not a broadcast or multicast address.
26355  *
26356  * Rationale:
26357  *	- Hardware drivers do not support fragmentation with
26358  *	  the current interface.
26359  *	- snoop, multicast, and broadcast may result in exposure of
26360  *	  a cleartext datagram.
26361  * We check all five of these conditions here.
26362  *
26363  * XXX would like to nuke "ire_t *" parameter here; problem is that
26364  * IRE is only way to figure out if a v4 address is a broadcast and
26365  * thus ineligible for acceleration...
26366  */
26367 static void
26368 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26369 {
26370 	ipsec_out_t *io;
26371 	mblk_t *data_mp;
26372 	uint_t plen, overhead;
26373 	ip_stack_t	*ipst;
26374 
26375 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26376 		return;
26377 
26378 	if (ill == NULL)
26379 		return;
26380 	ipst = ill->ill_ipst;
26381 	/*
26382 	 * Destination address is a broadcast or multicast.  Punt.
26383 	 */
26384 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26385 	    IRE_LOCAL)))
26386 		return;
26387 
26388 	data_mp = ipsec_mp->b_cont;
26389 
26390 	if (ill->ill_isv6) {
26391 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26392 
26393 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26394 			return;
26395 
26396 		plen = ip6h->ip6_plen;
26397 	} else {
26398 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26399 
26400 		if (CLASSD(ipha->ipha_dst))
26401 			return;
26402 
26403 		plen = ipha->ipha_length;
26404 	}
26405 	/*
26406 	 * Is there a pending DLPI control message being exchanged
26407 	 * between IP/IPsec and the DLS Provider? If there is, it
26408 	 * could be a SADB update, and the state of the DLS Provider
26409 	 * SADB might not be in sync with the SADB maintained by
26410 	 * IPsec. To avoid dropping packets or using the wrong keying
26411 	 * material, we do not accelerate this packet.
26412 	 */
26413 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26414 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26415 		    "ill_dlpi_pending! don't accelerate packet\n"));
26416 		return;
26417 	}
26418 
26419 	/*
26420 	 * Is the Provider in promiscous mode? If it does, we don't
26421 	 * accelerate the packet since it will bounce back up to the
26422 	 * listeners in the clear.
26423 	 */
26424 	if (ill->ill_promisc_on_phys) {
26425 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26426 		    "ill in promiscous mode, don't accelerate packet\n"));
26427 		return;
26428 	}
26429 
26430 	/*
26431 	 * Will the packet require fragmentation?
26432 	 */
26433 
26434 	/*
26435 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26436 	 * as is used elsewhere.
26437 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26438 	 *	+ 2-byte trailer
26439 	 */
26440 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26441 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26442 
26443 	if ((plen + overhead) > ill->ill_max_mtu)
26444 		return;
26445 
26446 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26447 
26448 	/*
26449 	 * Can the ill accelerate this IPsec protocol and algorithm
26450 	 * specified by the SA?
26451 	 */
26452 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26453 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26454 		return;
26455 	}
26456 
26457 	/*
26458 	 * Tell AH or ESP that the outbound ill is capable of
26459 	 * accelerating this packet.
26460 	 */
26461 	io->ipsec_out_is_capab_ill = B_TRUE;
26462 }
26463 
26464 /*
26465  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26466  *
26467  * If this function returns B_TRUE, the requested SA's have been filled
26468  * into the ipsec_out_*_sa pointers.
26469  *
26470  * If the function returns B_FALSE, the packet has been "consumed", most
26471  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26472  *
26473  * The SA references created by the protocol-specific "select"
26474  * function will be released when the ipsec_mp is freed, thanks to the
26475  * ipsec_out_free destructor -- see spd.c.
26476  */
26477 static boolean_t
26478 ipsec_out_select_sa(mblk_t *ipsec_mp)
26479 {
26480 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26481 	ipsec_out_t *io;
26482 	ipsec_policy_t *pp;
26483 	ipsec_action_t *ap;
26484 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26485 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26486 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26487 
26488 	if (!io->ipsec_out_secure) {
26489 		/*
26490 		 * We came here by mistake.
26491 		 * Don't bother with ipsec processing
26492 		 * We should "discourage" this path in the future.
26493 		 */
26494 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26495 		return (B_FALSE);
26496 	}
26497 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26498 	ASSERT((io->ipsec_out_policy != NULL) ||
26499 	    (io->ipsec_out_act != NULL));
26500 
26501 	ASSERT(io->ipsec_out_failed == B_FALSE);
26502 
26503 	/*
26504 	 * IPsec processing has started.
26505 	 */
26506 	io->ipsec_out_proc_begin = B_TRUE;
26507 	ap = io->ipsec_out_act;
26508 	if (ap == NULL) {
26509 		pp = io->ipsec_out_policy;
26510 		ASSERT(pp != NULL);
26511 		ap = pp->ipsp_act;
26512 		ASSERT(ap != NULL);
26513 	}
26514 
26515 	/*
26516 	 * We have an action.  now, let's select SA's.
26517 	 * (In the future, we can cache this in the conn_t..)
26518 	 */
26519 	if (ap->ipa_want_esp) {
26520 		if (io->ipsec_out_esp_sa == NULL) {
26521 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26522 			    IPPROTO_ESP);
26523 		}
26524 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26525 	}
26526 
26527 	if (ap->ipa_want_ah) {
26528 		if (io->ipsec_out_ah_sa == NULL) {
26529 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26530 			    IPPROTO_AH);
26531 		}
26532 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26533 		/*
26534 		 * The ESP and AH processing order needs to be preserved
26535 		 * when both protocols are required (ESP should be applied
26536 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26537 		 * when both ESP and AH are required, and an AH ACQUIRE
26538 		 * is needed.
26539 		 */
26540 		if (ap->ipa_want_esp && need_ah_acquire)
26541 			need_esp_acquire = B_TRUE;
26542 	}
26543 
26544 	/*
26545 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26546 	 * Release SAs that got referenced, but will not be used until we
26547 	 * acquire _all_ of the SAs we need.
26548 	 */
26549 	if (need_ah_acquire || need_esp_acquire) {
26550 		if (io->ipsec_out_ah_sa != NULL) {
26551 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26552 			io->ipsec_out_ah_sa = NULL;
26553 		}
26554 		if (io->ipsec_out_esp_sa != NULL) {
26555 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26556 			io->ipsec_out_esp_sa = NULL;
26557 		}
26558 
26559 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26560 		return (B_FALSE);
26561 	}
26562 
26563 	return (B_TRUE);
26564 }
26565 
26566 /*
26567  * Process an IPSEC_OUT message and see what you can
26568  * do with it.
26569  * IPQoS Notes:
26570  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26571  * IPsec.
26572  * XXX would like to nuke ire_t.
26573  * XXX ill_index better be "real"
26574  */
26575 void
26576 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26577 {
26578 	ipsec_out_t *io;
26579 	ipsec_policy_t *pp;
26580 	ipsec_action_t *ap;
26581 	ipha_t *ipha;
26582 	ip6_t *ip6h;
26583 	mblk_t *mp;
26584 	ill_t *ill;
26585 	zoneid_t zoneid;
26586 	ipsec_status_t ipsec_rc;
26587 	boolean_t ill_need_rele = B_FALSE;
26588 	ip_stack_t	*ipst;
26589 	ipsec_stack_t	*ipss;
26590 
26591 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26592 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26593 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26594 	ipst = io->ipsec_out_ns->netstack_ip;
26595 	mp = ipsec_mp->b_cont;
26596 
26597 	/*
26598 	 * Initiate IPPF processing. We do it here to account for packets
26599 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26600 	 * We can check for ipsec_out_proc_begin even for such packets, as
26601 	 * they will always be false (asserted below).
26602 	 */
26603 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26604 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26605 		    io->ipsec_out_ill_index : ill_index);
26606 		if (mp == NULL) {
26607 			ip2dbg(("ipsec_out_process: packet dropped "\
26608 			    "during IPPF processing\n"));
26609 			freeb(ipsec_mp);
26610 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26611 			return;
26612 		}
26613 	}
26614 
26615 	if (!io->ipsec_out_secure) {
26616 		/*
26617 		 * We came here by mistake.
26618 		 * Don't bother with ipsec processing
26619 		 * Should "discourage" this path in the future.
26620 		 */
26621 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26622 		goto done;
26623 	}
26624 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26625 	ASSERT((io->ipsec_out_policy != NULL) ||
26626 	    (io->ipsec_out_act != NULL));
26627 	ASSERT(io->ipsec_out_failed == B_FALSE);
26628 
26629 	ipss = ipst->ips_netstack->netstack_ipsec;
26630 	if (!ipsec_loaded(ipss)) {
26631 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26632 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26633 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26634 		} else {
26635 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26636 		}
26637 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26638 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26639 		    &ipss->ipsec_dropper);
26640 		return;
26641 	}
26642 
26643 	/*
26644 	 * IPsec processing has started.
26645 	 */
26646 	io->ipsec_out_proc_begin = B_TRUE;
26647 	ap = io->ipsec_out_act;
26648 	if (ap == NULL) {
26649 		pp = io->ipsec_out_policy;
26650 		ASSERT(pp != NULL);
26651 		ap = pp->ipsp_act;
26652 		ASSERT(ap != NULL);
26653 	}
26654 
26655 	/*
26656 	 * Save the outbound ill index. When the packet comes back
26657 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26658 	 * before sending it the accelerated packet.
26659 	 */
26660 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26661 		ill = ire_to_ill(ire);
26662 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26663 	}
26664 
26665 	/*
26666 	 * The order of processing is first insert a IP header if needed.
26667 	 * Then insert the ESP header and then the AH header.
26668 	 */
26669 	if ((io->ipsec_out_se_done == B_FALSE) &&
26670 	    (ap->ipa_want_se)) {
26671 		/*
26672 		 * First get the outer IP header before sending
26673 		 * it to ESP.
26674 		 */
26675 		ipha_t *oipha, *iipha;
26676 		mblk_t *outer_mp, *inner_mp;
26677 
26678 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26679 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26680 			    "ipsec_out_process: "
26681 			    "Self-Encapsulation failed: Out of memory\n");
26682 			freemsg(ipsec_mp);
26683 			if (ill != NULL) {
26684 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26685 			} else {
26686 				BUMP_MIB(&ipst->ips_ip_mib,
26687 				    ipIfStatsOutDiscards);
26688 			}
26689 			return;
26690 		}
26691 		inner_mp = ipsec_mp->b_cont;
26692 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26693 		oipha = (ipha_t *)outer_mp->b_rptr;
26694 		iipha = (ipha_t *)inner_mp->b_rptr;
26695 		*oipha = *iipha;
26696 		outer_mp->b_wptr += sizeof (ipha_t);
26697 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26698 		    sizeof (ipha_t));
26699 		oipha->ipha_protocol = IPPROTO_ENCAP;
26700 		oipha->ipha_version_and_hdr_length =
26701 		    IP_SIMPLE_HDR_VERSION;
26702 		oipha->ipha_hdr_checksum = 0;
26703 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26704 		outer_mp->b_cont = inner_mp;
26705 		ipsec_mp->b_cont = outer_mp;
26706 
26707 		io->ipsec_out_se_done = B_TRUE;
26708 		io->ipsec_out_tunnel = B_TRUE;
26709 	}
26710 
26711 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26712 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26713 	    !ipsec_out_select_sa(ipsec_mp))
26714 		return;
26715 
26716 	/*
26717 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26718 	 * to do the heavy lifting.
26719 	 */
26720 	zoneid = io->ipsec_out_zoneid;
26721 	ASSERT(zoneid != ALL_ZONES);
26722 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26723 		ASSERT(io->ipsec_out_esp_sa != NULL);
26724 		io->ipsec_out_esp_done = B_TRUE;
26725 		/*
26726 		 * Note that since hw accel can only apply one transform,
26727 		 * not two, we skip hw accel for ESP if we also have AH
26728 		 * This is an design limitation of the interface
26729 		 * which should be revisited.
26730 		 */
26731 		ASSERT(ire != NULL);
26732 		if (io->ipsec_out_ah_sa == NULL) {
26733 			ill = (ill_t *)ire->ire_stq->q_ptr;
26734 			ipsec_out_is_accelerated(ipsec_mp,
26735 			    io->ipsec_out_esp_sa, ill, ire);
26736 		}
26737 
26738 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26739 		switch (ipsec_rc) {
26740 		case IPSEC_STATUS_SUCCESS:
26741 			break;
26742 		case IPSEC_STATUS_FAILED:
26743 			if (ill != NULL) {
26744 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26745 			} else {
26746 				BUMP_MIB(&ipst->ips_ip_mib,
26747 				    ipIfStatsOutDiscards);
26748 			}
26749 			/* FALLTHRU */
26750 		case IPSEC_STATUS_PENDING:
26751 			return;
26752 		}
26753 	}
26754 
26755 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26756 		ASSERT(io->ipsec_out_ah_sa != NULL);
26757 		io->ipsec_out_ah_done = B_TRUE;
26758 		if (ire == NULL) {
26759 			int idx = io->ipsec_out_capab_ill_index;
26760 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26761 			    NULL, NULL, NULL, NULL, ipst);
26762 			ill_need_rele = B_TRUE;
26763 		} else {
26764 			ill = (ill_t *)ire->ire_stq->q_ptr;
26765 		}
26766 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26767 		    ire);
26768 
26769 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26770 		switch (ipsec_rc) {
26771 		case IPSEC_STATUS_SUCCESS:
26772 			break;
26773 		case IPSEC_STATUS_FAILED:
26774 			if (ill != NULL) {
26775 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26776 			} else {
26777 				BUMP_MIB(&ipst->ips_ip_mib,
26778 				    ipIfStatsOutDiscards);
26779 			}
26780 			/* FALLTHRU */
26781 		case IPSEC_STATUS_PENDING:
26782 			if (ill != NULL && ill_need_rele)
26783 				ill_refrele(ill);
26784 			return;
26785 		}
26786 	}
26787 	/*
26788 	 * We are done with IPsec processing. Send it over the wire.
26789 	 */
26790 done:
26791 	mp = ipsec_mp->b_cont;
26792 	ipha = (ipha_t *)mp->b_rptr;
26793 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26794 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26795 		    ire);
26796 	} else {
26797 		ip6h = (ip6_t *)ipha;
26798 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26799 		    ire);
26800 	}
26801 	if (ill != NULL && ill_need_rele)
26802 		ill_refrele(ill);
26803 }
26804 
26805 /* ARGSUSED */
26806 void
26807 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26808 {
26809 	opt_restart_t	*or;
26810 	int	err;
26811 	conn_t	*connp;
26812 	cred_t	*cr;
26813 
26814 	ASSERT(CONN_Q(q));
26815 	connp = Q_TO_CONN(q);
26816 
26817 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26818 	or = (opt_restart_t *)first_mp->b_rptr;
26819 	/*
26820 	 * We checked for a db_credp the first time svr4_optcom_req
26821 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26822 	 */
26823 	cr = msg_getcred(first_mp, NULL);
26824 	ASSERT(cr != NULL);
26825 
26826 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26827 		err = svr4_optcom_req(q, first_mp, cr,
26828 		    &ip_opt_obj, B_FALSE);
26829 	} else {
26830 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26831 		err = tpi_optcom_req(q, first_mp, cr,
26832 		    &ip_opt_obj, B_FALSE);
26833 	}
26834 	if (err != EINPROGRESS) {
26835 		/* operation is done */
26836 		CONN_OPER_PENDING_DONE(connp);
26837 	}
26838 }
26839 
26840 /*
26841  * ioctls that go through a down/up sequence may need to wait for the down
26842  * to complete. This involves waiting for the ire and ipif refcnts to go down
26843  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26844  */
26845 /* ARGSUSED */
26846 void
26847 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26848 {
26849 	struct iocblk *iocp;
26850 	mblk_t *mp1;
26851 	ip_ioctl_cmd_t *ipip;
26852 	int err;
26853 	sin_t	*sin;
26854 	struct lifreq *lifr;
26855 	struct ifreq *ifr;
26856 
26857 	iocp = (struct iocblk *)mp->b_rptr;
26858 	ASSERT(ipsq != NULL);
26859 	/* Existence of mp1 verified in ip_wput_nondata */
26860 	mp1 = mp->b_cont->b_cont;
26861 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26862 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26863 		/*
26864 		 * Special case where ipx_current_ipif is not set:
26865 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26866 		 * We are here as were not able to complete the operation in
26867 		 * ipif_set_values because we could not become exclusive on
26868 		 * the new ipsq.
26869 		 */
26870 		ill_t *ill = q->q_ptr;
26871 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26872 	}
26873 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26874 
26875 	if (ipip->ipi_cmd_type == IF_CMD) {
26876 		/* This a old style SIOC[GS]IF* command */
26877 		ifr = (struct ifreq *)mp1->b_rptr;
26878 		sin = (sin_t *)&ifr->ifr_addr;
26879 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26880 		/* This a new style SIOC[GS]LIF* command */
26881 		lifr = (struct lifreq *)mp1->b_rptr;
26882 		sin = (sin_t *)&lifr->lifr_addr;
26883 	} else {
26884 		sin = NULL;
26885 	}
26886 
26887 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26888 	    q, mp, ipip, mp1->b_rptr);
26889 
26890 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26891 }
26892 
26893 /*
26894  * ioctl processing
26895  *
26896  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26897  * the ioctl command in the ioctl tables, determines the copyin data size
26898  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26899  *
26900  * ioctl processing then continues when the M_IOCDATA makes its way down to
26901  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26902  * associated 'conn' is refheld till the end of the ioctl and the general
26903  * ioctl processing function ip_process_ioctl() is called to extract the
26904  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26905  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26906  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26907  * is used to extract the ioctl's arguments.
26908  *
26909  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26910  * so goes thru the serialization primitive ipsq_try_enter. Then the
26911  * appropriate function to handle the ioctl is called based on the entry in
26912  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26913  * which also refreleases the 'conn' that was refheld at the start of the
26914  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26915  *
26916  * Many exclusive ioctls go thru an internal down up sequence as part of
26917  * the operation. For example an attempt to change the IP address of an
26918  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26919  * does all the cleanup such as deleting all ires that use this address.
26920  * Then we need to wait till all references to the interface go away.
26921  */
26922 void
26923 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26924 {
26925 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26926 	ip_ioctl_cmd_t *ipip = arg;
26927 	ip_extract_func_t *extract_funcp;
26928 	cmd_info_t ci;
26929 	int err;
26930 	boolean_t entered_ipsq = B_FALSE;
26931 
26932 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26933 
26934 	if (ipip == NULL)
26935 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26936 
26937 	/*
26938 	 * SIOCLIFADDIF needs to go thru a special path since the
26939 	 * ill may not exist yet. This happens in the case of lo0
26940 	 * which is created using this ioctl.
26941 	 */
26942 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26943 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26944 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26945 		return;
26946 	}
26947 
26948 	ci.ci_ipif = NULL;
26949 	if (ipip->ipi_cmd_type == MISC_CMD) {
26950 		/*
26951 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26952 		 */
26953 		if (ipip->ipi_cmd == IF_UNITSEL) {
26954 			/* ioctl comes down the ill */
26955 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26956 			ipif_refhold(ci.ci_ipif);
26957 		}
26958 		err = 0;
26959 		ci.ci_sin = NULL;
26960 		ci.ci_sin6 = NULL;
26961 		ci.ci_lifr = NULL;
26962 	} else {
26963 		switch (ipip->ipi_cmd_type) {
26964 		case IF_CMD:
26965 		case LIF_CMD:
26966 			extract_funcp = ip_extract_lifreq;
26967 			break;
26968 
26969 		case ARP_CMD:
26970 		case XARP_CMD:
26971 			extract_funcp = ip_extract_arpreq;
26972 			break;
26973 
26974 		case TUN_CMD:
26975 			extract_funcp = ip_extract_tunreq;
26976 			break;
26977 
26978 		case MSFILT_CMD:
26979 			extract_funcp = ip_extract_msfilter;
26980 			break;
26981 
26982 		default:
26983 			ASSERT(0);
26984 		}
26985 
26986 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26987 		if (err != 0) {
26988 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26989 			return;
26990 		}
26991 
26992 		/*
26993 		 * All of the extraction functions return a refheld ipif.
26994 		 */
26995 		ASSERT(ci.ci_ipif != NULL);
26996 	}
26997 
26998 	if (!(ipip->ipi_flags & IPI_WR)) {
26999 		/*
27000 		 * A return value of EINPROGRESS means the ioctl is
27001 		 * either queued and waiting for some reason or has
27002 		 * already completed.
27003 		 */
27004 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27005 		    ci.ci_lifr);
27006 		if (ci.ci_ipif != NULL)
27007 			ipif_refrele(ci.ci_ipif);
27008 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27009 		return;
27010 	}
27011 
27012 	ASSERT(ci.ci_ipif != NULL);
27013 
27014 	/*
27015 	 * If ipsq is non-NULL, we are already being called exclusively.
27016 	 */
27017 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27018 	if (ipsq == NULL) {
27019 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27020 		    NEW_OP, B_TRUE);
27021 		if (ipsq == NULL) {
27022 			ipif_refrele(ci.ci_ipif);
27023 			return;
27024 		}
27025 		entered_ipsq = B_TRUE;
27026 	}
27027 
27028 	/*
27029 	 * Release the ipif so that ipif_down and friends that wait for
27030 	 * references to go away are not misled about the current ipif_refcnt
27031 	 * values. We are writer so we can access the ipif even after releasing
27032 	 * the ipif.
27033 	 */
27034 	ipif_refrele(ci.ci_ipif);
27035 
27036 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27037 
27038 	/*
27039 	 * A return value of EINPROGRESS means the ioctl is
27040 	 * either queued and waiting for some reason or has
27041 	 * already completed.
27042 	 */
27043 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27044 
27045 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27046 
27047 	if (entered_ipsq)
27048 		ipsq_exit(ipsq);
27049 }
27050 
27051 /*
27052  * Complete the ioctl. Typically ioctls use the mi package and need to
27053  * do mi_copyout/mi_copy_done.
27054  */
27055 void
27056 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27057 {
27058 	conn_t	*connp = NULL;
27059 
27060 	if (err == EINPROGRESS)
27061 		return;
27062 
27063 	if (CONN_Q(q)) {
27064 		connp = Q_TO_CONN(q);
27065 		ASSERT(connp->conn_ref >= 2);
27066 	}
27067 
27068 	switch (mode) {
27069 	case COPYOUT:
27070 		if (err == 0)
27071 			mi_copyout(q, mp);
27072 		else
27073 			mi_copy_done(q, mp, err);
27074 		break;
27075 
27076 	case NO_COPYOUT:
27077 		mi_copy_done(q, mp, err);
27078 		break;
27079 
27080 	default:
27081 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27082 		break;
27083 	}
27084 
27085 	/*
27086 	 * The refhold placed at the start of the ioctl is released here.
27087 	 */
27088 	if (connp != NULL)
27089 		CONN_OPER_PENDING_DONE(connp);
27090 
27091 	if (ipsq != NULL)
27092 		ipsq_current_finish(ipsq);
27093 }
27094 
27095 /* Called from ip_wput for all non data messages */
27096 /* ARGSUSED */
27097 void
27098 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27099 {
27100 	mblk_t		*mp1;
27101 	ire_t		*ire, *fake_ire;
27102 	ill_t		*ill;
27103 	struct iocblk	*iocp;
27104 	ip_ioctl_cmd_t	*ipip;
27105 	cred_t		*cr;
27106 	conn_t		*connp;
27107 	int		err;
27108 	nce_t		*nce;
27109 	ipif_t		*ipif;
27110 	ip_stack_t	*ipst;
27111 	char		*proto_str;
27112 
27113 	if (CONN_Q(q)) {
27114 		connp = Q_TO_CONN(q);
27115 		ipst = connp->conn_netstack->netstack_ip;
27116 	} else {
27117 		connp = NULL;
27118 		ipst = ILLQ_TO_IPST(q);
27119 	}
27120 
27121 	switch (DB_TYPE(mp)) {
27122 	case M_IOCTL:
27123 		/*
27124 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27125 		 * will arrange to copy in associated control structures.
27126 		 */
27127 		ip_sioctl_copyin_setup(q, mp);
27128 		return;
27129 	case M_IOCDATA:
27130 		/*
27131 		 * Ensure that this is associated with one of our trans-
27132 		 * parent ioctls.  If it's not ours, discard it if we're
27133 		 * running as a driver, or pass it on if we're a module.
27134 		 */
27135 		iocp = (struct iocblk *)mp->b_rptr;
27136 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27137 		if (ipip == NULL) {
27138 			if (q->q_next == NULL) {
27139 				goto nak;
27140 			} else {
27141 				putnext(q, mp);
27142 			}
27143 			return;
27144 		}
27145 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27146 			/*
27147 			 * the ioctl is one we recognise, but is not
27148 			 * consumed by IP as a module, pass M_IOCDATA
27149 			 * for processing downstream, but only for
27150 			 * common Streams ioctls.
27151 			 */
27152 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27153 				putnext(q, mp);
27154 				return;
27155 			} else {
27156 				goto nak;
27157 			}
27158 		}
27159 
27160 		/* IOCTL continuation following copyin or copyout. */
27161 		if (mi_copy_state(q, mp, NULL) == -1) {
27162 			/*
27163 			 * The copy operation failed.  mi_copy_state already
27164 			 * cleaned up, so we're out of here.
27165 			 */
27166 			return;
27167 		}
27168 		/*
27169 		 * If we just completed a copy in, we become writer and
27170 		 * continue processing in ip_sioctl_copyin_done.  If it
27171 		 * was a copy out, we call mi_copyout again.  If there is
27172 		 * nothing more to copy out, it will complete the IOCTL.
27173 		 */
27174 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27175 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27176 				mi_copy_done(q, mp, EPROTO);
27177 				return;
27178 			}
27179 			/*
27180 			 * Check for cases that need more copying.  A return
27181 			 * value of 0 means a second copyin has been started,
27182 			 * so we return; a return value of 1 means no more
27183 			 * copying is needed, so we continue.
27184 			 */
27185 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27186 			    MI_COPY_COUNT(mp) == 1) {
27187 				if (ip_copyin_msfilter(q, mp) == 0)
27188 					return;
27189 			}
27190 			/*
27191 			 * Refhold the conn, till the ioctl completes. This is
27192 			 * needed in case the ioctl ends up in the pending mp
27193 			 * list. Every mp in the ill_pending_mp list and
27194 			 * the ipx_pending_mp must have a refhold on the conn
27195 			 * to resume processing. The refhold is released when
27196 			 * the ioctl completes. (normally or abnormally)
27197 			 * In all cases ip_ioctl_finish is called to finish
27198 			 * the ioctl.
27199 			 */
27200 			if (connp != NULL) {
27201 				/* This is not a reentry */
27202 				ASSERT(ipsq == NULL);
27203 				CONN_INC_REF(connp);
27204 			} else {
27205 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27206 					mi_copy_done(q, mp, EINVAL);
27207 					return;
27208 				}
27209 			}
27210 
27211 			ip_process_ioctl(ipsq, q, mp, ipip);
27212 
27213 		} else {
27214 			mi_copyout(q, mp);
27215 		}
27216 		return;
27217 nak:
27218 		iocp->ioc_error = EINVAL;
27219 		mp->b_datap->db_type = M_IOCNAK;
27220 		iocp->ioc_count = 0;
27221 		qreply(q, mp);
27222 		return;
27223 
27224 	case M_IOCNAK:
27225 		/*
27226 		 * The only way we could get here is if a resolver didn't like
27227 		 * an IOCTL we sent it.	 This shouldn't happen.
27228 		 */
27229 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27230 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27231 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27232 		freemsg(mp);
27233 		return;
27234 	case M_IOCACK:
27235 		/* /dev/ip shouldn't see this */
27236 		if (CONN_Q(q))
27237 			goto nak;
27238 
27239 		/*
27240 		 * Finish socket ioctls passed through to ARP.  We use the
27241 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27242 		 * we need to become writer before calling ip_sioctl_iocack().
27243 		 * Note that qwriter_ip() will release the refhold, and that a
27244 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27245 		 * ill stream.
27246 		 */
27247 		iocp = (struct iocblk *)mp->b_rptr;
27248 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27249 			ip_sioctl_iocack(NULL, q, mp, NULL);
27250 			return;
27251 		}
27252 
27253 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27254 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27255 		ill = q->q_ptr;
27256 		ill_refhold(ill);
27257 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27258 		return;
27259 	case M_FLUSH:
27260 		if (*mp->b_rptr & FLUSHW)
27261 			flushq(q, FLUSHALL);
27262 		if (q->q_next) {
27263 			putnext(q, mp);
27264 			return;
27265 		}
27266 		if (*mp->b_rptr & FLUSHR) {
27267 			*mp->b_rptr &= ~FLUSHW;
27268 			qreply(q, mp);
27269 			return;
27270 		}
27271 		freemsg(mp);
27272 		return;
27273 	case IRE_DB_REQ_TYPE:
27274 		if (connp == NULL) {
27275 			proto_str = "IRE_DB_REQ_TYPE";
27276 			goto protonak;
27277 		}
27278 		/* An Upper Level Protocol wants a copy of an IRE. */
27279 		ip_ire_req(q, mp);
27280 		return;
27281 	case M_CTL:
27282 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27283 			break;
27284 
27285 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27286 		    TUN_HELLO) {
27287 			ASSERT(connp != NULL);
27288 			connp->conn_flags |= IPCL_IPTUN;
27289 			freeb(mp);
27290 			return;
27291 		}
27292 
27293 		/* M_CTL messages are used by ARP to tell us things. */
27294 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27295 			break;
27296 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27297 		case AR_ENTRY_SQUERY:
27298 			putnext(q, mp);
27299 			return;
27300 		case AR_CLIENT_NOTIFY:
27301 			ip_arp_news(q, mp);
27302 			return;
27303 		case AR_DLPIOP_DONE:
27304 			ASSERT(q->q_next != NULL);
27305 			ill = (ill_t *)q->q_ptr;
27306 			/* qwriter_ip releases the refhold */
27307 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27308 			ill_refhold(ill);
27309 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27310 			return;
27311 		case AR_ARP_CLOSING:
27312 			/*
27313 			 * ARP (above us) is closing. If no ARP bringup is
27314 			 * currently pending, ack the message so that ARP
27315 			 * can complete its close. Also mark ill_arp_closing
27316 			 * so that new ARP bringups will fail. If any
27317 			 * ARP bringup is currently in progress, we will
27318 			 * ack this when the current ARP bringup completes.
27319 			 */
27320 			ASSERT(q->q_next != NULL);
27321 			ill = (ill_t *)q->q_ptr;
27322 			mutex_enter(&ill->ill_lock);
27323 			ill->ill_arp_closing = 1;
27324 			if (!ill->ill_arp_bringup_pending) {
27325 				mutex_exit(&ill->ill_lock);
27326 				qreply(q, mp);
27327 			} else {
27328 				mutex_exit(&ill->ill_lock);
27329 				freemsg(mp);
27330 			}
27331 			return;
27332 		case AR_ARP_EXTEND:
27333 			/*
27334 			 * The ARP module above us is capable of duplicate
27335 			 * address detection.  Old ATM drivers will not send
27336 			 * this message.
27337 			 */
27338 			ASSERT(q->q_next != NULL);
27339 			ill = (ill_t *)q->q_ptr;
27340 			ill->ill_arp_extend = B_TRUE;
27341 			freemsg(mp);
27342 			return;
27343 		default:
27344 			break;
27345 		}
27346 		break;
27347 	case M_PROTO:
27348 	case M_PCPROTO:
27349 		/*
27350 		 * The only PROTO messages we expect are copies of option
27351 		 * negotiation acknowledgements, AH and ESP bind requests
27352 		 * are also expected.
27353 		 */
27354 		switch (((union T_primitives *)mp->b_rptr)->type) {
27355 		case O_T_BIND_REQ:
27356 		case T_BIND_REQ: {
27357 			/* Request can get queued in bind */
27358 			if (connp == NULL) {
27359 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27360 				goto protonak;
27361 			}
27362 			/*
27363 			 * The transports except SCTP call ip_bind_{v4,v6}()
27364 			 * directly instead of a a putnext. SCTP doesn't
27365 			 * generate any T_BIND_REQ since it has its own
27366 			 * fanout data structures. However, ESP and AH
27367 			 * come in for regular binds; all other cases are
27368 			 * bind retries.
27369 			 */
27370 			ASSERT(!IPCL_IS_SCTP(connp));
27371 
27372 			/* Don't increment refcnt if this is a re-entry */
27373 			if (ipsq == NULL)
27374 				CONN_INC_REF(connp);
27375 
27376 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27377 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27378 			ASSERT(mp != NULL);
27379 
27380 			ASSERT(!IPCL_IS_TCP(connp));
27381 			ASSERT(!IPCL_IS_UDP(connp));
27382 			ASSERT(!IPCL_IS_RAWIP(connp));
27383 
27384 			/* The case of AH and ESP */
27385 			qreply(q, mp);
27386 			CONN_OPER_PENDING_DONE(connp);
27387 			return;
27388 		}
27389 		case T_SVR4_OPTMGMT_REQ:
27390 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27391 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27392 
27393 			if (connp == NULL) {
27394 				proto_str = "T_SVR4_OPTMGMT_REQ";
27395 				goto protonak;
27396 			}
27397 
27398 			/*
27399 			 * All Solaris components should pass a db_credp
27400 			 * for this TPI message, hence we ASSERT.
27401 			 * But in case there is some other M_PROTO that looks
27402 			 * like a TPI message sent by some other kernel
27403 			 * component, we check and return an error.
27404 			 */
27405 			cr = msg_getcred(mp, NULL);
27406 			ASSERT(cr != NULL);
27407 			if (cr == NULL) {
27408 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27409 				if (mp != NULL)
27410 					qreply(q, mp);
27411 				return;
27412 			}
27413 
27414 			if (!snmpcom_req(q, mp, ip_snmp_set,
27415 			    ip_snmp_get, cr)) {
27416 				/*
27417 				 * Call svr4_optcom_req so that it can
27418 				 * generate the ack. We don't come here
27419 				 * if this operation is being restarted.
27420 				 * ip_restart_optmgmt will drop the conn ref.
27421 				 * In the case of ipsec option after the ipsec
27422 				 * load is complete conn_restart_ipsec_waiter
27423 				 * drops the conn ref.
27424 				 */
27425 				ASSERT(ipsq == NULL);
27426 				CONN_INC_REF(connp);
27427 				if (ip_check_for_ipsec_opt(q, mp))
27428 					return;
27429 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27430 				    B_FALSE);
27431 				if (err != EINPROGRESS) {
27432 					/* Operation is done */
27433 					CONN_OPER_PENDING_DONE(connp);
27434 				}
27435 			}
27436 			return;
27437 		case T_OPTMGMT_REQ:
27438 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27439 			/*
27440 			 * Note: No snmpcom_req support through new
27441 			 * T_OPTMGMT_REQ.
27442 			 * Call tpi_optcom_req so that it can
27443 			 * generate the ack.
27444 			 */
27445 			if (connp == NULL) {
27446 				proto_str = "T_OPTMGMT_REQ";
27447 				goto protonak;
27448 			}
27449 
27450 			/*
27451 			 * All Solaris components should pass a db_credp
27452 			 * for this TPI message, hence we ASSERT.
27453 			 * But in case there is some other M_PROTO that looks
27454 			 * like a TPI message sent by some other kernel
27455 			 * component, we check and return an error.
27456 			 */
27457 			cr = msg_getcred(mp, NULL);
27458 			ASSERT(cr != NULL);
27459 			if (cr == NULL) {
27460 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27461 				if (mp != NULL)
27462 					qreply(q, mp);
27463 				return;
27464 			}
27465 			ASSERT(ipsq == NULL);
27466 			/*
27467 			 * We don't come here for restart. ip_restart_optmgmt
27468 			 * will drop the conn ref. In the case of ipsec option
27469 			 * after the ipsec load is complete
27470 			 * conn_restart_ipsec_waiter drops the conn ref.
27471 			 */
27472 			CONN_INC_REF(connp);
27473 			if (ip_check_for_ipsec_opt(q, mp))
27474 				return;
27475 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27476 			if (err != EINPROGRESS) {
27477 				/* Operation is done */
27478 				CONN_OPER_PENDING_DONE(connp);
27479 			}
27480 			return;
27481 		case T_UNBIND_REQ:
27482 			if (connp == NULL) {
27483 				proto_str = "T_UNBIND_REQ";
27484 				goto protonak;
27485 			}
27486 			ip_unbind(Q_TO_CONN(q));
27487 			mp = mi_tpi_ok_ack_alloc(mp);
27488 			qreply(q, mp);
27489 			return;
27490 		default:
27491 			/*
27492 			 * Have to drop any DLPI messages coming down from
27493 			 * arp (such as an info_req which would cause ip
27494 			 * to receive an extra info_ack if it was passed
27495 			 * through.
27496 			 */
27497 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27498 			    (int)*(uint_t *)mp->b_rptr));
27499 			freemsg(mp);
27500 			return;
27501 		}
27502 		/* NOTREACHED */
27503 	case IRE_DB_TYPE: {
27504 		nce_t		*nce;
27505 		ill_t		*ill;
27506 		in6_addr_t	gw_addr_v6;
27507 
27508 		/*
27509 		 * This is a response back from a resolver.  It
27510 		 * consists of a message chain containing:
27511 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27512 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27513 		 * The LL_HDR_MBLK is the DLPI header to use to get
27514 		 * the attached packet, and subsequent ones for the
27515 		 * same destination, transmitted.
27516 		 */
27517 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27518 			break;
27519 		/*
27520 		 * First, check to make sure the resolution succeeded.
27521 		 * If it failed, the second mblk will be empty.
27522 		 * If it is, free the chain, dropping the packet.
27523 		 * (We must ire_delete the ire; that frees the ire mblk)
27524 		 * We're doing this now to support PVCs for ATM; it's
27525 		 * a partial xresolv implementation. When we fully implement
27526 		 * xresolv interfaces, instead of freeing everything here
27527 		 * we'll initiate neighbor discovery.
27528 		 *
27529 		 * For v4 (ARP and other external resolvers) the resolver
27530 		 * frees the message, so no check is needed. This check
27531 		 * is required, though, for a full xresolve implementation.
27532 		 * Including this code here now both shows how external
27533 		 * resolvers can NACK a resolution request using an
27534 		 * existing design that has no specific provisions for NACKs,
27535 		 * and also takes into account that the current non-ARP
27536 		 * external resolver has been coded to use this method of
27537 		 * NACKing for all IPv6 (xresolv) cases,
27538 		 * whether our xresolv implementation is complete or not.
27539 		 *
27540 		 */
27541 		ire = (ire_t *)mp->b_rptr;
27542 		ill = ire_to_ill(ire);
27543 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27544 		if (mp1->b_rptr == mp1->b_wptr) {
27545 			if (ire->ire_ipversion == IPV6_VERSION) {
27546 				/*
27547 				 * XRESOLV interface.
27548 				 */
27549 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27550 				mutex_enter(&ire->ire_lock);
27551 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27552 				mutex_exit(&ire->ire_lock);
27553 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27554 					nce = ndp_lookup_v6(ill, B_FALSE,
27555 					    &ire->ire_addr_v6, B_FALSE);
27556 				} else {
27557 					nce = ndp_lookup_v6(ill, B_FALSE,
27558 					    &gw_addr_v6, B_FALSE);
27559 				}
27560 				if (nce != NULL) {
27561 					nce_resolv_failed(nce);
27562 					ndp_delete(nce);
27563 					NCE_REFRELE(nce);
27564 				}
27565 			}
27566 			mp->b_cont = NULL;
27567 			freemsg(mp1);		/* frees the pkt as well */
27568 			ASSERT(ire->ire_nce == NULL);
27569 			ire_delete((ire_t *)mp->b_rptr);
27570 			return;
27571 		}
27572 
27573 		/*
27574 		 * Split them into IRE_MBLK and pkt and feed it into
27575 		 * ire_add_then_send. Then in ire_add_then_send
27576 		 * the IRE will be added, and then the packet will be
27577 		 * run back through ip_wput. This time it will make
27578 		 * it to the wire.
27579 		 */
27580 		mp->b_cont = NULL;
27581 		mp = mp1->b_cont;		/* now, mp points to pkt */
27582 		mp1->b_cont = NULL;
27583 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27584 		if (ire->ire_ipversion == IPV6_VERSION) {
27585 			/*
27586 			 * XRESOLV interface. Find the nce and put a copy
27587 			 * of the dl_unitdata_req in nce_res_mp
27588 			 */
27589 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27590 			mutex_enter(&ire->ire_lock);
27591 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27592 			mutex_exit(&ire->ire_lock);
27593 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27594 				nce = ndp_lookup_v6(ill, B_FALSE,
27595 				    &ire->ire_addr_v6, B_FALSE);
27596 			} else {
27597 				nce = ndp_lookup_v6(ill, B_FALSE,
27598 				    &gw_addr_v6, B_FALSE);
27599 			}
27600 			if (nce != NULL) {
27601 				/*
27602 				 * We have to protect nce_res_mp here
27603 				 * from being accessed by other threads
27604 				 * while we change the mblk pointer.
27605 				 * Other functions will also lock the nce when
27606 				 * accessing nce_res_mp.
27607 				 *
27608 				 * The reason we change the mblk pointer
27609 				 * here rather than copying the resolved address
27610 				 * into the template is that, unlike with
27611 				 * ethernet, we have no guarantee that the
27612 				 * resolved address length will be
27613 				 * smaller than or equal to the lla length
27614 				 * with which the template was allocated,
27615 				 * (for ethernet, they're equal)
27616 				 * so we have to use the actual resolved
27617 				 * address mblk - which holds the real
27618 				 * dl_unitdata_req with the resolved address.
27619 				 *
27620 				 * Doing this is the same behavior as was
27621 				 * previously used in the v4 ARP case.
27622 				 */
27623 				mutex_enter(&nce->nce_lock);
27624 				if (nce->nce_res_mp != NULL)
27625 					freemsg(nce->nce_res_mp);
27626 				nce->nce_res_mp = mp1;
27627 				mutex_exit(&nce->nce_lock);
27628 				/*
27629 				 * We do a fastpath probe here because
27630 				 * we have resolved the address without
27631 				 * using Neighbor Discovery.
27632 				 * In the non-XRESOLV v6 case, the fastpath
27633 				 * probe is done right after neighbor
27634 				 * discovery completes.
27635 				 */
27636 				if (nce->nce_res_mp != NULL) {
27637 					int res;
27638 					nce_fastpath_list_add(nce);
27639 					res = ill_fastpath_probe(ill,
27640 					    nce->nce_res_mp);
27641 					if (res != 0 && res != EAGAIN)
27642 						nce_fastpath_list_delete(nce);
27643 				}
27644 
27645 				ire_add_then_send(q, ire, mp);
27646 				/*
27647 				 * Now we have to clean out any packets
27648 				 * that may have been queued on the nce
27649 				 * while it was waiting for address resolution
27650 				 * to complete.
27651 				 */
27652 				mutex_enter(&nce->nce_lock);
27653 				mp1 = nce->nce_qd_mp;
27654 				nce->nce_qd_mp = NULL;
27655 				mutex_exit(&nce->nce_lock);
27656 				while (mp1 != NULL) {
27657 					mblk_t *nxt_mp;
27658 					queue_t *fwdq = NULL;
27659 					ill_t   *inbound_ill;
27660 					uint_t ifindex;
27661 
27662 					nxt_mp = mp1->b_next;
27663 					mp1->b_next = NULL;
27664 					/*
27665 					 * Retrieve ifindex stored in
27666 					 * ip_rput_data_v6()
27667 					 */
27668 					ifindex =
27669 					    (uint_t)(uintptr_t)mp1->b_prev;
27670 					inbound_ill =
27671 					    ill_lookup_on_ifindex(ifindex,
27672 					    B_TRUE, NULL, NULL, NULL,
27673 					    NULL, ipst);
27674 					mp1->b_prev = NULL;
27675 					if (inbound_ill != NULL)
27676 						fwdq = inbound_ill->ill_rq;
27677 
27678 					if (fwdq != NULL) {
27679 						put(fwdq, mp1);
27680 						ill_refrele(inbound_ill);
27681 					} else
27682 						put(WR(ill->ill_rq), mp1);
27683 					mp1 = nxt_mp;
27684 				}
27685 				NCE_REFRELE(nce);
27686 			} else {	/* nce is NULL; clean up */
27687 				ire_delete(ire);
27688 				freemsg(mp);
27689 				freemsg(mp1);
27690 				return;
27691 			}
27692 		} else {
27693 			nce_t *arpce;
27694 			/*
27695 			 * Link layer resolution succeeded. Recompute the
27696 			 * ire_nce.
27697 			 */
27698 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27699 			if ((arpce = ndp_lookup_v4(ill,
27700 			    (ire->ire_gateway_addr != INADDR_ANY ?
27701 			    &ire->ire_gateway_addr : &ire->ire_addr),
27702 			    B_FALSE)) == NULL) {
27703 				freeb(ire->ire_mp);
27704 				freeb(mp1);
27705 				freemsg(mp);
27706 				return;
27707 			}
27708 			mutex_enter(&arpce->nce_lock);
27709 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27710 			if (arpce->nce_state == ND_REACHABLE) {
27711 				/*
27712 				 * Someone resolved this before us;
27713 				 * cleanup the res_mp. Since ire has
27714 				 * not been added yet, the call to ire_add_v4
27715 				 * from ire_add_then_send (when a dup is
27716 				 * detected) will clean up the ire.
27717 				 */
27718 				freeb(mp1);
27719 			} else {
27720 				ASSERT(arpce->nce_res_mp == NULL);
27721 				arpce->nce_res_mp = mp1;
27722 				arpce->nce_state = ND_REACHABLE;
27723 			}
27724 			mutex_exit(&arpce->nce_lock);
27725 			if (ire->ire_marks & IRE_MARK_NOADD) {
27726 				/*
27727 				 * this ire will not be added to the ire
27728 				 * cache table, so we can set the ire_nce
27729 				 * here, as there are no atomicity constraints.
27730 				 */
27731 				ire->ire_nce = arpce;
27732 				/*
27733 				 * We are associating this nce with the ire
27734 				 * so change the nce ref taken in
27735 				 * ndp_lookup_v4() from
27736 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27737 				 */
27738 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27739 			} else {
27740 				NCE_REFRELE(arpce);
27741 			}
27742 			ire_add_then_send(q, ire, mp);
27743 		}
27744 		return;	/* All is well, the packet has been sent. */
27745 	}
27746 	case IRE_ARPRESOLVE_TYPE: {
27747 
27748 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27749 			break;
27750 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27751 		mp->b_cont = NULL;
27752 		/*
27753 		 * First, check to make sure the resolution succeeded.
27754 		 * If it failed, the second mblk will be empty.
27755 		 */
27756 		if (mp1->b_rptr == mp1->b_wptr) {
27757 			/* cleanup  the incomplete ire, free queued packets */
27758 			freemsg(mp); /* fake ire */
27759 			freeb(mp1);  /* dl_unitdata response */
27760 			return;
27761 		}
27762 
27763 		/*
27764 		 * Update any incomplete nce_t found. We search the ctable
27765 		 * and find the nce from the ire->ire_nce because we need
27766 		 * to pass the ire to ip_xmit_v4 later, and can find both
27767 		 * ire and nce in one lookup.
27768 		 */
27769 		fake_ire = (ire_t *)mp->b_rptr;
27770 
27771 		/*
27772 		 * By the time we come back here from ARP the logical outgoing
27773 		 * interface of the incomplete ire we added in ire_forward()
27774 		 * could have disappeared, causing the incomplete ire to also
27775 		 * disappear.  So we need to retreive the proper ipif for the
27776 		 * ire before looking in ctable.  In the case of IPMP, the
27777 		 * ipif may be on the IPMP ill, so look it up based on the
27778 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27779 		 * Then, we can verify that ire_ipif_seqid still exists.
27780 		 */
27781 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27782 		    NULL, NULL, NULL, NULL, ipst);
27783 		if (ill == NULL) {
27784 			ip1dbg(("ill for incomplete ire vanished\n"));
27785 			freemsg(mp); /* fake ire */
27786 			freeb(mp1);  /* dl_unitdata response */
27787 			return;
27788 		}
27789 
27790 		/* Get the outgoing ipif */
27791 		mutex_enter(&ill->ill_lock);
27792 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27793 		if (ipif == NULL) {
27794 			mutex_exit(&ill->ill_lock);
27795 			ill_refrele(ill);
27796 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27797 			freemsg(mp); /* fake_ire */
27798 			freeb(mp1);  /* dl_unitdata response */
27799 			return;
27800 		}
27801 
27802 		ipif_refhold_locked(ipif);
27803 		mutex_exit(&ill->ill_lock);
27804 		ill_refrele(ill);
27805 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27806 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27807 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27808 		ipif_refrele(ipif);
27809 		if (ire == NULL) {
27810 			/*
27811 			 * no ire was found; check if there is an nce
27812 			 * for this lookup; if it has no ire's pointing at it
27813 			 * cleanup.
27814 			 */
27815 			if ((nce = ndp_lookup_v4(q->q_ptr,
27816 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27817 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27818 			    B_FALSE)) != NULL) {
27819 				/*
27820 				 * cleanup:
27821 				 * We check for refcnt 2 (one for the nce
27822 				 * hash list + 1 for the ref taken by
27823 				 * ndp_lookup_v4) to check that there are
27824 				 * no ire's pointing at the nce.
27825 				 */
27826 				if (nce->nce_refcnt == 2)
27827 					ndp_delete(nce);
27828 				NCE_REFRELE(nce);
27829 			}
27830 			freeb(mp1);  /* dl_unitdata response */
27831 			freemsg(mp); /* fake ire */
27832 			return;
27833 		}
27834 
27835 		nce = ire->ire_nce;
27836 		DTRACE_PROBE2(ire__arpresolve__type,
27837 		    ire_t *, ire, nce_t *, nce);
27838 		ASSERT(nce->nce_state != ND_INITIAL);
27839 		mutex_enter(&nce->nce_lock);
27840 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27841 		if (nce->nce_state == ND_REACHABLE) {
27842 			/*
27843 			 * Someone resolved this before us;
27844 			 * our response is not needed any more.
27845 			 */
27846 			mutex_exit(&nce->nce_lock);
27847 			freeb(mp1);  /* dl_unitdata response */
27848 		} else {
27849 			ASSERT(nce->nce_res_mp == NULL);
27850 			nce->nce_res_mp = mp1;
27851 			nce->nce_state = ND_REACHABLE;
27852 			mutex_exit(&nce->nce_lock);
27853 			nce_fastpath(nce);
27854 		}
27855 		/*
27856 		 * The cached nce_t has been updated to be reachable;
27857 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27858 		 */
27859 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27860 		freemsg(mp);
27861 		/*
27862 		 * send out queued packets.
27863 		 */
27864 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27865 
27866 		IRE_REFRELE(ire);
27867 		return;
27868 	}
27869 	default:
27870 		break;
27871 	}
27872 	if (q->q_next) {
27873 		putnext(q, mp);
27874 	} else
27875 		freemsg(mp);
27876 	return;
27877 
27878 protonak:
27879 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27880 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27881 		qreply(q, mp);
27882 }
27883 
27884 /*
27885  * Process IP options in an outbound packet.  Modify the destination if there
27886  * is a source route option.
27887  * Returns non-zero if something fails in which case an ICMP error has been
27888  * sent and mp freed.
27889  */
27890 static int
27891 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27892     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27893 {
27894 	ipoptp_t	opts;
27895 	uchar_t		*opt;
27896 	uint8_t		optval;
27897 	uint8_t		optlen;
27898 	ipaddr_t	dst;
27899 	intptr_t	code = 0;
27900 	mblk_t		*mp;
27901 	ire_t		*ire = NULL;
27902 
27903 	ip2dbg(("ip_wput_options\n"));
27904 	mp = ipsec_mp;
27905 	if (mctl_present) {
27906 		mp = ipsec_mp->b_cont;
27907 	}
27908 
27909 	dst = ipha->ipha_dst;
27910 	for (optval = ipoptp_first(&opts, ipha);
27911 	    optval != IPOPT_EOL;
27912 	    optval = ipoptp_next(&opts)) {
27913 		opt = opts.ipoptp_cur;
27914 		optlen = opts.ipoptp_len;
27915 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27916 		    optval, optlen));
27917 		switch (optval) {
27918 			uint32_t off;
27919 		case IPOPT_SSRR:
27920 		case IPOPT_LSRR:
27921 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27922 				ip1dbg((
27923 				    "ip_wput_options: bad option offset\n"));
27924 				code = (char *)&opt[IPOPT_OLEN] -
27925 				    (char *)ipha;
27926 				goto param_prob;
27927 			}
27928 			off = opt[IPOPT_OFFSET];
27929 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27930 			    ntohl(dst)));
27931 			/*
27932 			 * For strict: verify that dst is directly
27933 			 * reachable.
27934 			 */
27935 			if (optval == IPOPT_SSRR) {
27936 				ire = ire_ftable_lookup(dst, 0, 0,
27937 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27938 				    msg_getlabel(mp),
27939 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27940 				if (ire == NULL) {
27941 					ip1dbg(("ip_wput_options: SSRR not"
27942 					    " directly reachable: 0x%x\n",
27943 					    ntohl(dst)));
27944 					goto bad_src_route;
27945 				}
27946 				ire_refrele(ire);
27947 			}
27948 			break;
27949 		case IPOPT_RR:
27950 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27951 				ip1dbg((
27952 				    "ip_wput_options: bad option offset\n"));
27953 				code = (char *)&opt[IPOPT_OLEN] -
27954 				    (char *)ipha;
27955 				goto param_prob;
27956 			}
27957 			break;
27958 		case IPOPT_TS:
27959 			/*
27960 			 * Verify that length >=5 and that there is either
27961 			 * room for another timestamp or that the overflow
27962 			 * counter is not maxed out.
27963 			 */
27964 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27965 			if (optlen < IPOPT_MINLEN_IT) {
27966 				goto param_prob;
27967 			}
27968 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27969 				ip1dbg((
27970 				    "ip_wput_options: bad option offset\n"));
27971 				code = (char *)&opt[IPOPT_OFFSET] -
27972 				    (char *)ipha;
27973 				goto param_prob;
27974 			}
27975 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27976 			case IPOPT_TS_TSONLY:
27977 				off = IPOPT_TS_TIMELEN;
27978 				break;
27979 			case IPOPT_TS_TSANDADDR:
27980 			case IPOPT_TS_PRESPEC:
27981 			case IPOPT_TS_PRESPEC_RFC791:
27982 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27983 				break;
27984 			default:
27985 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27986 				    (char *)ipha;
27987 				goto param_prob;
27988 			}
27989 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27990 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27991 				/*
27992 				 * No room and the overflow counter is 15
27993 				 * already.
27994 				 */
27995 				goto param_prob;
27996 			}
27997 			break;
27998 		}
27999 	}
28000 
28001 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28002 		return (0);
28003 
28004 	ip1dbg(("ip_wput_options: error processing IP options."));
28005 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28006 
28007 param_prob:
28008 	/*
28009 	 * Since ip_wput() isn't close to finished, we fill
28010 	 * in enough of the header for credible error reporting.
28011 	 */
28012 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28013 		/* Failed */
28014 		freemsg(ipsec_mp);
28015 		return (-1);
28016 	}
28017 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28018 	return (-1);
28019 
28020 bad_src_route:
28021 	/*
28022 	 * Since ip_wput() isn't close to finished, we fill
28023 	 * in enough of the header for credible error reporting.
28024 	 */
28025 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28026 		/* Failed */
28027 		freemsg(ipsec_mp);
28028 		return (-1);
28029 	}
28030 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28031 	return (-1);
28032 }
28033 
28034 /*
28035  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28036  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28037  * thru /etc/system.
28038  */
28039 #define	CONN_MAXDRAINCNT	64
28040 
28041 static void
28042 conn_drain_init(ip_stack_t *ipst)
28043 {
28044 	int i, j;
28045 	idl_tx_list_t *itl_tx;
28046 
28047 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28048 
28049 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28050 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28051 		/*
28052 		 * Default value of the number of drainers is the
28053 		 * number of cpus, subject to maximum of 8 drainers.
28054 		 */
28055 		if (boot_max_ncpus != -1)
28056 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28057 		else
28058 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28059 	}
28060 
28061 	ipst->ips_idl_tx_list =
28062 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
28063 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28064 		itl_tx =  &ipst->ips_idl_tx_list[i];
28065 		itl_tx->txl_drain_list =
28066 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28067 		    sizeof (idl_t), KM_SLEEP);
28068 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
28069 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
28070 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
28071 			    MUTEX_DEFAULT, NULL);
28072 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
28073 		}
28074 	}
28075 }
28076 
28077 static void
28078 conn_drain_fini(ip_stack_t *ipst)
28079 {
28080 	int i;
28081 	idl_tx_list_t *itl_tx;
28082 
28083 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28084 		itl_tx =  &ipst->ips_idl_tx_list[i];
28085 		kmem_free(itl_tx->txl_drain_list,
28086 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28087 	}
28088 	kmem_free(ipst->ips_idl_tx_list,
28089 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28090 	ipst->ips_idl_tx_list = NULL;
28091 }
28092 
28093 /*
28094  * Note: For an overview of how flowcontrol is handled in IP please see the
28095  * IP Flowcontrol notes at the top of this file.
28096  *
28097  * Flow control has blocked us from proceeding. Insert the given conn in one
28098  * of the conn drain lists. These conn wq's will be qenabled later on when
28099  * STREAMS flow control does a backenable. conn_walk_drain will enable
28100  * the first conn in each of these drain lists. Each of these qenabled conns
28101  * in turn enables the next in the list, after it runs, or when it closes,
28102  * thus sustaining the drain process.
28103  */
28104 void
28105 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28106 {
28107 	idl_t	*idl = tx_list->txl_drain_list;
28108 	uint_t	index;
28109 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28110 
28111 	mutex_enter(&connp->conn_lock);
28112 	if (connp->conn_state_flags & CONN_CLOSING) {
28113 		/*
28114 		 * The conn is closing as a result of which CONN_CLOSING
28115 		 * is set. Return.
28116 		 */
28117 		mutex_exit(&connp->conn_lock);
28118 		return;
28119 	} else if (connp->conn_idl == NULL) {
28120 		/*
28121 		 * Assign the next drain list round robin. We dont' use
28122 		 * a lock, and thus it may not be strictly round robin.
28123 		 * Atomicity of load/stores is enough to make sure that
28124 		 * conn_drain_list_index is always within bounds.
28125 		 */
28126 		index = tx_list->txl_drain_index;
28127 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28128 		connp->conn_idl = &tx_list->txl_drain_list[index];
28129 		index++;
28130 		if (index == ipst->ips_conn_drain_list_cnt)
28131 			index = 0;
28132 		tx_list->txl_drain_index = index;
28133 	}
28134 	mutex_exit(&connp->conn_lock);
28135 
28136 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28137 	if ((connp->conn_drain_prev != NULL) ||
28138 	    (connp->conn_state_flags & CONN_CLOSING)) {
28139 		/*
28140 		 * The conn is already in the drain list, OR
28141 		 * the conn is closing. We need to check again for
28142 		 * the closing case again since close can happen
28143 		 * after we drop the conn_lock, and before we
28144 		 * acquire the CONN_DRAIN_LIST_LOCK.
28145 		 */
28146 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28147 		return;
28148 	} else {
28149 		idl = connp->conn_idl;
28150 	}
28151 
28152 	/*
28153 	 * The conn is not in the drain list. Insert it at the
28154 	 * tail of the drain list. The drain list is circular
28155 	 * and doubly linked. idl_conn points to the 1st element
28156 	 * in the list.
28157 	 */
28158 	if (idl->idl_conn == NULL) {
28159 		idl->idl_conn = connp;
28160 		connp->conn_drain_next = connp;
28161 		connp->conn_drain_prev = connp;
28162 	} else {
28163 		conn_t *head = idl->idl_conn;
28164 
28165 		connp->conn_drain_next = head;
28166 		connp->conn_drain_prev = head->conn_drain_prev;
28167 		head->conn_drain_prev->conn_drain_next = connp;
28168 		head->conn_drain_prev = connp;
28169 	}
28170 	/*
28171 	 * For non streams based sockets assert flow control.
28172 	 */
28173 	if (IPCL_IS_NONSTR(connp)) {
28174 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28175 		(*connp->conn_upcalls->su_txq_full)
28176 		    (connp->conn_upper_handle, B_TRUE);
28177 	} else {
28178 		conn_setqfull(connp);
28179 		noenable(connp->conn_wq);
28180 	}
28181 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28182 }
28183 
28184 /*
28185  * This conn is closing, and we are called from ip_close. OR
28186  * This conn has been serviced by ip_wsrv, and we need to do the tail
28187  * processing.
28188  * If this conn is part of the drain list, we may need to sustain the drain
28189  * process by qenabling the next conn in the drain list. We may also need to
28190  * remove this conn from the list, if it is done.
28191  */
28192 static void
28193 conn_drain_tail(conn_t *connp, boolean_t closing)
28194 {
28195 	idl_t *idl;
28196 
28197 	/*
28198 	 * connp->conn_idl is stable at this point, and no lock is needed
28199 	 * to check it. If we are called from ip_close, close has already
28200 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28201 	 * called us only because conn_idl is non-null. If we are called thru
28202 	 * service, conn_idl could be null, but it cannot change because
28203 	 * service is single-threaded per queue, and there cannot be another
28204 	 * instance of service trying to call conn_drain_insert on this conn
28205 	 * now.
28206 	 */
28207 	ASSERT(!closing || (connp->conn_idl != NULL));
28208 
28209 	/*
28210 	 * If connp->conn_idl is null, the conn has not been inserted into any
28211 	 * drain list even once since creation of the conn. Just return.
28212 	 */
28213 	if (connp->conn_idl == NULL)
28214 		return;
28215 
28216 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28217 
28218 	if (connp->conn_drain_prev == NULL) {
28219 		/* This conn is currently not in the drain list.  */
28220 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28221 		return;
28222 	}
28223 	idl = connp->conn_idl;
28224 	if (idl->idl_conn_draining == connp) {
28225 		/*
28226 		 * This conn is the current drainer. If this is the last conn
28227 		 * in the drain list, we need to do more checks, in the 'if'
28228 		 * below. Otherwwise we need to just qenable the next conn,
28229 		 * to sustain the draining, and is handled in the 'else'
28230 		 * below.
28231 		 */
28232 		if (connp->conn_drain_next == idl->idl_conn) {
28233 			/*
28234 			 * This conn is the last in this list. This round
28235 			 * of draining is complete. If idl_repeat is set,
28236 			 * it means another flow enabling has happened from
28237 			 * the driver/streams and we need to another round
28238 			 * of draining.
28239 			 * If there are more than 2 conns in the drain list,
28240 			 * do a left rotate by 1, so that all conns except the
28241 			 * conn at the head move towards the head by 1, and the
28242 			 * the conn at the head goes to the tail. This attempts
28243 			 * a more even share for all queues that are being
28244 			 * drained.
28245 			 */
28246 			if ((connp->conn_drain_next != connp) &&
28247 			    (idl->idl_conn->conn_drain_next != connp)) {
28248 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28249 			}
28250 			if (idl->idl_repeat) {
28251 				qenable(idl->idl_conn->conn_wq);
28252 				idl->idl_conn_draining = idl->idl_conn;
28253 				idl->idl_repeat = 0;
28254 			} else {
28255 				idl->idl_conn_draining = NULL;
28256 			}
28257 		} else {
28258 			/*
28259 			 * If the next queue that we are now qenable'ing,
28260 			 * is closing, it will remove itself from this list
28261 			 * and qenable the subsequent queue in ip_close().
28262 			 * Serialization is acheived thru idl_lock.
28263 			 */
28264 			qenable(connp->conn_drain_next->conn_wq);
28265 			idl->idl_conn_draining = connp->conn_drain_next;
28266 		}
28267 	}
28268 	if (!connp->conn_did_putbq || closing) {
28269 		/*
28270 		 * Remove ourself from the drain list, if we did not do
28271 		 * a putbq, or if the conn is closing.
28272 		 * Note: It is possible that q->q_first is non-null. It means
28273 		 * that these messages landed after we did a enableok() in
28274 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28275 		 * service them.
28276 		 */
28277 		if (connp->conn_drain_next == connp) {
28278 			/* Singleton in the list */
28279 			ASSERT(connp->conn_drain_prev == connp);
28280 			idl->idl_conn = NULL;
28281 			idl->idl_conn_draining = NULL;
28282 		} else {
28283 			connp->conn_drain_prev->conn_drain_next =
28284 			    connp->conn_drain_next;
28285 			connp->conn_drain_next->conn_drain_prev =
28286 			    connp->conn_drain_prev;
28287 			if (idl->idl_conn == connp)
28288 				idl->idl_conn = connp->conn_drain_next;
28289 			ASSERT(idl->idl_conn_draining != connp);
28290 
28291 		}
28292 		connp->conn_drain_next = NULL;
28293 		connp->conn_drain_prev = NULL;
28294 
28295 		/*
28296 		 * For non streams based sockets open up flow control.
28297 		 */
28298 		if (IPCL_IS_NONSTR(connp)) {
28299 			(*connp->conn_upcalls->su_txq_full)
28300 			    (connp->conn_upper_handle, B_FALSE);
28301 		} else {
28302 			conn_clrqfull(connp);
28303 			enableok(connp->conn_wq);
28304 		}
28305 	}
28306 
28307 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28308 }
28309 
28310 /*
28311  * Write service routine. Shared perimeter entry point.
28312  * ip_wsrv can be called in any of the following ways.
28313  * 1. The device queue's messages has fallen below the low water mark
28314  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28315  *    the drain lists and backenable the first conn in each list.
28316  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28317  *    qenabled non-tcp upper layers. We start dequeing messages and call
28318  *    ip_wput for each message.
28319  */
28320 
28321 void
28322 ip_wsrv(queue_t *q)
28323 {
28324 	conn_t	*connp;
28325 	ill_t	*ill;
28326 	mblk_t	*mp;
28327 
28328 	if (q->q_next) {
28329 		ill = (ill_t *)q->q_ptr;
28330 		if (ill->ill_state_flags == 0) {
28331 			ip_stack_t *ipst = ill->ill_ipst;
28332 
28333 			/*
28334 			 * The device flow control has opened up.
28335 			 * Walk through conn drain lists and qenable the
28336 			 * first conn in each list. This makes sense only
28337 			 * if the stream is fully plumbed and setup.
28338 			 * Hence the if check above.
28339 			 */
28340 			ip1dbg(("ip_wsrv: walking\n"));
28341 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28342 		}
28343 		return;
28344 	}
28345 
28346 	connp = Q_TO_CONN(q);
28347 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28348 
28349 	/*
28350 	 * 1. Set conn_draining flag to signal that service is active.
28351 	 *
28352 	 * 2. ip_output determines whether it has been called from service,
28353 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28354 	 *    has been called from service.
28355 	 *
28356 	 * 3. Message ordering is preserved by the following logic.
28357 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28358 	 *    the message at the tail, if conn_draining is set (i.e. service
28359 	 *    is running) or if q->q_first is non-null.
28360 	 *
28361 	 *    ii. If ip_output is called from service, and if ip_output cannot
28362 	 *    putnext due to flow control, it does a putbq.
28363 	 *
28364 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28365 	 *    (causing an infinite loop).
28366 	 */
28367 	ASSERT(!connp->conn_did_putbq);
28368 
28369 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28370 		connp->conn_draining = 1;
28371 		noenable(q);
28372 		while ((mp = getq(q)) != NULL) {
28373 			ASSERT(CONN_Q(q));
28374 
28375 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28376 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28377 			if (connp->conn_did_putbq) {
28378 				/* ip_wput did a putbq */
28379 				break;
28380 			}
28381 		}
28382 		/*
28383 		 * At this point, a thread coming down from top, calling
28384 		 * ip_wput, may end up queueing the message. We have not yet
28385 		 * enabled the queue, so ip_wsrv won't be called again.
28386 		 * To avoid this race, check q->q_first again (in the loop)
28387 		 * If the other thread queued the message before we call
28388 		 * enableok(), we will catch it in the q->q_first check.
28389 		 * If the other thread queues the message after we call
28390 		 * enableok(), ip_wsrv will be called again by STREAMS.
28391 		 */
28392 		connp->conn_draining = 0;
28393 		enableok(q);
28394 	}
28395 
28396 	/* Enable the next conn for draining */
28397 	conn_drain_tail(connp, B_FALSE);
28398 
28399 	/*
28400 	 * conn_direct_blocked is used to indicate blocked
28401 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28402 	 * This is the only place where it is set without
28403 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28404 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28405 	 */
28406 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28407 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28408 		connp->conn_direct_blocked = B_FALSE;
28409 	}
28410 
28411 	connp->conn_did_putbq = 0;
28412 }
28413 
28414 /*
28415  * Callback to disable flow control in IP.
28416  *
28417  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28418  * is enabled.
28419  *
28420  * When MAC_TX() is not able to send any more packets, dld sets its queue
28421  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28422  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28423  * function and wakes up corresponding mac worker threads, which in turn
28424  * calls this callback function, and disables flow control.
28425  */
28426 void
28427 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28428 {
28429 	ill_t *ill = (ill_t *)arg;
28430 	ip_stack_t *ipst = ill->ill_ipst;
28431 	idl_tx_list_t *idl_txl;
28432 
28433 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28434 	mutex_enter(&idl_txl->txl_lock);
28435 	/* add code to to set a flag to indicate idl_txl is enabled */
28436 	conn_walk_drain(ipst, idl_txl);
28437 	mutex_exit(&idl_txl->txl_lock);
28438 }
28439 
28440 /*
28441  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28442  * of conns that need to be drained, check if drain is already in progress.
28443  * If so set the idl_repeat bit, indicating that the last conn in the list
28444  * needs to reinitiate the drain once again, for the list. If drain is not
28445  * in progress for the list, initiate the draining, by qenabling the 1st
28446  * conn in the list. The drain is self-sustaining, each qenabled conn will
28447  * in turn qenable the next conn, when it is done/blocked/closing.
28448  */
28449 static void
28450 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28451 {
28452 	int i;
28453 	idl_t *idl;
28454 
28455 	IP_STAT(ipst, ip_conn_walk_drain);
28456 
28457 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28458 		idl = &tx_list->txl_drain_list[i];
28459 		mutex_enter(&idl->idl_lock);
28460 		if (idl->idl_conn == NULL) {
28461 			mutex_exit(&idl->idl_lock);
28462 			continue;
28463 		}
28464 		/*
28465 		 * If this list is not being drained currently by
28466 		 * an ip_wsrv thread, start the process.
28467 		 */
28468 		if (idl->idl_conn_draining == NULL) {
28469 			ASSERT(idl->idl_repeat == 0);
28470 			qenable(idl->idl_conn->conn_wq);
28471 			idl->idl_conn_draining = idl->idl_conn;
28472 		} else {
28473 			idl->idl_repeat = 1;
28474 		}
28475 		mutex_exit(&idl->idl_lock);
28476 	}
28477 }
28478 
28479 /*
28480  * Determine if the ill and multicast aspects of that packets
28481  * "matches" the conn.
28482  */
28483 boolean_t
28484 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28485     zoneid_t zoneid)
28486 {
28487 	ill_t *bound_ill;
28488 	boolean_t found;
28489 	ipif_t *ipif;
28490 	ire_t *ire;
28491 	ipaddr_t dst, src;
28492 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28493 
28494 	dst = ipha->ipha_dst;
28495 	src = ipha->ipha_src;
28496 
28497 	/*
28498 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28499 	 * unicast, broadcast and multicast reception to
28500 	 * conn_incoming_ill. conn_wantpacket itself is called
28501 	 * only for BROADCAST and multicast.
28502 	 */
28503 	bound_ill = connp->conn_incoming_ill;
28504 	if (bound_ill != NULL) {
28505 		if (IS_IPMP(bound_ill)) {
28506 			if (bound_ill->ill_grp != ill->ill_grp)
28507 				return (B_FALSE);
28508 		} else {
28509 			if (bound_ill != ill)
28510 				return (B_FALSE);
28511 		}
28512 	}
28513 
28514 	if (!CLASSD(dst)) {
28515 		if (IPCL_ZONE_MATCH(connp, zoneid))
28516 			return (B_TRUE);
28517 		/*
28518 		 * The conn is in a different zone; we need to check that this
28519 		 * broadcast address is configured in the application's zone.
28520 		 */
28521 		ipif = ipif_get_next_ipif(NULL, ill);
28522 		if (ipif == NULL)
28523 			return (B_FALSE);
28524 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28525 		    connp->conn_zoneid, NULL,
28526 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28527 		ipif_refrele(ipif);
28528 		if (ire != NULL) {
28529 			ire_refrele(ire);
28530 			return (B_TRUE);
28531 		} else {
28532 			return (B_FALSE);
28533 		}
28534 	}
28535 
28536 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28537 	    connp->conn_zoneid == zoneid) {
28538 		/*
28539 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28540 		 * disabled, therefore we don't dispatch the multicast packet to
28541 		 * the sending zone.
28542 		 */
28543 		return (B_FALSE);
28544 	}
28545 
28546 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28547 		/*
28548 		 * Multicast packet on the loopback interface: we only match
28549 		 * conns who joined the group in the specified zone.
28550 		 */
28551 		return (B_FALSE);
28552 	}
28553 
28554 	if (connp->conn_multi_router) {
28555 		/* multicast packet and multicast router socket: send up */
28556 		return (B_TRUE);
28557 	}
28558 
28559 	mutex_enter(&connp->conn_lock);
28560 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28561 	mutex_exit(&connp->conn_lock);
28562 	return (found);
28563 }
28564 
28565 static void
28566 conn_setqfull(conn_t *connp)
28567 {
28568 	queue_t *q = connp->conn_wq;
28569 
28570 	if (!(q->q_flag & QFULL)) {
28571 		mutex_enter(QLOCK(q));
28572 		if (!(q->q_flag & QFULL)) {
28573 			/* still need to set QFULL */
28574 			q->q_flag |= QFULL;
28575 			mutex_exit(QLOCK(q));
28576 		} else {
28577 			mutex_exit(QLOCK(q));
28578 		}
28579 	}
28580 }
28581 
28582 static void
28583 conn_clrqfull(conn_t *connp)
28584 {
28585 	queue_t *q = connp->conn_wq;
28586 
28587 	if (q->q_flag & QFULL) {
28588 		mutex_enter(QLOCK(q));
28589 		if (q->q_flag & QFULL) {
28590 			q->q_flag &= ~QFULL;
28591 			mutex_exit(QLOCK(q));
28592 			if (q->q_flag & QWANTW)
28593 				qbackenable(q, 0);
28594 		} else {
28595 			mutex_exit(QLOCK(q));
28596 		}
28597 	}
28598 }
28599 
28600 /*
28601  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28602  */
28603 /* ARGSUSED */
28604 static void
28605 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28606 {
28607 	ill_t *ill = (ill_t *)q->q_ptr;
28608 	mblk_t	*mp1, *mp2;
28609 	ipif_t  *ipif;
28610 	int err = 0;
28611 	conn_t *connp = NULL;
28612 	ipsq_t	*ipsq;
28613 	arc_t	*arc;
28614 
28615 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28616 
28617 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28618 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28619 
28620 	ASSERT(IAM_WRITER_ILL(ill));
28621 	mp2 = mp->b_cont;
28622 	mp->b_cont = NULL;
28623 
28624 	/*
28625 	 * We have now received the arp bringup completion message
28626 	 * from ARP. Mark the arp bringup as done. Also if the arp
28627 	 * stream has already started closing, send up the AR_ARP_CLOSING
28628 	 * ack now since ARP is waiting in close for this ack.
28629 	 */
28630 	mutex_enter(&ill->ill_lock);
28631 	ill->ill_arp_bringup_pending = 0;
28632 	if (ill->ill_arp_closing) {
28633 		mutex_exit(&ill->ill_lock);
28634 		/* Let's reuse the mp for sending the ack */
28635 		arc = (arc_t *)mp->b_rptr;
28636 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28637 		arc->arc_cmd = AR_ARP_CLOSING;
28638 		qreply(q, mp);
28639 	} else {
28640 		mutex_exit(&ill->ill_lock);
28641 		freeb(mp);
28642 	}
28643 
28644 	ipsq = ill->ill_phyint->phyint_ipsq;
28645 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28646 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28647 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28648 	if (mp1 == NULL) {
28649 		/* bringup was aborted by the user */
28650 		freemsg(mp2);
28651 		return;
28652 	}
28653 
28654 	/*
28655 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28656 	 * must have an associated conn_t.  Otherwise, we're bringing this
28657 	 * interface back up as part of handling an asynchronous event (e.g.,
28658 	 * physical address change).
28659 	 */
28660 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28661 		ASSERT(connp != NULL);
28662 		q = CONNP_TO_WQ(connp);
28663 	} else {
28664 		ASSERT(connp == NULL);
28665 		q = ill->ill_rq;
28666 	}
28667 
28668 	/*
28669 	 * If the DL_BIND_REQ fails, it is noted
28670 	 * in arc_name_offset.
28671 	 */
28672 	err = *((int *)mp2->b_rptr);
28673 	if (err == 0) {
28674 		if (ipif->ipif_isv6) {
28675 			if ((err = ipif_up_done_v6(ipif)) != 0)
28676 				ip0dbg(("ip_arp_done: init failed\n"));
28677 		} else {
28678 			if ((err = ipif_up_done(ipif)) != 0)
28679 				ip0dbg(("ip_arp_done: init failed\n"));
28680 		}
28681 	} else {
28682 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28683 	}
28684 
28685 	freemsg(mp2);
28686 
28687 	if ((err == 0) && (ill->ill_up_ipifs)) {
28688 		err = ill_up_ipifs(ill, q, mp1);
28689 		if (err == EINPROGRESS)
28690 			return;
28691 	}
28692 
28693 	/*
28694 	 * If we have a moved ipif to bring up, and everything has succeeded
28695 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28696 	 * down -- the admin can try to bring it up by hand if need be.
28697 	 */
28698 	if (ill->ill_move_ipif != NULL) {
28699 		ipif = ill->ill_move_ipif;
28700 		ill->ill_move_ipif = NULL;
28701 		if (err == 0) {
28702 			err = ipif_up(ipif, q, mp1);
28703 			if (err == EINPROGRESS)
28704 				return;
28705 		}
28706 	}
28707 
28708 	/*
28709 	 * The operation must complete without EINPROGRESS since
28710 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28711 	 * operation will be stuck forever in the ipsq.
28712 	 */
28713 	ASSERT(err != EINPROGRESS);
28714 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28715 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28716 	else
28717 		ipsq_current_finish(ipsq);
28718 }
28719 
28720 /* Allocate the private structure */
28721 static int
28722 ip_priv_alloc(void **bufp)
28723 {
28724 	void	*buf;
28725 
28726 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28727 		return (ENOMEM);
28728 
28729 	*bufp = buf;
28730 	return (0);
28731 }
28732 
28733 /* Function to delete the private structure */
28734 void
28735 ip_priv_free(void *buf)
28736 {
28737 	ASSERT(buf != NULL);
28738 	kmem_free(buf, sizeof (ip_priv_t));
28739 }
28740 
28741 /*
28742  * The entry point for IPPF processing.
28743  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28744  * routine just returns.
28745  *
28746  * When called, ip_process generates an ipp_packet_t structure
28747  * which holds the state information for this packet and invokes the
28748  * the classifier (via ipp_packet_process). The classification, depending on
28749  * configured filters, results in a list of actions for this packet. Invoking
28750  * an action may cause the packet to be dropped, in which case the resulting
28751  * mblk (*mpp) is NULL. proc indicates the callout position for
28752  * this packet and ill_index is the interface this packet on or will leave
28753  * on (inbound and outbound resp.).
28754  */
28755 void
28756 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28757 {
28758 	mblk_t		*mp;
28759 	ip_priv_t	*priv;
28760 	ipp_action_id_t	aid;
28761 	int		rc = 0;
28762 	ipp_packet_t	*pp;
28763 #define	IP_CLASS	"ip"
28764 
28765 	/* If the classifier is not loaded, return  */
28766 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28767 		return;
28768 	}
28769 
28770 	mp = *mpp;
28771 	ASSERT(mp != NULL);
28772 
28773 	/* Allocate the packet structure */
28774 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28775 	if (rc != 0) {
28776 		*mpp = NULL;
28777 		freemsg(mp);
28778 		return;
28779 	}
28780 
28781 	/* Allocate the private structure */
28782 	rc = ip_priv_alloc((void **)&priv);
28783 	if (rc != 0) {
28784 		*mpp = NULL;
28785 		freemsg(mp);
28786 		ipp_packet_free(pp);
28787 		return;
28788 	}
28789 	priv->proc = proc;
28790 	priv->ill_index = ill_index;
28791 	ipp_packet_set_private(pp, priv, ip_priv_free);
28792 	ipp_packet_set_data(pp, mp);
28793 
28794 	/* Invoke the classifier */
28795 	rc = ipp_packet_process(&pp);
28796 	if (pp != NULL) {
28797 		mp = ipp_packet_get_data(pp);
28798 		ipp_packet_free(pp);
28799 		if (rc != 0) {
28800 			freemsg(mp);
28801 			*mpp = NULL;
28802 		}
28803 	} else {
28804 		*mpp = NULL;
28805 	}
28806 #undef	IP_CLASS
28807 }
28808 
28809 /*
28810  * Propagate a multicast group membership operation (add/drop) on
28811  * all the interfaces crossed by the related multirt routes.
28812  * The call is considered successful if the operation succeeds
28813  * on at least one interface.
28814  */
28815 static int
28816 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28817     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28818     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28819     mblk_t *first_mp)
28820 {
28821 	ire_t		*ire_gw;
28822 	irb_t		*irb;
28823 	int		error = 0;
28824 	opt_restart_t	*or;
28825 	ip_stack_t	*ipst = ire->ire_ipst;
28826 
28827 	irb = ire->ire_bucket;
28828 	ASSERT(irb != NULL);
28829 
28830 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28831 
28832 	or = (opt_restart_t *)first_mp->b_rptr;
28833 	IRB_REFHOLD(irb);
28834 	for (; ire != NULL; ire = ire->ire_next) {
28835 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28836 			continue;
28837 		if (ire->ire_addr != group)
28838 			continue;
28839 
28840 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28841 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28842 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28843 		/* No resolver exists for the gateway; skip this ire. */
28844 		if (ire_gw == NULL)
28845 			continue;
28846 
28847 		/*
28848 		 * This function can return EINPROGRESS. If so the operation
28849 		 * will be restarted from ip_restart_optmgmt which will
28850 		 * call ip_opt_set and option processing will restart for
28851 		 * this option. So we may end up calling 'fn' more than once.
28852 		 * This requires that 'fn' is idempotent except for the
28853 		 * return value. The operation is considered a success if
28854 		 * it succeeds at least once on any one interface.
28855 		 */
28856 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28857 		    NULL, fmode, src, first_mp);
28858 		if (error == 0)
28859 			or->or_private = CGTP_MCAST_SUCCESS;
28860 
28861 		if (ip_debug > 0) {
28862 			ulong_t	off;
28863 			char	*ksym;
28864 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28865 			ip2dbg(("ip_multirt_apply_membership: "
28866 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28867 			    "error %d [success %u]\n",
28868 			    ksym ? ksym : "?",
28869 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28870 			    error, or->or_private));
28871 		}
28872 
28873 		ire_refrele(ire_gw);
28874 		if (error == EINPROGRESS) {
28875 			IRB_REFRELE(irb);
28876 			return (error);
28877 		}
28878 	}
28879 	IRB_REFRELE(irb);
28880 	/*
28881 	 * Consider the call as successful if we succeeded on at least
28882 	 * one interface. Otherwise, return the last encountered error.
28883 	 */
28884 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28885 }
28886 
28887 /*
28888  * Issue a warning regarding a route crossing an interface with an
28889  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28890  * amount of time is logged.
28891  */
28892 static void
28893 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28894 {
28895 	hrtime_t	current = gethrtime();
28896 	char		buf[INET_ADDRSTRLEN];
28897 	ip_stack_t	*ipst = ire->ire_ipst;
28898 
28899 	/* Convert interval in ms to hrtime in ns */
28900 	if (ipst->ips_multirt_bad_mtu_last_time +
28901 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28902 	    current) {
28903 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28904 		    "to %s, incorrect MTU %u (expected %u)\n",
28905 		    ip_dot_addr(ire->ire_addr, buf),
28906 		    ire->ire_max_frag, max_frag);
28907 
28908 		ipst->ips_multirt_bad_mtu_last_time = current;
28909 	}
28910 }
28911 
28912 /*
28913  * Get the CGTP (multirouting) filtering status.
28914  * If 0, the CGTP hooks are transparent.
28915  */
28916 /* ARGSUSED */
28917 static int
28918 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28919 {
28920 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28921 
28922 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28923 	return (0);
28924 }
28925 
28926 /*
28927  * Set the CGTP (multirouting) filtering status.
28928  * If the status is changed from active to transparent
28929  * or from transparent to active, forward the new status
28930  * to the filtering module (if loaded).
28931  */
28932 /* ARGSUSED */
28933 static int
28934 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28935     cred_t *ioc_cr)
28936 {
28937 	long		new_value;
28938 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28939 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28940 
28941 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28942 		return (EPERM);
28943 
28944 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28945 	    new_value < 0 || new_value > 1) {
28946 		return (EINVAL);
28947 	}
28948 
28949 	if ((!*ip_cgtp_filter_value) && new_value) {
28950 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28951 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28952 		    " (module not loaded)" : "");
28953 	}
28954 	if (*ip_cgtp_filter_value && (!new_value)) {
28955 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28956 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28957 		    " (module not loaded)" : "");
28958 	}
28959 
28960 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28961 		int	res;
28962 		netstackid_t stackid;
28963 
28964 		stackid = ipst->ips_netstack->netstack_stackid;
28965 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28966 		    new_value);
28967 		if (res)
28968 			return (res);
28969 	}
28970 
28971 	*ip_cgtp_filter_value = (boolean_t)new_value;
28972 
28973 	return (0);
28974 }
28975 
28976 /*
28977  * Return the expected CGTP hooks version number.
28978  */
28979 int
28980 ip_cgtp_filter_supported(void)
28981 {
28982 	return (ip_cgtp_filter_rev);
28983 }
28984 
28985 /*
28986  * CGTP hooks can be registered by invoking this function.
28987  * Checks that the version number matches.
28988  */
28989 int
28990 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28991 {
28992 	netstack_t *ns;
28993 	ip_stack_t *ipst;
28994 
28995 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28996 		return (ENOTSUP);
28997 
28998 	ns = netstack_find_by_stackid(stackid);
28999 	if (ns == NULL)
29000 		return (EINVAL);
29001 	ipst = ns->netstack_ip;
29002 	ASSERT(ipst != NULL);
29003 
29004 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29005 		netstack_rele(ns);
29006 		return (EALREADY);
29007 	}
29008 
29009 	ipst->ips_ip_cgtp_filter_ops = ops;
29010 	netstack_rele(ns);
29011 	return (0);
29012 }
29013 
29014 /*
29015  * CGTP hooks can be unregistered by invoking this function.
29016  * Returns ENXIO if there was no registration.
29017  * Returns EBUSY if the ndd variable has not been turned off.
29018  */
29019 int
29020 ip_cgtp_filter_unregister(netstackid_t stackid)
29021 {
29022 	netstack_t *ns;
29023 	ip_stack_t *ipst;
29024 
29025 	ns = netstack_find_by_stackid(stackid);
29026 	if (ns == NULL)
29027 		return (EINVAL);
29028 	ipst = ns->netstack_ip;
29029 	ASSERT(ipst != NULL);
29030 
29031 	if (ipst->ips_ip_cgtp_filter) {
29032 		netstack_rele(ns);
29033 		return (EBUSY);
29034 	}
29035 
29036 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29037 		netstack_rele(ns);
29038 		return (ENXIO);
29039 	}
29040 	ipst->ips_ip_cgtp_filter_ops = NULL;
29041 	netstack_rele(ns);
29042 	return (0);
29043 }
29044 
29045 /*
29046  * Check whether there is a CGTP filter registration.
29047  * Returns non-zero if there is a registration, otherwise returns zero.
29048  * Note: returns zero if bad stackid.
29049  */
29050 int
29051 ip_cgtp_filter_is_registered(netstackid_t stackid)
29052 {
29053 	netstack_t *ns;
29054 	ip_stack_t *ipst;
29055 	int ret;
29056 
29057 	ns = netstack_find_by_stackid(stackid);
29058 	if (ns == NULL)
29059 		return (0);
29060 	ipst = ns->netstack_ip;
29061 	ASSERT(ipst != NULL);
29062 
29063 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29064 		ret = 1;
29065 	else
29066 		ret = 0;
29067 
29068 	netstack_rele(ns);
29069 	return (ret);
29070 }
29071 
29072 static int
29073 ip_squeue_switch(int val)
29074 {
29075 	int rval = SQ_FILL;
29076 
29077 	switch (val) {
29078 	case IP_SQUEUE_ENTER_NODRAIN:
29079 		rval = SQ_NODRAIN;
29080 		break;
29081 	case IP_SQUEUE_ENTER:
29082 		rval = SQ_PROCESS;
29083 		break;
29084 	default:
29085 		break;
29086 	}
29087 	return (rval);
29088 }
29089 
29090 /* ARGSUSED */
29091 static int
29092 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29093     caddr_t addr, cred_t *cr)
29094 {
29095 	int *v = (int *)addr;
29096 	long new_value;
29097 
29098 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29099 		return (EPERM);
29100 
29101 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29102 		return (EINVAL);
29103 
29104 	ip_squeue_flag = ip_squeue_switch(new_value);
29105 	*v = new_value;
29106 	return (0);
29107 }
29108 
29109 /*
29110  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29111  * ip_debug.
29112  */
29113 /* ARGSUSED */
29114 static int
29115 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29116     caddr_t addr, cred_t *cr)
29117 {
29118 	int *v = (int *)addr;
29119 	long new_value;
29120 
29121 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29122 		return (EPERM);
29123 
29124 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29125 		return (EINVAL);
29126 
29127 	*v = new_value;
29128 	return (0);
29129 }
29130 
29131 static void *
29132 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29133 {
29134 	kstat_t *ksp;
29135 
29136 	ip_stat_t template = {
29137 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29138 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29139 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29140 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29141 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29142 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29143 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29144 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29145 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29146 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29147 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29148 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29149 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29150 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29151 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29152 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29153 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29154 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29155 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29156 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29157 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29158 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29159 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29160 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29161 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29162 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29163 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29164 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29165 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29166 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29167 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29168 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29169 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29170 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29171 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29172 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29173 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29174 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29175 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29176 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29177 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29178 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29179 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29180 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29181 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29182 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29183 	};
29184 
29185 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29186 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29187 	    KSTAT_FLAG_VIRTUAL, stackid);
29188 
29189 	if (ksp == NULL)
29190 		return (NULL);
29191 
29192 	bcopy(&template, ip_statisticsp, sizeof (template));
29193 	ksp->ks_data = (void *)ip_statisticsp;
29194 	ksp->ks_private = (void *)(uintptr_t)stackid;
29195 
29196 	kstat_install(ksp);
29197 	return (ksp);
29198 }
29199 
29200 static void
29201 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29202 {
29203 	if (ksp != NULL) {
29204 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29205 		kstat_delete_netstack(ksp, stackid);
29206 	}
29207 }
29208 
29209 static void *
29210 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29211 {
29212 	kstat_t	*ksp;
29213 
29214 	ip_named_kstat_t template = {
29215 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29216 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29217 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29218 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29219 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29220 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29221 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29222 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29223 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29224 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29225 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29226 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29227 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29228 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29229 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29230 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29231 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29232 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29233 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29234 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29235 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29236 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29237 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29238 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29239 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29240 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29241 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29242 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29243 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29244 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29245 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29246 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29247 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29248 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29249 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29250 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29251 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29252 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29253 	};
29254 
29255 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29256 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29257 	if (ksp == NULL || ksp->ks_data == NULL)
29258 		return (NULL);
29259 
29260 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29261 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29262 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29263 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29264 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29265 
29266 	template.netToMediaEntrySize.value.i32 =
29267 	    sizeof (mib2_ipNetToMediaEntry_t);
29268 
29269 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29270 
29271 	bcopy(&template, ksp->ks_data, sizeof (template));
29272 	ksp->ks_update = ip_kstat_update;
29273 	ksp->ks_private = (void *)(uintptr_t)stackid;
29274 
29275 	kstat_install(ksp);
29276 	return (ksp);
29277 }
29278 
29279 static void
29280 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29281 {
29282 	if (ksp != NULL) {
29283 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29284 		kstat_delete_netstack(ksp, stackid);
29285 	}
29286 }
29287 
29288 static int
29289 ip_kstat_update(kstat_t *kp, int rw)
29290 {
29291 	ip_named_kstat_t *ipkp;
29292 	mib2_ipIfStatsEntry_t ipmib;
29293 	ill_walk_context_t ctx;
29294 	ill_t *ill;
29295 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29296 	netstack_t	*ns;
29297 	ip_stack_t	*ipst;
29298 
29299 	if (kp == NULL || kp->ks_data == NULL)
29300 		return (EIO);
29301 
29302 	if (rw == KSTAT_WRITE)
29303 		return (EACCES);
29304 
29305 	ns = netstack_find_by_stackid(stackid);
29306 	if (ns == NULL)
29307 		return (-1);
29308 	ipst = ns->netstack_ip;
29309 	if (ipst == NULL) {
29310 		netstack_rele(ns);
29311 		return (-1);
29312 	}
29313 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29314 
29315 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29316 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29317 	ill = ILL_START_WALK_V4(&ctx, ipst);
29318 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29319 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29320 	rw_exit(&ipst->ips_ill_g_lock);
29321 
29322 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29323 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29324 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29325 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29326 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29327 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29328 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29329 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29330 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29331 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29332 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29333 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29334 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29335 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29336 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29337 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29338 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29339 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29340 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29341 
29342 	ipkp->routingDiscards.value.ui32 =	0;
29343 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29344 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29345 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29346 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29347 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29348 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29349 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29350 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29351 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29352 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29353 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29354 
29355 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29356 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29357 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29358 
29359 	netstack_rele(ns);
29360 
29361 	return (0);
29362 }
29363 
29364 static void *
29365 icmp_kstat_init(netstackid_t stackid)
29366 {
29367 	kstat_t	*ksp;
29368 
29369 	icmp_named_kstat_t template = {
29370 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29371 		{ "inErrors",		KSTAT_DATA_UINT32 },
29372 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29373 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29374 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29375 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29376 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29377 		{ "inEchos",		KSTAT_DATA_UINT32 },
29378 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29379 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29380 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29381 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29382 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29383 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29384 		{ "outErrors",		KSTAT_DATA_UINT32 },
29385 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29386 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29387 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29388 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29389 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29390 		{ "outEchos",		KSTAT_DATA_UINT32 },
29391 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29392 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29393 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29394 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29395 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29396 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29397 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29398 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29399 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29400 		{ "outDrops",		KSTAT_DATA_UINT32 },
29401 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29402 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29403 	};
29404 
29405 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29406 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29407 	if (ksp == NULL || ksp->ks_data == NULL)
29408 		return (NULL);
29409 
29410 	bcopy(&template, ksp->ks_data, sizeof (template));
29411 
29412 	ksp->ks_update = icmp_kstat_update;
29413 	ksp->ks_private = (void *)(uintptr_t)stackid;
29414 
29415 	kstat_install(ksp);
29416 	return (ksp);
29417 }
29418 
29419 static void
29420 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29421 {
29422 	if (ksp != NULL) {
29423 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29424 		kstat_delete_netstack(ksp, stackid);
29425 	}
29426 }
29427 
29428 static int
29429 icmp_kstat_update(kstat_t *kp, int rw)
29430 {
29431 	icmp_named_kstat_t *icmpkp;
29432 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29433 	netstack_t	*ns;
29434 	ip_stack_t	*ipst;
29435 
29436 	if ((kp == NULL) || (kp->ks_data == NULL))
29437 		return (EIO);
29438 
29439 	if (rw == KSTAT_WRITE)
29440 		return (EACCES);
29441 
29442 	ns = netstack_find_by_stackid(stackid);
29443 	if (ns == NULL)
29444 		return (-1);
29445 	ipst = ns->netstack_ip;
29446 	if (ipst == NULL) {
29447 		netstack_rele(ns);
29448 		return (-1);
29449 	}
29450 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29451 
29452 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29453 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29454 	icmpkp->inDestUnreachs.value.ui32 =
29455 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29456 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29457 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29458 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29459 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29460 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29461 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29462 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29463 	icmpkp->inTimestampReps.value.ui32 =
29464 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29465 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29466 	icmpkp->inAddrMaskReps.value.ui32 =
29467 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29468 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29469 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29470 	icmpkp->outDestUnreachs.value.ui32 =
29471 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29472 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29473 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29474 	icmpkp->outSrcQuenchs.value.ui32 =
29475 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29476 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29477 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29478 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29479 	icmpkp->outTimestamps.value.ui32 =
29480 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29481 	icmpkp->outTimestampReps.value.ui32 =
29482 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29483 	icmpkp->outAddrMasks.value.ui32 =
29484 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29485 	icmpkp->outAddrMaskReps.value.ui32 =
29486 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29487 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29488 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29489 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29490 	icmpkp->outFragNeeded.value.ui32 =
29491 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29492 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29493 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29494 	icmpkp->inBadRedirects.value.ui32 =
29495 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29496 
29497 	netstack_rele(ns);
29498 	return (0);
29499 }
29500 
29501 /*
29502  * This is the fanout function for raw socket opened for SCTP.  Note
29503  * that it is called after SCTP checks that there is no socket which
29504  * wants a packet.  Then before SCTP handles this out of the blue packet,
29505  * this function is called to see if there is any raw socket for SCTP.
29506  * If there is and it is bound to the correct address, the packet will
29507  * be sent to that socket.  Note that only one raw socket can be bound to
29508  * a port.  This is assured in ipcl_sctp_hash_insert();
29509  */
29510 void
29511 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29512     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29513     zoneid_t zoneid)
29514 {
29515 	conn_t		*connp;
29516 	queue_t		*rq;
29517 	mblk_t		*first_mp;
29518 	boolean_t	secure;
29519 	ip6_t		*ip6h;
29520 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29521 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29522 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29523 	boolean_t	sctp_csum_err = B_FALSE;
29524 
29525 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29526 		sctp_csum_err = B_TRUE;
29527 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29528 	}
29529 
29530 	first_mp = mp;
29531 	if (mctl_present) {
29532 		mp = first_mp->b_cont;
29533 		secure = ipsec_in_is_secure(first_mp);
29534 		ASSERT(mp != NULL);
29535 	} else {
29536 		secure = B_FALSE;
29537 	}
29538 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29539 
29540 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29541 	if (connp == NULL) {
29542 		/*
29543 		 * Although raw sctp is not summed, OOB chunks must be.
29544 		 * Drop the packet here if the sctp checksum failed.
29545 		 */
29546 		if (sctp_csum_err) {
29547 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29548 			freemsg(first_mp);
29549 			return;
29550 		}
29551 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29552 		return;
29553 	}
29554 	rq = connp->conn_rq;
29555 	if (!canputnext(rq)) {
29556 		CONN_DEC_REF(connp);
29557 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29558 		freemsg(first_mp);
29559 		return;
29560 	}
29561 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29562 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29563 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29564 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29565 		if (first_mp == NULL) {
29566 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29567 			CONN_DEC_REF(connp);
29568 			return;
29569 		}
29570 	}
29571 	/*
29572 	 * We probably should not send M_CTL message up to
29573 	 * raw socket.
29574 	 */
29575 	if (mctl_present)
29576 		freeb(first_mp);
29577 
29578 	/* Initiate IPPF processing here if needed. */
29579 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29580 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29581 		ip_process(IPP_LOCAL_IN, &mp,
29582 		    recv_ill->ill_phyint->phyint_ifindex);
29583 		if (mp == NULL) {
29584 			CONN_DEC_REF(connp);
29585 			return;
29586 		}
29587 	}
29588 
29589 	if (connp->conn_recvif || connp->conn_recvslla ||
29590 	    ((connp->conn_ip_recvpktinfo ||
29591 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29592 	    (flags & IP_FF_IPINFO))) {
29593 		int in_flags = 0;
29594 
29595 		/*
29596 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29597 		 * IPF_RECVIF.
29598 		 */
29599 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29600 			in_flags = IPF_RECVIF;
29601 		}
29602 		if (connp->conn_recvslla) {
29603 			in_flags |= IPF_RECVSLLA;
29604 		}
29605 		if (isv4) {
29606 			mp = ip_add_info(mp, recv_ill, in_flags,
29607 			    IPCL_ZONEID(connp), ipst);
29608 		} else {
29609 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29610 			if (mp == NULL) {
29611 				BUMP_MIB(recv_ill->ill_ip_mib,
29612 				    ipIfStatsInDiscards);
29613 				CONN_DEC_REF(connp);
29614 				return;
29615 			}
29616 		}
29617 	}
29618 
29619 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29620 	/*
29621 	 * We are sending the IPSEC_IN message also up. Refer
29622 	 * to comments above this function.
29623 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29624 	 */
29625 	(connp->conn_recv)(connp, mp, NULL);
29626 	CONN_DEC_REF(connp);
29627 }
29628 
29629 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29630 {									\
29631 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29632 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29633 }
29634 /*
29635  * This function should be called only if all packet processing
29636  * including fragmentation is complete. Callers of this function
29637  * must set mp->b_prev to one of these values:
29638  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29639  * prior to handing over the mp as first argument to this function.
29640  *
29641  * If the ire passed by caller is incomplete, this function
29642  * queues the packet and if necessary, sends ARP request and bails.
29643  * If the ire passed is fully resolved, we simply prepend
29644  * the link-layer header to the packet, do ipsec hw acceleration
29645  * work if necessary, and send the packet out on the wire.
29646  *
29647  * NOTE: IPsec will only call this function with fully resolved
29648  * ires if hw acceleration is involved.
29649  * TODO list :
29650  * 	a Handle M_MULTIDATA so that
29651  *	  tcp_multisend->tcp_multisend_data can
29652  *	  call ip_xmit_v4 directly
29653  *	b Handle post-ARP work for fragments so that
29654  *	  ip_wput_frag can call this function.
29655  */
29656 ipxmit_state_t
29657 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29658     boolean_t flow_ctl_enabled, conn_t *connp)
29659 {
29660 	nce_t		*arpce;
29661 	ipha_t		*ipha;
29662 	queue_t		*q;
29663 	int		ill_index;
29664 	mblk_t		*nxt_mp, *first_mp;
29665 	boolean_t	xmit_drop = B_FALSE;
29666 	ip_proc_t	proc;
29667 	ill_t		*out_ill;
29668 	int		pkt_len;
29669 
29670 	arpce = ire->ire_nce;
29671 	ASSERT(arpce != NULL);
29672 
29673 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29674 
29675 	mutex_enter(&arpce->nce_lock);
29676 	switch (arpce->nce_state) {
29677 	case ND_REACHABLE:
29678 		/* If there are other queued packets, queue this packet */
29679 		if (arpce->nce_qd_mp != NULL) {
29680 			if (mp != NULL)
29681 				nce_queue_mp_common(arpce, mp, B_FALSE);
29682 			mp = arpce->nce_qd_mp;
29683 		}
29684 		arpce->nce_qd_mp = NULL;
29685 		mutex_exit(&arpce->nce_lock);
29686 
29687 		/*
29688 		 * Flush the queue.  In the common case, where the
29689 		 * ARP is already resolved,  it will go through the
29690 		 * while loop only once.
29691 		 */
29692 		while (mp != NULL) {
29693 
29694 			nxt_mp = mp->b_next;
29695 			mp->b_next = NULL;
29696 			ASSERT(mp->b_datap->db_type != M_CTL);
29697 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29698 			/*
29699 			 * This info is needed for IPQOS to do COS marking
29700 			 * in ip_wput_attach_llhdr->ip_process.
29701 			 */
29702 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29703 			mp->b_prev = NULL;
29704 
29705 			/* set up ill index for outbound qos processing */
29706 			out_ill = ire_to_ill(ire);
29707 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29708 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29709 			    ill_index, &ipha);
29710 			if (first_mp == NULL) {
29711 				xmit_drop = B_TRUE;
29712 				BUMP_MIB(out_ill->ill_ip_mib,
29713 				    ipIfStatsOutDiscards);
29714 				goto next_mp;
29715 			}
29716 
29717 			/* non-ipsec hw accel case */
29718 			if (io == NULL || !io->ipsec_out_accelerated) {
29719 				/* send it */
29720 				q = ire->ire_stq;
29721 				if (proc == IPP_FWD_OUT) {
29722 					UPDATE_IB_PKT_COUNT(ire);
29723 				} else {
29724 					UPDATE_OB_PKT_COUNT(ire);
29725 				}
29726 				ire->ire_last_used_time = lbolt;
29727 
29728 				if (flow_ctl_enabled || canputnext(q)) {
29729 					if (proc == IPP_FWD_OUT) {
29730 
29731 					BUMP_MIB(out_ill->ill_ip_mib,
29732 					    ipIfStatsHCOutForwDatagrams);
29733 
29734 					}
29735 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29736 					    pkt_len);
29737 
29738 					DTRACE_IP7(send, mblk_t *, first_mp,
29739 					    conn_t *, NULL, void_ip_t *, ipha,
29740 					    __dtrace_ipsr_ill_t *, out_ill,
29741 					    ipha_t *, ipha, ip6_t *, NULL, int,
29742 					    0);
29743 
29744 					ILL_SEND_TX(out_ill,
29745 					    ire, connp, first_mp, 0, connp);
29746 				} else {
29747 					BUMP_MIB(out_ill->ill_ip_mib,
29748 					    ipIfStatsOutDiscards);
29749 					xmit_drop = B_TRUE;
29750 					freemsg(first_mp);
29751 				}
29752 			} else {
29753 				/*
29754 				 * Safety Pup says: make sure this
29755 				 *  is going to the right interface!
29756 				 */
29757 				ill_t *ill1 =
29758 				    (ill_t *)ire->ire_stq->q_ptr;
29759 				int ifindex =
29760 				    ill1->ill_phyint->phyint_ifindex;
29761 				if (ifindex !=
29762 				    io->ipsec_out_capab_ill_index) {
29763 					xmit_drop = B_TRUE;
29764 					freemsg(mp);
29765 				} else {
29766 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29767 					    pkt_len);
29768 
29769 					DTRACE_IP7(send, mblk_t *, first_mp,
29770 					    conn_t *, NULL, void_ip_t *, ipha,
29771 					    __dtrace_ipsr_ill_t *, ill1,
29772 					    ipha_t *, ipha, ip6_t *, NULL,
29773 					    int, 0);
29774 
29775 					ipsec_hw_putnext(ire->ire_stq, mp);
29776 				}
29777 			}
29778 next_mp:
29779 			mp = nxt_mp;
29780 		} /* while (mp != NULL) */
29781 		if (xmit_drop)
29782 			return (SEND_FAILED);
29783 		else
29784 			return (SEND_PASSED);
29785 
29786 	case ND_INITIAL:
29787 	case ND_INCOMPLETE:
29788 
29789 		/*
29790 		 * While we do send off packets to dests that
29791 		 * use fully-resolved CGTP routes, we do not
29792 		 * handle unresolved CGTP routes.
29793 		 */
29794 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29795 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29796 
29797 		if (mp != NULL) {
29798 			/* queue the packet */
29799 			nce_queue_mp_common(arpce, mp, B_FALSE);
29800 		}
29801 
29802 		if (arpce->nce_state == ND_INCOMPLETE) {
29803 			mutex_exit(&arpce->nce_lock);
29804 			DTRACE_PROBE3(ip__xmit__incomplete,
29805 			    (ire_t *), ire, (mblk_t *), mp,
29806 			    (ipsec_out_t *), io);
29807 			return (LOOKUP_IN_PROGRESS);
29808 		}
29809 
29810 		arpce->nce_state = ND_INCOMPLETE;
29811 		mutex_exit(&arpce->nce_lock);
29812 
29813 		/*
29814 		 * Note that ire_add() (called from ire_forward())
29815 		 * holds a ref on the ire until ARP is completed.
29816 		 */
29817 		ire_arpresolve(ire);
29818 		return (LOOKUP_IN_PROGRESS);
29819 	default:
29820 		ASSERT(0);
29821 		mutex_exit(&arpce->nce_lock);
29822 		return (LLHDR_RESLV_FAILED);
29823 	}
29824 }
29825 
29826 #undef	UPDATE_IP_MIB_OB_COUNTERS
29827 
29828 /*
29829  * Return B_TRUE if the buffers differ in length or content.
29830  * This is used for comparing extension header buffers.
29831  * Note that an extension header would be declared different
29832  * even if all that changed was the next header value in that header i.e.
29833  * what really changed is the next extension header.
29834  */
29835 boolean_t
29836 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29837     uint_t blen)
29838 {
29839 	if (!b_valid)
29840 		blen = 0;
29841 
29842 	if (alen != blen)
29843 		return (B_TRUE);
29844 	if (alen == 0)
29845 		return (B_FALSE);	/* Both zero length */
29846 	return (bcmp(abuf, bbuf, alen));
29847 }
29848 
29849 /*
29850  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29851  * Return B_FALSE if memory allocation fails - don't change any state!
29852  */
29853 boolean_t
29854 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29855     const void *src, uint_t srclen)
29856 {
29857 	void *dst;
29858 
29859 	if (!src_valid)
29860 		srclen = 0;
29861 
29862 	ASSERT(*dstlenp == 0);
29863 	if (src != NULL && srclen != 0) {
29864 		dst = mi_alloc(srclen, BPRI_MED);
29865 		if (dst == NULL)
29866 			return (B_FALSE);
29867 	} else {
29868 		dst = NULL;
29869 	}
29870 	if (*dstp != NULL)
29871 		mi_free(*dstp);
29872 	*dstp = dst;
29873 	*dstlenp = dst == NULL ? 0 : srclen;
29874 	return (B_TRUE);
29875 }
29876 
29877 /*
29878  * Replace what is in *dst, *dstlen with the source.
29879  * Assumes ip_allocbuf has already been called.
29880  */
29881 void
29882 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29883     const void *src, uint_t srclen)
29884 {
29885 	if (!src_valid)
29886 		srclen = 0;
29887 
29888 	ASSERT(*dstlenp == srclen);
29889 	if (src != NULL && srclen != 0)
29890 		bcopy(src, *dstp, srclen);
29891 }
29892 
29893 /*
29894  * Free the storage pointed to by the members of an ip6_pkt_t.
29895  */
29896 void
29897 ip6_pkt_free(ip6_pkt_t *ipp)
29898 {
29899 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29900 
29901 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29902 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29903 		ipp->ipp_hopopts = NULL;
29904 		ipp->ipp_hopoptslen = 0;
29905 	}
29906 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29907 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29908 		ipp->ipp_rtdstopts = NULL;
29909 		ipp->ipp_rtdstoptslen = 0;
29910 	}
29911 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29912 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29913 		ipp->ipp_dstopts = NULL;
29914 		ipp->ipp_dstoptslen = 0;
29915 	}
29916 	if (ipp->ipp_fields & IPPF_RTHDR) {
29917 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29918 		ipp->ipp_rthdr = NULL;
29919 		ipp->ipp_rthdrlen = 0;
29920 	}
29921 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29922 	    IPPF_RTHDR);
29923 }
29924 
29925 zoneid_t
29926 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29927     zoneid_t lookup_zoneid)
29928 {
29929 	ire_t		*ire;
29930 	int		ire_flags = MATCH_IRE_TYPE;
29931 	zoneid_t	zoneid = ALL_ZONES;
29932 
29933 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29934 		return (ALL_ZONES);
29935 
29936 	if (lookup_zoneid != ALL_ZONES)
29937 		ire_flags |= MATCH_IRE_ZONEONLY;
29938 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29939 	    lookup_zoneid, NULL, ire_flags, ipst);
29940 	if (ire != NULL) {
29941 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29942 		ire_refrele(ire);
29943 	}
29944 	return (zoneid);
29945 }
29946 
29947 zoneid_t
29948 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29949     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29950 {
29951 	ire_t		*ire;
29952 	int		ire_flags = MATCH_IRE_TYPE;
29953 	zoneid_t	zoneid = ALL_ZONES;
29954 	ipif_t		*ipif_arg = NULL;
29955 
29956 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29957 		return (ALL_ZONES);
29958 
29959 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
29960 		ire_flags |= MATCH_IRE_ILL;
29961 		ipif_arg = ill->ill_ipif;
29962 	}
29963 	if (lookup_zoneid != ALL_ZONES)
29964 		ire_flags |= MATCH_IRE_ZONEONLY;
29965 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
29966 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
29967 	if (ire != NULL) {
29968 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29969 		ire_refrele(ire);
29970 	}
29971 	return (zoneid);
29972 }
29973 
29974 /*
29975  * IP obserability hook support functions.
29976  */
29977 
29978 static void
29979 ipobs_init(ip_stack_t *ipst)
29980 {
29981 	ipst->ips_ipobs_enabled = B_FALSE;
29982 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
29983 	    offsetof(ipobs_cb_t, ipobs_cbnext));
29984 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
29985 	ipst->ips_ipobs_cb_nwalkers = 0;
29986 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
29987 }
29988 
29989 static void
29990 ipobs_fini(ip_stack_t *ipst)
29991 {
29992 	ipobs_cb_t *cb;
29993 
29994 	mutex_enter(&ipst->ips_ipobs_cb_lock);
29995 	while (ipst->ips_ipobs_cb_nwalkers != 0)
29996 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
29997 
29998 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
29999 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30000 		kmem_free(cb, sizeof (*cb));
30001 	}
30002 	list_destroy(&ipst->ips_ipobs_cb_list);
30003 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30004 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30005 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30006 }
30007 
30008 void
30009 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30010     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30011 {
30012 	mblk_t *mp2;
30013 	ipobs_cb_t *ipobs_cb;
30014 	ipobs_hook_data_t *ihd;
30015 	uint64_t grifindex = 0;
30016 
30017 	ASSERT(DB_TYPE(mp) == M_DATA);
30018 
30019 	if (IS_UNDER_IPMP(ill))
30020 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
30021 
30022 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30023 	ipst->ips_ipobs_cb_nwalkers++;
30024 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30025 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30026 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30027 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
30028 		if (mp2 != NULL) {
30029 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
30030 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30031 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30032 				freemsg(mp2);
30033 				continue;
30034 			}
30035 			ihd->ihd_mp->b_rptr += hlen;
30036 			ihd->ihd_htype = htype;
30037 			ihd->ihd_ipver = ipver;
30038 			ihd->ihd_zsrc = zsrc;
30039 			ihd->ihd_zdst = zdst;
30040 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30041 			ihd->ihd_grifindex = grifindex;
30042 			ihd->ihd_stack = ipst->ips_netstack;
30043 			mp2->b_wptr += sizeof (*ihd);
30044 			ipobs_cb->ipobs_cbfunc(mp2);
30045 		}
30046 	}
30047 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30048 	ipst->ips_ipobs_cb_nwalkers--;
30049 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30050 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30051 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30052 }
30053 
30054 void
30055 ipobs_register_hook(netstack_t *ns, pfv_t func)
30056 {
30057 	ipobs_cb_t   *cb;
30058 	ip_stack_t *ipst = ns->netstack_ip;
30059 
30060 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30061 
30062 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30063 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30064 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30065 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30066 
30067 	cb->ipobs_cbfunc = func;
30068 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30069 	ipst->ips_ipobs_enabled = B_TRUE;
30070 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30071 }
30072 
30073 void
30074 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30075 {
30076 	ipobs_cb_t	*curcb;
30077 	ip_stack_t	*ipst = ns->netstack_ip;
30078 
30079 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30080 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30081 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30082 
30083 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30084 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30085 		if (func == curcb->ipobs_cbfunc) {
30086 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30087 			kmem_free(curcb, sizeof (*curcb));
30088 			break;
30089 		}
30090 	}
30091 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30092 		ipst->ips_ipobs_enabled = B_FALSE;
30093 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30094 }
30095