xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision c279fc79)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/dlpi.h>
31 #include <sys/stropts.h>
32 #include <sys/sysmacros.h>
33 #include <sys/strsubr.h>
34 #include <sys/strlog.h>
35 #include <sys/strsun.h>
36 #include <sys/zone.h>
37 #define	_SUN_TPI_VERSION 2
38 #include <sys/tihdr.h>
39 #include <sys/xti_inet.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/kobj.h>
44 #include <sys/modctl.h>
45 #include <sys/atomic.h>
46 #include <sys/policy.h>
47 #include <sys/priv.h>
48 #include <sys/taskq.h>
49 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 #include <sys/squeue_impl.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
132  * IP_SQUEUE_ENTER: SQ_PROCESS
133  * IP_SQUEUE_FILL: SQ_FILL
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 int ip_squeue_flag;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	uint_t		ird_flags;	/* see below */
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 #define	IRD_REPORT_TESTHIDDEN	0x01	/* include IRE_MARK_TESTHIDDEN routes */
180 
181 /*
182  * Cluster specific hooks. These should be NULL when booted as a non-cluster
183  */
184 
185 /*
186  * Hook functions to enable cluster networking
187  * On non-clustered systems these vectors must always be NULL.
188  *
189  * Hook function to Check ip specified ip address is a shared ip address
190  * in the cluster
191  *
192  */
193 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
194     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
195 
196 /*
197  * Hook function to generate cluster wide ip fragment identifier
198  */
199 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
201     void *args) = NULL;
202 
203 /*
204  * Hook function to generate cluster wide SPI.
205  */
206 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
207     void *) = NULL;
208 
209 /*
210  * Hook function to verify if the SPI is already utlized.
211  */
212 
213 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
214 
215 /*
216  * Hook function to delete the SPI from the cluster wide repository.
217  */
218 
219 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
220 
221 /*
222  * Hook function to inform the cluster when packet received on an IDLE SA
223  */
224 
225 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
226     in6_addr_t, in6_addr_t, void *) = NULL;
227 
228 /*
229  * Synchronization notes:
230  *
231  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
232  * MT level protection given by STREAMS. IP uses a combination of its own
233  * internal serialization mechanism and standard Solaris locking techniques.
234  * The internal serialization is per phyint.  This is used to serialize
235  * plumbing operations, certain multicast operations, most set ioctls,
236  * igmp/mld timers etc.
237  *
238  * Plumbing is a long sequence of operations involving message
239  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
240  * involved in plumbing operations. A natural model is to serialize these
241  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
242  * parallel without any interference. But various set ioctls on hme0 are best
243  * serialized, along with multicast join/leave operations, igmp/mld timer
244  * operations, and processing of DLPI control messages received from drivers
245  * on a per phyint basis.  This serialization is provided by the ipsq_t and
246  * primitives operating on this. Details can be found in ip_if.c above the
247  * core primitives operating on ipsq_t.
248  *
249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
251  * In addition ipif's and ill's referenced by the ire are also indirectly
252  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
253  * the ipif's address or netmask change as long as an ipif is refheld
254  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
255  * address of an ipif has to go through the ipsq_t. This ensures that only
256  * 1 such exclusive operation proceeds at any time on the ipif. It then
257  * deletes all ires associated with this ipif, and waits for all refcnts
258  * associated with this ipif to come down to zero. The address is changed
259  * only after the ipif has been quiesced. Then the ipif is brought up again.
260  * More details are described above the comment in ip_sioctl_flags.
261  *
262  * Packet processing is based mostly on IREs and are fully multi-threaded
263  * using standard Solaris MT techniques.
264  *
265  * There are explicit locks in IP to handle:
266  * - The ip_g_head list maintained by mi_open_link() and friends.
267  *
268  * - The reassembly data structures (one lock per hash bucket)
269  *
270  * - conn_lock is meant to protect conn_t fields. The fields actually
271  *   protected by conn_lock are documented in the conn_t definition.
272  *
273  * - ire_lock to protect some of the fields of the ire, IRE tables
274  *   (one lock per hash bucket). Refer to ip_ire.c for details.
275  *
276  * - ndp_g_lock and nce_lock for protecting NCEs.
277  *
278  * - ill_lock protects fields of the ill and ipif. Details in ip.h
279  *
280  * - ill_g_lock: This is a global reader/writer lock. Protects the following
281  *	* The AVL tree based global multi list of all ills.
282  *	* The linked list of all ipifs of an ill
283  *	* The <ipsq-xop> mapping
284  *	* <ill-phyint> association
285  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
286  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
287  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
288  *   writer for the actual duration of the insertion/deletion/change.
289  *
290  * - ill_lock:  This is a per ill mutex.
291  *   It protects some members of the ill_t struct; see ip.h for details.
292  *   It also protects the <ill-phyint> assoc.
293  *   It also protects the list of ipifs hanging off the ill.
294  *
295  * - ipsq_lock: This is a per ipsq_t mutex lock.
296  *   This protects some members of the ipsq_t struct; see ip.h for details.
297  *   It also protects the <ipsq-ipxop> mapping
298  *
299  * - ipx_lock: This is a per ipxop_t mutex lock.
300  *   This protects some members of the ipxop_t struct; see ip.h for details.
301  *
302  * - phyint_lock: This is a per phyint mutex lock. Protects just the
303  *   phyint_flags
304  *
305  * - ip_g_nd_lock: This is a global reader/writer lock.
306  *   Any call to nd_load to load a new parameter to the ND table must hold the
307  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
308  *   as reader.
309  *
310  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
311  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
312  *   uniqueness check also done atomically.
313  *
314  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
315  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
316  *   as a writer when adding or deleting elements from these lists, and
317  *   as a reader when walking these lists to send a SADB update to the
318  *   IPsec capable ills.
319  *
320  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
321  *   group list linked by ill_usesrc_grp_next. It also protects the
322  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
323  *   group is being added or deleted.  This lock is taken as a reader when
324  *   walking the list/group(eg: to get the number of members in a usesrc group).
325  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
326  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
327  *   example, it is not necessary to take this lock in the initial portion
328  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
329  *   operations are executed exclusively and that ensures that the "usesrc
330  *   group state" cannot change. The "usesrc group state" change can happen
331  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
332  *
333  * Changing <ill-phyint>, <ipsq-xop> assocications:
334  *
335  * To change the <ill-phyint> association, the ill_g_lock must be held
336  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
337  * must be held.
338  *
339  * To change the <ipsq-xop> association, the ill_g_lock must be held as
340  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
341  * This is only done when ills are added or removed from IPMP groups.
342  *
343  * To add or delete an ipif from the list of ipifs hanging off the ill,
344  * ill_g_lock (writer) and ill_lock must be held and the thread must be
345  * a writer on the associated ipsq.
346  *
347  * To add or delete an ill to the system, the ill_g_lock must be held as
348  * writer and the thread must be a writer on the associated ipsq.
349  *
350  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
351  * must be a writer on the associated ipsq.
352  *
353  * Lock hierarchy
354  *
355  * Some lock hierarchy scenarios are listed below.
356  *
357  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
358  * ill_g_lock -> ill_lock(s) -> phyint_lock
359  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
360  * ill_g_lock -> ip_addr_avail_lock
361  * conn_lock -> irb_lock -> ill_lock -> ire_lock
362  * ill_g_lock -> ip_g_nd_lock
363  *
364  * When more than 1 ill lock is needed to be held, all ill lock addresses
365  * are sorted on address and locked starting from highest addressed lock
366  * downward.
367  *
368  * IPsec scenarios
369  *
370  * ipsa_lock -> ill_g_lock -> ill_lock
371  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
372  * ipsec_capab_ills_lock -> ipsa_lock
373  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
374  *
375  * Trusted Solaris scenarios
376  *
377  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
378  * igsa_lock -> gcdb_lock
379  * gcgrp_rwlock -> ire_lock
380  * gcgrp_rwlock -> gcdb_lock
381  *
382  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
383  *
384  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
385  * sq_lock -> conn_lock -> QLOCK(q)
386  * ill_lock -> ft_lock -> fe_lock
387  *
388  * Routing/forwarding table locking notes:
389  *
390  * Lock acquisition order: Radix tree lock, irb_lock.
391  * Requirements:
392  * i.  Walker must not hold any locks during the walker callback.
393  * ii  Walker must not see a truncated tree during the walk because of any node
394  *     deletion.
395  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
396  *     in many places in the code to walk the irb list. Thus even if all the
397  *     ires in a bucket have been deleted, we still can't free the radix node
398  *     until the ires have actually been inactive'd (freed).
399  *
400  * Tree traversal - Need to hold the global tree lock in read mode.
401  * Before dropping the global tree lock, need to either increment the ire_refcnt
402  * to ensure that the radix node can't be deleted.
403  *
404  * Tree add - Need to hold the global tree lock in write mode to add a
405  * radix node. To prevent the node from being deleted, increment the
406  * irb_refcnt, after the node is added to the tree. The ire itself is
407  * added later while holding the irb_lock, but not the tree lock.
408  *
409  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
410  * All associated ires must be inactive (i.e. freed), and irb_refcnt
411  * must be zero.
412  *
413  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
414  * global tree lock (read mode) for traversal.
415  *
416  * IPsec notes :
417  *
418  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
419  * in front of the actual packet. For outbound datagrams, the M_CTL
420  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
421  * information used by the IPsec code for applying the right level of
422  * protection. The information initialized by IP in the ipsec_out_t
423  * is determined by the per-socket policy or global policy in the system.
424  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
425  * ipsec_info.h) which starts out with nothing in it. It gets filled
426  * with the right information if it goes through the AH/ESP code, which
427  * happens if the incoming packet is secure. The information initialized
428  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
429  * the policy requirements needed by per-socket policy or global policy
430  * is met or not.
431  *
432  * If there is both per-socket policy (set using setsockopt) and there
433  * is also global policy match for the 5 tuples of the socket,
434  * ipsec_override_policy() makes the decision of which one to use.
435  *
436  * For fully connected sockets i.e dst, src [addr, port] is known,
437  * conn_policy_cached is set indicating that policy has been cached.
438  * conn_in_enforce_policy may or may not be set depending on whether
439  * there is a global policy match or per-socket policy match.
440  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
441  * Once the right policy is set on the conn_t, policy cannot change for
442  * this socket. This makes life simpler for TCP (UDP ?) where
443  * re-transmissions go out with the same policy. For symmetry, policy
444  * is cached for fully connected UDP sockets also. Thus if policy is cached,
445  * it also implies that policy is latched i.e policy cannot change
446  * on these sockets. As we have the right policy on the conn, we don't
447  * have to lookup global policy for every outbound and inbound datagram
448  * and thus serving as an optimization. Note that a global policy change
449  * does not affect fully connected sockets if they have policy. If fully
450  * connected sockets did not have any policy associated with it, global
451  * policy change may affect them.
452  *
453  * IP Flow control notes:
454  * ---------------------
455  * Non-TCP streams are flow controlled by IP. The way this is accomplished
456  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
457  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
458  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
459  * functions.
460  *
461  * Per Tx ring udp flow control:
462  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
463  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
464  *
465  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
466  * To achieve best performance, outgoing traffic need to be fanned out among
467  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
468  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
469  * the address of connp as fanout hint to mac_tx(). Under flow controlled
470  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
471  * cookie points to a specific Tx ring that is blocked. The cookie is used to
472  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
473  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
474  * connp's. The drain list is not a single list but a configurable number of
475  * lists.
476  *
477  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
478  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
479  * which is equal to 128. This array in turn contains a pointer to idl_t[],
480  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
481  * list will point to the list of connp's that are flow controlled.
482  *
483  *                      ---------------   -------   -------   -------
484  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
485  *                   |  ---------------   -------   -------   -------
486  *                   |  ---------------   -------   -------   -------
487  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
488  * ----------------  |  ---------------   -------   -------   -------
489  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
490  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
491  *                   |  ---------------   -------   -------   -------
492  *                   .        .              .         .         .
493  *                   |  ---------------   -------   -------   -------
494  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
495  *                      ---------------   -------   -------   -------
496  *                      ---------------   -------   -------   -------
497  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
498  *                   |  ---------------   -------   -------   -------
499  *                   |  ---------------   -------   -------   -------
500  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
501  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
502  * ----------------  |        .              .         .         .
503  *                   |  ---------------   -------   -------   -------
504  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
505  *                      ---------------   -------   -------   -------
506  *     .....
507  * ----------------
508  * |idl_tx_list[n]|-> ...
509  * ----------------
510  *
511  * When mac_tx() returns a cookie, the cookie is used to hash into a
512  * idl_tx_list in ips_idl_tx_list[] array. Then conn_drain_insert() is
513  * called passing idl_tx_list. The connp gets inserted in a drain list
514  * pointed to by idl_tx_list. conn_drain_list() asserts flow control for
515  * the sockets (non stream based) and sets QFULL condition for conn_wq.
516  * connp->conn_direct_blocked will be set to indicate the blocked
517  * condition.
518  *
519  * GLDv3 mac layer calls ill_flow_enable() when flow control is relieved.
520  * A cookie is passed in the call to ill_flow_enable() that identifies the
521  * blocked Tx ring. This cookie is used to get to the idl_tx_list that
522  * contains the blocked connp's. conn_walk_drain() uses the idl_tx_list_t
523  * and goes through each of the drain list (q)enabling the conn_wq of the
524  * first conn in each of the drain list. This causes ip_wsrv to run for the
525  * conn. ip_wsrv drains the queued messages, and removes the conn from the
526  * drain list, if all messages were drained. It also qenables the next conn
527  * in the drain list to continue the drain process.
528  *
529  * In reality the drain list is not a single list, but a configurable number
530  * of lists. conn_drain_walk() in the IP module, qenables the first conn in
531  * each list. If the ip_wsrv of the next qenabled conn does not run, because
532  * the stream closes, ip_close takes responsibility to qenable the next conn
533  * in the drain list. conn_drain_insert and conn_drain_tail are the only
534  * functions that manipulate this drain list. conn_drain_insert is called in
535  * ip_wput context itself (as opposed to from ip_wsrv context for STREAMS
536  * case -- see below). The synchronization between drain insertion and flow
537  * control wakeup is handled by using idl_txl->txl_lock.
538  *
539  * Flow control using STREAMS:
540  * When ILL_DIRECT_CAPABLE() is not TRUE, STREAMS flow control mechanism
541  * is used. On the send side, if the packet cannot be sent down to the
542  * driver by IP, because of a canput failure, IP does a putq on the conn_wq.
543  * This will cause ip_wsrv to run on the conn_wq. ip_wsrv in turn, inserts
544  * the conn in a list of conn's that need to be drained when the flow
545  * control condition subsides. The blocked connps are put in first member
546  * of ips_idl_tx_list[] array. Ultimately STREAMS backenables the ip_wsrv
547  * on the IP module. It calls conn_walk_drain() passing ips_idl_tx_list[0].
548  * ips_idl_tx_list[0] contains the drain lists of blocked conns. The
549  * conn_wq of the first conn in the drain lists is (q)enabled to run.
550  * ip_wsrv on this conn drains the queued messages, and removes the conn
551  * from the drain list, if all messages were drained. It also qenables the
552  * next conn in the drain list to continue the drain process.
553  *
554  * If the ip_wsrv of the next qenabled conn does not run, because the
555  * stream closes, ip_close takes responsibility to qenable the next conn in
556  * the drain list. The directly called ip_wput path always does a putq, if
557  * it cannot putnext. Thus synchronization problems are handled between
558  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
559  * functions that manipulate this drain list. Furthermore conn_drain_insert
560  * is called only from ip_wsrv for the STREAMS case, and there can be only 1
561  * instance of ip_wsrv running on a queue at any time. conn_drain_tail can
562  * be simultaneously called from both ip_wsrv and ip_close.
563  *
564  * IPQOS notes:
565  *
566  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
567  * and IPQoS modules. IPPF includes hooks in IP at different control points
568  * (callout positions) which direct packets to IPQoS modules for policy
569  * processing. Policies, if present, are global.
570  *
571  * The callout positions are located in the following paths:
572  *		o local_in (packets destined for this host)
573  *		o local_out (packets orginating from this host )
574  *		o fwd_in  (packets forwarded by this m/c - inbound)
575  *		o fwd_out (packets forwarded by this m/c - outbound)
576  * Hooks at these callout points can be enabled/disabled using the ndd variable
577  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
578  * By default all the callout positions are enabled.
579  *
580  * Outbound (local_out)
581  * Hooks are placed in ip_wput_ire and ipsec_out_process.
582  *
583  * Inbound (local_in)
584  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
585  * TCP and UDP fanout routines.
586  *
587  * Forwarding (in and out)
588  * Hooks are placed in ip_rput_forward.
589  *
590  * IP Policy Framework processing (IPPF processing)
591  * Policy processing for a packet is initiated by ip_process, which ascertains
592  * that the classifier (ipgpc) is loaded and configured, failing which the
593  * packet resumes normal processing in IP. If the clasifier is present, the
594  * packet is acted upon by one or more IPQoS modules (action instances), per
595  * filters configured in ipgpc and resumes normal IP processing thereafter.
596  * An action instance can drop a packet in course of its processing.
597  *
598  * A boolean variable, ip_policy, is used in all the fanout routines that can
599  * invoke ip_process for a packet. This variable indicates if the packet should
600  * to be sent for policy processing. The variable is set to B_TRUE by default,
601  * i.e. when the routines are invoked in the normal ip procesing path for a
602  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
603  * ip_policy is set to B_FALSE for all the routines called in these two
604  * functions because, in the former case,  we don't process loopback traffic
605  * currently while in the latter, the packets have already been processed in
606  * icmp_inbound.
607  *
608  * Zones notes:
609  *
610  * The partitioning rules for networking are as follows:
611  * 1) Packets coming from a zone must have a source address belonging to that
612  * zone.
613  * 2) Packets coming from a zone can only be sent on a physical interface on
614  * which the zone has an IP address.
615  * 3) Between two zones on the same machine, packet delivery is only allowed if
616  * there's a matching route for the destination and zone in the forwarding
617  * table.
618  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
619  * different zones can bind to the same port with the wildcard address
620  * (INADDR_ANY).
621  *
622  * The granularity of interface partitioning is at the logical interface level.
623  * Therefore, every zone has its own IP addresses, and incoming packets can be
624  * attributed to a zone unambiguously. A logical interface is placed into a zone
625  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
626  * structure. Rule (1) is implemented by modifying the source address selection
627  * algorithm so that the list of eligible addresses is filtered based on the
628  * sending process zone.
629  *
630  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
631  * across all zones, depending on their type. Here is the break-up:
632  *
633  * IRE type				Shared/exclusive
634  * --------				----------------
635  * IRE_BROADCAST			Exclusive
636  * IRE_DEFAULT (default routes)		Shared (*)
637  * IRE_LOCAL				Exclusive (x)
638  * IRE_LOOPBACK				Exclusive
639  * IRE_PREFIX (net routes)		Shared (*)
640  * IRE_CACHE				Exclusive
641  * IRE_IF_NORESOLVER (interface routes)	Exclusive
642  * IRE_IF_RESOLVER (interface routes)	Exclusive
643  * IRE_HOST (host routes)		Shared (*)
644  *
645  * (*) A zone can only use a default or off-subnet route if the gateway is
646  * directly reachable from the zone, that is, if the gateway's address matches
647  * one of the zone's logical interfaces.
648  *
649  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
650  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
651  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
652  * address of the zone itself (the destination). Since IRE_LOCAL is used
653  * for communication between zones, ip_wput_ire has special logic to set
654  * the right source address when sending using an IRE_LOCAL.
655  *
656  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
657  * ire_cache_lookup restricts loopback using an IRE_LOCAL
658  * between zone to the case when L2 would have conceptually looped the packet
659  * back, i.e. the loopback which is required since neither Ethernet drivers
660  * nor Ethernet hardware loops them back. This is the case when the normal
661  * routes (ignoring IREs with different zoneids) would send out the packet on
662  * the same ill as the ill with which is IRE_LOCAL is associated.
663  *
664  * Multiple zones can share a common broadcast address; typically all zones
665  * share the 255.255.255.255 address. Incoming as well as locally originated
666  * broadcast packets must be dispatched to all the zones on the broadcast
667  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
668  * since some zones may not be on the 10.16.72/24 network. To handle this, each
669  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
670  * sent to every zone that has an IRE_BROADCAST entry for the destination
671  * address on the input ill, see conn_wantpacket().
672  *
673  * Applications in different zones can join the same multicast group address.
674  * For IPv4, group memberships are per-logical interface, so they're already
675  * inherently part of a zone. For IPv6, group memberships are per-physical
676  * interface, so we distinguish IPv6 group memberships based on group address,
677  * interface and zoneid. In both cases, received multicast packets are sent to
678  * every zone for which a group membership entry exists. On IPv6 we need to
679  * check that the target zone still has an address on the receiving physical
680  * interface; it could have been removed since the application issued the
681  * IPV6_JOIN_GROUP.
682  */
683 
684 /*
685  * Squeue Fanout flags:
686  *	0: No fanout.
687  *	1: Fanout across all squeues
688  */
689 boolean_t	ip_squeue_fanout = 0;
690 
691 /*
692  * Maximum dups allowed per packet.
693  */
694 uint_t ip_max_frag_dups = 10;
695 
696 #define	IS_SIMPLE_IPH(ipha)						\
697 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
698 
699 /* RFC 1122 Conformance */
700 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
701 
702 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
703 
704 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
705 
706 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
707 		    cred_t *credp, boolean_t isv6);
708 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
709 		    ipha_t **);
710 
711 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
712 		    ip_stack_t *);
713 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
714 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
715 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
716 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
717 		    mblk_t *, int, ip_stack_t *);
718 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
719 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
720 		    ill_t *, zoneid_t);
721 static void	icmp_options_update(ipha_t *);
722 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
723 		    ip_stack_t *);
724 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
725 		    zoneid_t zoneid, ip_stack_t *);
726 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
727 static void	icmp_redirect(ill_t *, mblk_t *);
728 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
729 		    ip_stack_t *);
730 
731 static void	ip_arp_news(queue_t *, mblk_t *);
732 static boolean_t ip_bind_get_ire_v4(mblk_t **, ire_t *, iulp_t *, ip_stack_t *);
733 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
734 char		*ip_dot_addr(ipaddr_t, char *);
735 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
736 int		ip_close(queue_t *, int);
737 static char	*ip_dot_saddr(uchar_t *, char *);
738 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
739 		    boolean_t, boolean_t, ill_t *, zoneid_t);
740 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
741 		    boolean_t, boolean_t, zoneid_t);
742 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
743 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
744 static void	ip_lrput(queue_t *, mblk_t *);
745 ipaddr_t	ip_net_mask(ipaddr_t);
746 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
747 		    ip_stack_t *);
748 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
749 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
750 char		*ip_nv_lookup(nv_t *, int);
751 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
752 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
753 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
754 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
755     ipndp_t *, size_t);
756 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 void	ip_rput(queue_t *, mblk_t *);
758 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
759 		    void *dummy_arg);
760 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
761 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
762     ip_stack_t *);
763 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
764 			    ire_t *, ip_stack_t *);
765 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
766 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
767 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
768     ip_stack_t *);
769 static boolean_t ip_rput_fragment(ill_t *, ill_t *, mblk_t **, ipha_t *,
770     uint32_t *, uint16_t *);
771 int		ip_snmp_get(queue_t *, mblk_t *, int);
772 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
773 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
774 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
775 		    ip_stack_t *);
776 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
777 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
778 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
779 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
780 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
781 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
782 		    ip_stack_t *ipst);
783 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
784 		    ip_stack_t *ipst);
785 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
786 		    ip_stack_t *ipst);
787 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
788 		    ip_stack_t *ipst);
789 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
790 		    ip_stack_t *ipst);
791 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
792 		    ip_stack_t *ipst);
793 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
794 		    ip_stack_t *ipst);
795 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
796 		    ip_stack_t *ipst);
797 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
798 		    ip_stack_t *ipst);
799 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
800 		    ip_stack_t *ipst);
801 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
802 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
803 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
804 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
805 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
806 static boolean_t	ip_source_route_included(ipha_t *);
807 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
808 
809 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
810 		    zoneid_t, ip_stack_t *, conn_t *);
811 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *,
812 		    mblk_t *);
813 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
814 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
815 		    zoneid_t, ip_stack_t *);
816 
817 static void	conn_drain_init(ip_stack_t *);
818 static void	conn_drain_fini(ip_stack_t *);
819 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
820 
821 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
822 static void	conn_setqfull(conn_t *);
823 static void	conn_clrqfull(conn_t *);
824 
825 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
826 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
827 static void	ip_stack_fini(netstackid_t stackid, void *arg);
828 
829 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
830     zoneid_t);
831 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
832     void *dummy_arg);
833 
834 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
835 
836 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
837     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
838     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
839 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
840 
841 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
842 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
843     caddr_t, cred_t *);
844 extern int	ip_helper_stream_setup(queue_t *, dev_t *, int, int,
845     cred_t *, boolean_t);
846 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
847     caddr_t cp, cred_t *cr);
848 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
849     cred_t *);
850 static int	ip_squeue_switch(int);
851 
852 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
853 static void	ip_kstat_fini(netstackid_t, kstat_t *);
854 static int	ip_kstat_update(kstat_t *kp, int rw);
855 static void	*icmp_kstat_init(netstackid_t);
856 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
857 static int	icmp_kstat_update(kstat_t *kp, int rw);
858 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
859 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
860 
861 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
862     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
863 
864 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
865     ipha_t *, ill_t *, boolean_t, boolean_t);
866 
867 static void ipobs_init(ip_stack_t *);
868 static void ipobs_fini(ip_stack_t *);
869 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
870 
871 /* How long, in seconds, we allow frags to hang around. */
872 #define	IP_FRAG_TIMEOUT		15
873 #define	IPV6_FRAG_TIMEOUT	60
874 
875 /*
876  * Threshold which determines whether MDT should be used when
877  * generating IP fragments; payload size must be greater than
878  * this threshold for MDT to take place.
879  */
880 #define	IP_WPUT_FRAG_MDT_MIN	32768
881 
882 /* Setable in /etc/system only */
883 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
884 
885 static long ip_rput_pullups;
886 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
887 
888 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
889 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
890 
891 int	ip_debug;
892 
893 #ifdef DEBUG
894 uint32_t ipsechw_debug = 0;
895 #endif
896 
897 /*
898  * Multirouting/CGTP stuff
899  */
900 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
901 
902 /*
903  * XXX following really should only be in a header. Would need more
904  * header and .c clean up first.
905  */
906 extern optdb_obj_t	ip_opt_obj;
907 
908 ulong_t ip_squeue_enter_unbound = 0;
909 
910 /*
911  * Named Dispatch Parameter Table.
912  * All of these are alterable, within the min/max values given, at run time.
913  */
914 static ipparam_t	lcl_param_arr[] = {
915 	/* min	max	value	name */
916 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
917 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
918 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
919 	{  0,	1,	0,	"ip_respond_to_timestamp"},
920 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
921 	{  0,	1,	1,	"ip_send_redirects"},
922 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
923 	{  0,	10,	0,	"ip_mrtdebug"},
924 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
925 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
926 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
927 	{  1,	255,	255,	"ip_def_ttl" },
928 	{  0,	1,	0,	"ip_forward_src_routed"},
929 	{  0,	256,	32,	"ip_wroff_extra" },
930 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
931 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
932 	{  0,	1,	1,	"ip_path_mtu_discovery" },
933 	{  0,	240,	30,	"ip_ignore_delete_time" },
934 	{  0,	1,	0,	"ip_ignore_redirect" },
935 	{  0,	1,	1,	"ip_output_queue" },
936 	{  1,	254,	1,	"ip_broadcast_ttl" },
937 	{  0,	99999,	100,	"ip_icmp_err_interval" },
938 	{  1,	99999,	10,	"ip_icmp_err_burst" },
939 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
940 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
941 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
942 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
943 	{  0,	1,	1,	"icmp_accept_clear_messages" },
944 	{  0,	1,	1,	"igmp_accept_clear_messages" },
945 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
946 				"ip_ndp_delay_first_probe_time"},
947 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
948 				"ip_ndp_max_unicast_solicit"},
949 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
950 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
951 	{  0,	1,	0,	"ip6_forward_src_routed"},
952 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
953 	{  0,	1,	1,	"ip6_send_redirects"},
954 	{  0,	1,	0,	"ip6_ignore_redirect" },
955 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
956 
957 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
958 
959 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
960 
961 	{  0,	1,	1,	"pim_accept_clear_messages" },
962 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
963 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
964 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
965 	{  0,	15,	0,	"ip_policy_mask" },
966 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
967 	{  0,	255,	1,	"ip_multirt_ttl" },
968 	{  0,	1,	1,	"ip_multidata_outbound" },
969 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
970 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
971 	{  0,	1000,	1,	"ip_max_temp_defend" },
972 	{  0,	1000,	3,	"ip_max_defend" },
973 	{  0,	999999,	30,	"ip_defend_interval" },
974 	{  0,	3600000, 300000, "ip_dup_recovery" },
975 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
976 	{  0,	1,	1,	"ip_lso_outbound" },
977 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
978 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
979 	{ 68,	65535,	576,	"ip_pmtu_min" },
980 #ifdef DEBUG
981 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
982 #else
983 	{  0,	0,	0,	"" },
984 #endif
985 };
986 
987 /*
988  * Extended NDP table
989  * The addresses for the first two are filled in to be ips_ip_g_forward
990  * and ips_ipv6_forward at init time.
991  */
992 static ipndp_t	lcl_ndp_arr[] = {
993 	/* getf			setf		data			name */
994 #define	IPNDP_IP_FORWARDING_OFFSET	0
995 	{  ip_param_generic_get,	ip_forward_set,	NULL,
996 	    "ip_forwarding" },
997 #define	IPNDP_IP6_FORWARDING_OFFSET	1
998 	{  ip_param_generic_get,	ip_forward_set,	NULL,
999 	    "ip6_forwarding" },
1000 	{ ip_param_generic_get, ip_input_proc_set,
1001 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
1002 	{ ip_param_generic_get, ip_int_set,
1003 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
1004 #define	IPNDP_CGTP_FILTER_OFFSET	4
1005 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
1006 	    "ip_cgtp_filter" },
1007 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
1008 	    "ip_debug" },
1009 };
1010 
1011 /*
1012  * Table of IP ioctls encoding the various properties of the ioctl and
1013  * indexed based on the last byte of the ioctl command. Occasionally there
1014  * is a clash, and there is more than 1 ioctl with the same last byte.
1015  * In such a case 1 ioctl is encoded in the ndx table and the remaining
1016  * ioctls are encoded in the misc table. An entry in the ndx table is
1017  * retrieved by indexing on the last byte of the ioctl command and comparing
1018  * the ioctl command with the value in the ndx table. In the event of a
1019  * mismatch the misc table is then searched sequentially for the desired
1020  * ioctl command.
1021  *
1022  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
1023  */
1024 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
1025 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
1037 			MISC_CMD, ip_siocaddrt, NULL },
1038 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
1039 			MISC_CMD, ip_siocdelrt, NULL },
1040 
1041 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1042 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1043 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
1044 			IF_CMD, ip_sioctl_get_addr, NULL },
1045 
1046 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1047 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1048 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
1049 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
1050 
1051 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
1052 			IPI_PRIV | IPI_WR,
1053 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1054 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1055 			IPI_MODOK | IPI_GET_CMD,
1056 			IF_CMD, ip_sioctl_get_flags, NULL },
1057 
1058 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 
1061 	/* copyin size cannot be coded for SIOCGIFCONF */
1062 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1063 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1064 
1065 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1066 			IF_CMD, ip_sioctl_mtu, NULL },
1067 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
1068 			IF_CMD, ip_sioctl_get_mtu, NULL },
1069 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1070 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
1071 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1072 			IF_CMD, ip_sioctl_brdaddr, NULL },
1073 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1074 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
1075 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1076 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1077 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1078 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
1079 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1080 			IF_CMD, ip_sioctl_metric, NULL },
1081 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 
1083 	/* See 166-168 below for extended SIOC*XARP ioctls */
1084 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1085 			ARP_CMD, ip_sioctl_arp, NULL },
1086 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
1087 			ARP_CMD, ip_sioctl_arp, NULL },
1088 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
1089 			ARP_CMD, ip_sioctl_arp, NULL },
1090 
1091 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1114 			MISC_CMD, if_unitsel, if_unitsel_restart },
1115 
1116 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 
1135 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1136 			IPI_PRIV | IPI_WR | IPI_MODOK,
1137 			IF_CMD, ip_sioctl_sifname, NULL },
1138 
1139 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1142 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1143 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1147 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 
1153 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
1154 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1155 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
1156 			IF_CMD, ip_sioctl_get_muxid, NULL },
1157 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1158 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
1159 
1160 	/* Both if and lif variants share same func */
1161 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
1162 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1163 	/* Both if and lif variants share same func */
1164 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1165 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
1166 
1167 	/* copyin size cannot be coded for SIOCGIFCONF */
1168 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1169 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1170 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1171 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1172 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1173 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1174 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1175 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1176 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1177 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1178 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1179 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1180 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1181 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1182 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1183 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1184 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1185 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1186 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1187 
1188 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1189 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
1190 			ip_sioctl_removeif_restart },
1191 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1192 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_addif, NULL },
1194 #define	SIOCLIFADDR_NDX 112
1195 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1197 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1198 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
1199 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1200 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1201 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1202 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1203 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1204 			IPI_PRIV | IPI_WR,
1205 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1206 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1207 			IPI_GET_CMD | IPI_MODOK,
1208 			LIF_CMD, ip_sioctl_get_flags, NULL },
1209 
1210 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1211 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1212 
1213 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1214 			ip_sioctl_get_lifconf, NULL },
1215 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1216 			LIF_CMD, ip_sioctl_mtu, NULL },
1217 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
1218 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1219 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1220 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1221 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1222 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1223 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1224 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
1225 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1226 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1227 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1228 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
1229 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1230 			LIF_CMD, ip_sioctl_metric, NULL },
1231 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1232 			IPI_PRIV | IPI_WR | IPI_MODOK,
1233 			LIF_CMD, ip_sioctl_slifname,
1234 			ip_sioctl_slifname_restart },
1235 
1236 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
1237 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1238 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1239 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
1240 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1241 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1242 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1243 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1244 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1245 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1246 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1247 			LIF_CMD, ip_sioctl_token, NULL },
1248 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1249 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1250 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1251 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1252 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1253 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1254 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1255 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1256 
1257 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1258 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1259 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1260 			LIF_CMD, ip_siocdelndp_v6, NULL },
1261 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1262 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1263 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1264 			LIF_CMD, ip_siocsetndp_v6, NULL },
1265 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1266 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1267 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1268 			MISC_CMD, ip_sioctl_tonlink, NULL },
1269 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1270 			MISC_CMD, ip_sioctl_tmysite, NULL },
1271 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), 0,
1272 			TUN_CMD, ip_sioctl_tunparam, NULL },
1273 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1274 		    IPI_PRIV | IPI_WR,
1275 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1276 
1277 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1278 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1279 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1280 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1281 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1282 
1283 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1284 
1285 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1286 			LIF_CMD, ip_sioctl_get_binding, NULL },
1287 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1288 			IPI_PRIV | IPI_WR,
1289 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1290 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1291 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1292 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1293 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1294 
1295 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1296 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1297 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1298 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1299 
1300 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1301 
1302 	/* These are handled in ip_sioctl_copyin_setup itself */
1303 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1304 			MISC_CMD, NULL, NULL },
1305 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1306 			MISC_CMD, NULL, NULL },
1307 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1308 
1309 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1310 			ip_sioctl_get_lifconf, NULL },
1311 
1312 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1313 			XARP_CMD, ip_sioctl_arp, NULL },
1314 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1315 			XARP_CMD, ip_sioctl_arp, NULL },
1316 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1317 			XARP_CMD, ip_sioctl_arp, NULL },
1318 
1319 	/* SIOCPOPSOCKFS is not handled by IP */
1320 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1321 
1322 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1323 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1324 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1325 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1326 			ip_sioctl_slifzone_restart },
1327 	/* 172-174 are SCTP ioctls and not handled by IP */
1328 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1329 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1330 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1331 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1332 			IPI_GET_CMD, LIF_CMD,
1333 			ip_sioctl_get_lifusesrc, 0 },
1334 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1335 			IPI_PRIV | IPI_WR,
1336 			LIF_CMD, ip_sioctl_slifusesrc,
1337 			NULL },
1338 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1339 			ip_sioctl_get_lifsrcof, NULL },
1340 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1341 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1342 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1343 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1344 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1345 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1346 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1347 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1348 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1349 	/* SIOCSENABLESDP is handled by SDP */
1350 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1351 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1352 };
1353 
1354 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1355 
1356 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1357 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1358 		IPI_GET_CMD, TUN_CMD, ip_sioctl_tunparam, NULL },
1359 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1360 		TUN_CMD, ip_sioctl_tunparam, NULL },
1361 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1362 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1363 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1364 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1365 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1366 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1367 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1368 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1369 		MISC_CMD, mrt_ioctl},
1370 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1371 		MISC_CMD, mrt_ioctl},
1372 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1373 		MISC_CMD, mrt_ioctl}
1374 };
1375 
1376 int ip_misc_ioctl_count =
1377     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1378 
1379 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1380 					/* Settable in /etc/system */
1381 /* Defined in ip_ire.c */
1382 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1383 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1384 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1385 
1386 static nv_t	ire_nv_arr[] = {
1387 	{ IRE_BROADCAST, "BROADCAST" },
1388 	{ IRE_LOCAL, "LOCAL" },
1389 	{ IRE_LOOPBACK, "LOOPBACK" },
1390 	{ IRE_CACHE, "CACHE" },
1391 	{ IRE_DEFAULT, "DEFAULT" },
1392 	{ IRE_PREFIX, "PREFIX" },
1393 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1394 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1395 	{ IRE_HOST, "HOST" },
1396 	{ 0 }
1397 };
1398 
1399 nv_t	*ire_nv_tbl = ire_nv_arr;
1400 
1401 /* Simple ICMP IP Header Template */
1402 static ipha_t icmp_ipha = {
1403 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1404 };
1405 
1406 struct module_info ip_mod_info = {
1407 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1408 	IP_MOD_LOWAT
1409 };
1410 
1411 /*
1412  * Duplicate static symbols within a module confuses mdb; so we avoid the
1413  * problem by making the symbols here distinct from those in udp.c.
1414  */
1415 
1416 /*
1417  * Entry points for IP as a device and as a module.
1418  * FIXME: down the road we might want a separate module and driver qinit.
1419  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1420  */
1421 static struct qinit iprinitv4 = {
1422 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1423 	&ip_mod_info
1424 };
1425 
1426 struct qinit iprinitv6 = {
1427 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1428 	&ip_mod_info
1429 };
1430 
1431 static struct qinit ipwinitv4 = {
1432 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1433 	&ip_mod_info
1434 };
1435 
1436 struct qinit ipwinitv6 = {
1437 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1438 	&ip_mod_info
1439 };
1440 
1441 static struct qinit iplrinit = {
1442 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1443 	&ip_mod_info
1444 };
1445 
1446 static struct qinit iplwinit = {
1447 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1448 	&ip_mod_info
1449 };
1450 
1451 /* For AF_INET aka /dev/ip */
1452 struct streamtab ipinfov4 = {
1453 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1454 };
1455 
1456 /* For AF_INET6 aka /dev/ip6 */
1457 struct streamtab ipinfov6 = {
1458 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1459 };
1460 
1461 #ifdef	DEBUG
1462 static boolean_t skip_sctp_cksum = B_FALSE;
1463 #endif
1464 
1465 /*
1466  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1467  * ip_rput_v6(), ip_output(), etc.  If the message
1468  * block already has a M_CTL at the front of it, then simply set the zoneid
1469  * appropriately.
1470  */
1471 mblk_t *
1472 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1473 {
1474 	mblk_t		*first_mp;
1475 	ipsec_out_t	*io;
1476 
1477 	ASSERT(zoneid != ALL_ZONES);
1478 	if (mp->b_datap->db_type == M_CTL) {
1479 		io = (ipsec_out_t *)mp->b_rptr;
1480 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1481 		io->ipsec_out_zoneid = zoneid;
1482 		return (mp);
1483 	}
1484 
1485 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1486 	if (first_mp == NULL)
1487 		return (NULL);
1488 	io = (ipsec_out_t *)first_mp->b_rptr;
1489 	/* This is not a secure packet */
1490 	io->ipsec_out_secure = B_FALSE;
1491 	io->ipsec_out_zoneid = zoneid;
1492 	first_mp->b_cont = mp;
1493 	return (first_mp);
1494 }
1495 
1496 /*
1497  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1498  */
1499 mblk_t *
1500 ip_copymsg(mblk_t *mp)
1501 {
1502 	mblk_t *nmp;
1503 	ipsec_info_t *in;
1504 
1505 	if (mp->b_datap->db_type != M_CTL)
1506 		return (copymsg(mp));
1507 
1508 	in = (ipsec_info_t *)mp->b_rptr;
1509 
1510 	/*
1511 	 * Note that M_CTL is also used for delivering ICMP error messages
1512 	 * upstream to transport layers.
1513 	 */
1514 	if (in->ipsec_info_type != IPSEC_OUT &&
1515 	    in->ipsec_info_type != IPSEC_IN)
1516 		return (copymsg(mp));
1517 
1518 	nmp = copymsg(mp->b_cont);
1519 
1520 	if (in->ipsec_info_type == IPSEC_OUT) {
1521 		return (ipsec_out_tag(mp, nmp,
1522 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1523 	} else {
1524 		return (ipsec_in_tag(mp, nmp,
1525 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1526 	}
1527 }
1528 
1529 /* Generate an ICMP fragmentation needed message. */
1530 static void
1531 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1532     ip_stack_t *ipst)
1533 {
1534 	icmph_t	icmph;
1535 	mblk_t *first_mp;
1536 	boolean_t mctl_present;
1537 
1538 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1539 
1540 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1541 		if (mctl_present)
1542 			freeb(first_mp);
1543 		return;
1544 	}
1545 
1546 	bzero(&icmph, sizeof (icmph_t));
1547 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1548 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1549 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1550 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1551 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1552 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1553 	    ipst);
1554 }
1555 
1556 /*
1557  * icmp_inbound deals with ICMP messages in the following ways.
1558  *
1559  * 1) It needs to send a reply back and possibly delivering it
1560  *    to the "interested" upper clients.
1561  * 2) It needs to send it to the upper clients only.
1562  * 3) It needs to change some values in IP only.
1563  * 4) It needs to change some values in IP and upper layers e.g TCP.
1564  *
1565  * We need to accomodate icmp messages coming in clear until we get
1566  * everything secure from the wire. If icmp_accept_clear_messages
1567  * is zero we check with the global policy and act accordingly. If
1568  * it is non-zero, we accept the message without any checks. But
1569  * *this does not mean* that this will be delivered to the upper
1570  * clients. By accepting we might send replies back, change our MTU
1571  * value etc. but delivery to the ULP/clients depends on their policy
1572  * dispositions.
1573  *
1574  * We handle the above 4 cases in the context of IPsec in the
1575  * following way :
1576  *
1577  * 1) Send the reply back in the same way as the request came in.
1578  *    If it came in encrypted, it goes out encrypted. If it came in
1579  *    clear, it goes out in clear. Thus, this will prevent chosen
1580  *    plain text attack.
1581  * 2) The client may or may not expect things to come in secure.
1582  *    If it comes in secure, the policy constraints are checked
1583  *    before delivering it to the upper layers. If it comes in
1584  *    clear, ipsec_inbound_accept_clear will decide whether to
1585  *    accept this in clear or not. In both the cases, if the returned
1586  *    message (IP header + 8 bytes) that caused the icmp message has
1587  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1588  *    sending up. If there are only 8 bytes of returned message, then
1589  *    upper client will not be notified.
1590  * 3) Check with global policy to see whether it matches the constaints.
1591  *    But this will be done only if icmp_accept_messages_in_clear is
1592  *    zero.
1593  * 4) If we need to change both in IP and ULP, then the decision taken
1594  *    while affecting the values in IP and while delivering up to TCP
1595  *    should be the same.
1596  *
1597  * 	There are two cases.
1598  *
1599  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1600  *	   failed), we will not deliver it to the ULP, even though they
1601  *	   are *willing* to accept in *clear*. This is fine as our global
1602  *	   disposition to icmp messages asks us reject the datagram.
1603  *
1604  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1605  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1606  *	   to deliver it to ULP (policy failed), it can lead to
1607  *	   consistency problems. The cases known at this time are
1608  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1609  *	   values :
1610  *
1611  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1612  *	     and Upper layer rejects. Then the communication will
1613  *	     come to a stop. This is solved by making similar decisions
1614  *	     at both levels. Currently, when we are unable to deliver
1615  *	     to the Upper Layer (due to policy failures) while IP has
1616  *	     adjusted ire_max_frag, the next outbound datagram would
1617  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1618  *	     will be with the right level of protection. Thus the right
1619  *	     value will be communicated even if we are not able to
1620  *	     communicate when we get from the wire initially. But this
1621  *	     assumes there would be at least one outbound datagram after
1622  *	     IP has adjusted its ire_max_frag value. To make things
1623  *	     simpler, we accept in clear after the validation of
1624  *	     AH/ESP headers.
1625  *
1626  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1627  *	     upper layer depending on the level of protection the upper
1628  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1629  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1630  *	     should be accepted in clear when the Upper layer expects secure.
1631  *	     Thus the communication may get aborted by some bad ICMP
1632  *	     packets.
1633  *
1634  * IPQoS Notes:
1635  * The only instance when a packet is sent for processing is when there
1636  * isn't an ICMP client and if we are interested in it.
1637  * If there is a client, IPPF processing will take place in the
1638  * ip_fanout_proto routine.
1639  *
1640  * Zones notes:
1641  * The packet is only processed in the context of the specified zone: typically
1642  * only this zone will reply to an echo request, and only interested clients in
1643  * this zone will receive a copy of the packet. This means that the caller must
1644  * call icmp_inbound() for each relevant zone.
1645  */
1646 static void
1647 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1648     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1649     ill_t *recv_ill, zoneid_t zoneid)
1650 {
1651 	icmph_t	*icmph;
1652 	ipha_t	*ipha;
1653 	int	iph_hdr_length;
1654 	int	hdr_length;
1655 	boolean_t	interested;
1656 	uint32_t	ts;
1657 	uchar_t	*wptr;
1658 	ipif_t	*ipif;
1659 	mblk_t *first_mp;
1660 	ipsec_in_t *ii;
1661 	timestruc_t now;
1662 	uint32_t ill_index;
1663 	ip_stack_t *ipst;
1664 
1665 	ASSERT(ill != NULL);
1666 	ipst = ill->ill_ipst;
1667 
1668 	first_mp = mp;
1669 	if (mctl_present) {
1670 		mp = first_mp->b_cont;
1671 		ASSERT(mp != NULL);
1672 	}
1673 
1674 	ipha = (ipha_t *)mp->b_rptr;
1675 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1676 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1677 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1678 		if (first_mp == NULL)
1679 			return;
1680 	}
1681 
1682 	/*
1683 	 * On a labeled system, we have to check whether the zone itself is
1684 	 * permitted to receive raw traffic.
1685 	 */
1686 	if (is_system_labeled()) {
1687 		if (zoneid == ALL_ZONES)
1688 			zoneid = tsol_packet_to_zoneid(mp);
1689 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1690 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1691 			    zoneid));
1692 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1693 			freemsg(first_mp);
1694 			return;
1695 		}
1696 	}
1697 
1698 	/*
1699 	 * We have accepted the ICMP message. It means that we will
1700 	 * respond to the packet if needed. It may not be delivered
1701 	 * to the upper client depending on the policy constraints
1702 	 * and the disposition in ipsec_inbound_accept_clear.
1703 	 */
1704 
1705 	ASSERT(ill != NULL);
1706 
1707 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1708 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1709 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1710 		/* Last chance to get real. */
1711 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1712 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1713 			freemsg(first_mp);
1714 			return;
1715 		}
1716 		/* Refresh iph following the pullup. */
1717 		ipha = (ipha_t *)mp->b_rptr;
1718 	}
1719 	/* ICMP header checksum, including checksum field, should be zero. */
1720 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1721 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1722 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1723 		freemsg(first_mp);
1724 		return;
1725 	}
1726 	/* The IP header will always be a multiple of four bytes */
1727 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1728 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1729 	    icmph->icmph_code));
1730 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1731 	/* We will set "interested" to "true" if we want a copy */
1732 	interested = B_FALSE;
1733 	switch (icmph->icmph_type) {
1734 	case ICMP_ECHO_REPLY:
1735 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1736 		break;
1737 	case ICMP_DEST_UNREACHABLE:
1738 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1739 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1740 		interested = B_TRUE;	/* Pass up to transport */
1741 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1742 		break;
1743 	case ICMP_SOURCE_QUENCH:
1744 		interested = B_TRUE;	/* Pass up to transport */
1745 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1746 		break;
1747 	case ICMP_REDIRECT:
1748 		if (!ipst->ips_ip_ignore_redirect)
1749 			interested = B_TRUE;
1750 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1751 		break;
1752 	case ICMP_ECHO_REQUEST:
1753 		/*
1754 		 * Whether to respond to echo requests that come in as IP
1755 		 * broadcasts or as IP multicast is subject to debate
1756 		 * (what isn't?).  We aim to please, you pick it.
1757 		 * Default is do it.
1758 		 */
1759 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1760 			/* unicast: always respond */
1761 			interested = B_TRUE;
1762 		} else if (CLASSD(ipha->ipha_dst)) {
1763 			/* multicast: respond based on tunable */
1764 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1765 		} else if (broadcast) {
1766 			/* broadcast: respond based on tunable */
1767 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1768 		}
1769 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1770 		break;
1771 	case ICMP_ROUTER_ADVERTISEMENT:
1772 	case ICMP_ROUTER_SOLICITATION:
1773 		break;
1774 	case ICMP_TIME_EXCEEDED:
1775 		interested = B_TRUE;	/* Pass up to transport */
1776 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1777 		break;
1778 	case ICMP_PARAM_PROBLEM:
1779 		interested = B_TRUE;	/* Pass up to transport */
1780 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1781 		break;
1782 	case ICMP_TIME_STAMP_REQUEST:
1783 		/* Response to Time Stamp Requests is local policy. */
1784 		if (ipst->ips_ip_g_resp_to_timestamp &&
1785 		    /* So is whether to respond if it was an IP broadcast. */
1786 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1787 			int tstamp_len = 3 * sizeof (uint32_t);
1788 
1789 			if (wptr +  tstamp_len > mp->b_wptr) {
1790 				if (!pullupmsg(mp, wptr + tstamp_len -
1791 				    mp->b_rptr)) {
1792 					BUMP_MIB(ill->ill_ip_mib,
1793 					    ipIfStatsInDiscards);
1794 					freemsg(first_mp);
1795 					return;
1796 				}
1797 				/* Refresh ipha following the pullup. */
1798 				ipha = (ipha_t *)mp->b_rptr;
1799 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1800 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1801 			}
1802 			interested = B_TRUE;
1803 		}
1804 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1805 		break;
1806 	case ICMP_TIME_STAMP_REPLY:
1807 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1808 		break;
1809 	case ICMP_INFO_REQUEST:
1810 		/* Per RFC 1122 3.2.2.7, ignore this. */
1811 	case ICMP_INFO_REPLY:
1812 		break;
1813 	case ICMP_ADDRESS_MASK_REQUEST:
1814 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1815 		    !broadcast) &&
1816 		    /* TODO m_pullup of complete header? */
1817 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1818 			interested = B_TRUE;
1819 		}
1820 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1821 		break;
1822 	case ICMP_ADDRESS_MASK_REPLY:
1823 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1824 		break;
1825 	default:
1826 		interested = B_TRUE;	/* Pass up to transport */
1827 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1828 		break;
1829 	}
1830 	/* See if there is an ICMP client. */
1831 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1832 		/* If there is an ICMP client and we want one too, copy it. */
1833 		mblk_t *first_mp1;
1834 
1835 		if (!interested) {
1836 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1837 			    ip_policy, recv_ill, zoneid);
1838 			return;
1839 		}
1840 		first_mp1 = ip_copymsg(first_mp);
1841 		if (first_mp1 != NULL) {
1842 			ip_fanout_proto(q, first_mp1, ill, ipha,
1843 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1844 		}
1845 	} else if (!interested) {
1846 		freemsg(first_mp);
1847 		return;
1848 	} else {
1849 		/*
1850 		 * Initiate policy processing for this packet if ip_policy
1851 		 * is true.
1852 		 */
1853 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1854 			ill_index = ill->ill_phyint->phyint_ifindex;
1855 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1856 			if (mp == NULL) {
1857 				if (mctl_present) {
1858 					freeb(first_mp);
1859 				}
1860 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1861 				return;
1862 			}
1863 		}
1864 	}
1865 	/* We want to do something with it. */
1866 	/* Check db_ref to make sure we can modify the packet. */
1867 	if (mp->b_datap->db_ref > 1) {
1868 		mblk_t	*first_mp1;
1869 
1870 		first_mp1 = ip_copymsg(first_mp);
1871 		freemsg(first_mp);
1872 		if (!first_mp1) {
1873 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1874 			return;
1875 		}
1876 		first_mp = first_mp1;
1877 		if (mctl_present) {
1878 			mp = first_mp->b_cont;
1879 			ASSERT(mp != NULL);
1880 		} else {
1881 			mp = first_mp;
1882 		}
1883 		ipha = (ipha_t *)mp->b_rptr;
1884 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1885 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1886 	}
1887 	switch (icmph->icmph_type) {
1888 	case ICMP_ADDRESS_MASK_REQUEST:
1889 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1890 		if (ipif == NULL) {
1891 			freemsg(first_mp);
1892 			return;
1893 		}
1894 		/*
1895 		 * outging interface must be IPv4
1896 		 */
1897 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1898 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1899 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1900 		ipif_refrele(ipif);
1901 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1902 		break;
1903 	case ICMP_ECHO_REQUEST:
1904 		icmph->icmph_type = ICMP_ECHO_REPLY;
1905 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1906 		break;
1907 	case ICMP_TIME_STAMP_REQUEST: {
1908 		uint32_t *tsp;
1909 
1910 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1911 		tsp = (uint32_t *)wptr;
1912 		tsp++;		/* Skip past 'originate time' */
1913 		/* Compute # of milliseconds since midnight */
1914 		gethrestime(&now);
1915 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1916 		    now.tv_nsec / (NANOSEC / MILLISEC);
1917 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1918 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1919 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1920 		break;
1921 	}
1922 	default:
1923 		ipha = (ipha_t *)&icmph[1];
1924 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1925 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1926 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1927 				freemsg(first_mp);
1928 				return;
1929 			}
1930 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1931 			ipha = (ipha_t *)&icmph[1];
1932 		}
1933 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1934 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1935 			freemsg(first_mp);
1936 			return;
1937 		}
1938 		hdr_length = IPH_HDR_LENGTH(ipha);
1939 		if (hdr_length < sizeof (ipha_t)) {
1940 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1941 			freemsg(first_mp);
1942 			return;
1943 		}
1944 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1945 			if (!pullupmsg(mp,
1946 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1947 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1948 				freemsg(first_mp);
1949 				return;
1950 			}
1951 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1952 			ipha = (ipha_t *)&icmph[1];
1953 		}
1954 		switch (icmph->icmph_type) {
1955 		case ICMP_REDIRECT:
1956 			/*
1957 			 * As there is no upper client to deliver, we don't
1958 			 * need the first_mp any more.
1959 			 */
1960 			if (mctl_present) {
1961 				freeb(first_mp);
1962 			}
1963 			icmp_redirect(ill, mp);
1964 			return;
1965 		case ICMP_DEST_UNREACHABLE:
1966 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1967 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1968 				    zoneid, mp, iph_hdr_length, ipst)) {
1969 					freemsg(first_mp);
1970 					return;
1971 				}
1972 				/*
1973 				 * icmp_inbound_too_big() may alter mp.
1974 				 * Resynch ipha and icmph accordingly.
1975 				 */
1976 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1977 				ipha = (ipha_t *)&icmph[1];
1978 			}
1979 			/* FALLTHRU */
1980 		default :
1981 			/*
1982 			 * IPQoS notes: Since we have already done IPQoS
1983 			 * processing we don't want to do it again in
1984 			 * the fanout routines called by
1985 			 * icmp_inbound_error_fanout, hence the last
1986 			 * argument, ip_policy, is B_FALSE.
1987 			 */
1988 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1989 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1990 			    B_FALSE, recv_ill, zoneid);
1991 		}
1992 		return;
1993 	}
1994 	/* Send out an ICMP packet */
1995 	icmph->icmph_checksum = 0;
1996 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1997 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1998 		ipif_t	*ipif_chosen;
1999 		/*
2000 		 * Make it look like it was directed to us, so we don't look
2001 		 * like a fool with a broadcast or multicast source address.
2002 		 */
2003 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
2004 		/*
2005 		 * Make sure that we haven't grabbed an interface that's DOWN.
2006 		 */
2007 		if (ipif != NULL) {
2008 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
2009 			    ipha->ipha_src, zoneid);
2010 			if (ipif_chosen != NULL) {
2011 				ipif_refrele(ipif);
2012 				ipif = ipif_chosen;
2013 			}
2014 		}
2015 		if (ipif == NULL) {
2016 			ip0dbg(("icmp_inbound: "
2017 			    "No source for broadcast/multicast:\n"
2018 			    "\tsrc 0x%x dst 0x%x ill %p "
2019 			    "ipif_lcl_addr 0x%x\n",
2020 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
2021 			    (void *)ill,
2022 			    ill->ill_ipif->ipif_lcl_addr));
2023 			freemsg(first_mp);
2024 			return;
2025 		}
2026 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
2027 		ipha->ipha_dst = ipif->ipif_src_addr;
2028 		ipif_refrele(ipif);
2029 	}
2030 	/* Reset time to live. */
2031 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2032 	{
2033 		/* Swap source and destination addresses */
2034 		ipaddr_t tmp;
2035 
2036 		tmp = ipha->ipha_src;
2037 		ipha->ipha_src = ipha->ipha_dst;
2038 		ipha->ipha_dst = tmp;
2039 	}
2040 	ipha->ipha_ident = 0;
2041 	if (!IS_SIMPLE_IPH(ipha))
2042 		icmp_options_update(ipha);
2043 
2044 	if (!mctl_present) {
2045 		/*
2046 		 * This packet should go out the same way as it
2047 		 * came in i.e in clear. To make sure that global
2048 		 * policy will not be applied to this in ip_wput_ire,
2049 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2050 		 */
2051 		ASSERT(first_mp == mp);
2052 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2053 		if (first_mp == NULL) {
2054 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2055 			freemsg(mp);
2056 			return;
2057 		}
2058 		ii = (ipsec_in_t *)first_mp->b_rptr;
2059 
2060 		/* This is not a secure packet */
2061 		ii->ipsec_in_secure = B_FALSE;
2062 		first_mp->b_cont = mp;
2063 	} else {
2064 		ii = (ipsec_in_t *)first_mp->b_rptr;
2065 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2066 	}
2067 	ii->ipsec_in_zoneid = zoneid;
2068 	ASSERT(zoneid != ALL_ZONES);
2069 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2070 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2071 		return;
2072 	}
2073 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2074 	put(WR(q), first_mp);
2075 }
2076 
2077 static ipaddr_t
2078 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2079 {
2080 	conn_t *connp;
2081 	connf_t *connfp;
2082 	ipaddr_t nexthop_addr = INADDR_ANY;
2083 	int hdr_length = IPH_HDR_LENGTH(ipha);
2084 	uint16_t *up;
2085 	uint32_t ports;
2086 	ip_stack_t *ipst = ill->ill_ipst;
2087 
2088 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2089 	switch (ipha->ipha_protocol) {
2090 		case IPPROTO_TCP:
2091 		{
2092 			tcph_t *tcph;
2093 
2094 			/* do a reverse lookup */
2095 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2096 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2097 			    TCPS_LISTEN, ipst);
2098 			break;
2099 		}
2100 		case IPPROTO_UDP:
2101 		{
2102 			uint32_t dstport, srcport;
2103 
2104 			((uint16_t *)&ports)[0] = up[1];
2105 			((uint16_t *)&ports)[1] = up[0];
2106 
2107 			/* Extract ports in net byte order */
2108 			dstport = htons(ntohl(ports) & 0xFFFF);
2109 			srcport = htons(ntohl(ports) >> 16);
2110 
2111 			connfp = &ipst->ips_ipcl_udp_fanout[
2112 			    IPCL_UDP_HASH(dstport, ipst)];
2113 			mutex_enter(&connfp->connf_lock);
2114 			connp = connfp->connf_head;
2115 
2116 			/* do a reverse lookup */
2117 			while ((connp != NULL) &&
2118 			    (!IPCL_UDP_MATCH(connp, dstport,
2119 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2120 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2121 				connp = connp->conn_next;
2122 			}
2123 			if (connp != NULL)
2124 				CONN_INC_REF(connp);
2125 			mutex_exit(&connfp->connf_lock);
2126 			break;
2127 		}
2128 		case IPPROTO_SCTP:
2129 		{
2130 			in6_addr_t map_src, map_dst;
2131 
2132 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2133 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2134 			((uint16_t *)&ports)[0] = up[1];
2135 			((uint16_t *)&ports)[1] = up[0];
2136 
2137 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2138 			    zoneid, ipst->ips_netstack->netstack_sctp);
2139 			if (connp == NULL) {
2140 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2141 				    zoneid, ports, ipha, ipst);
2142 			} else {
2143 				CONN_INC_REF(connp);
2144 				SCTP_REFRELE(CONN2SCTP(connp));
2145 			}
2146 			break;
2147 		}
2148 		default:
2149 		{
2150 			ipha_t ripha;
2151 
2152 			ripha.ipha_src = ipha->ipha_dst;
2153 			ripha.ipha_dst = ipha->ipha_src;
2154 			ripha.ipha_protocol = ipha->ipha_protocol;
2155 
2156 			connfp = &ipst->ips_ipcl_proto_fanout[
2157 			    ipha->ipha_protocol];
2158 			mutex_enter(&connfp->connf_lock);
2159 			connp = connfp->connf_head;
2160 			for (connp = connfp->connf_head; connp != NULL;
2161 			    connp = connp->conn_next) {
2162 				if (IPCL_PROTO_MATCH(connp,
2163 				    ipha->ipha_protocol, &ripha, ill,
2164 				    0, zoneid)) {
2165 					CONN_INC_REF(connp);
2166 					break;
2167 				}
2168 			}
2169 			mutex_exit(&connfp->connf_lock);
2170 		}
2171 	}
2172 	if (connp != NULL) {
2173 		if (connp->conn_nexthop_set)
2174 			nexthop_addr = connp->conn_nexthop_v4;
2175 		CONN_DEC_REF(connp);
2176 	}
2177 	return (nexthop_addr);
2178 }
2179 
2180 /* Table from RFC 1191 */
2181 static int icmp_frag_size_table[] =
2182 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2183 
2184 /*
2185  * Process received ICMP Packet too big.
2186  * After updating any IRE it does the fanout to any matching transport streams.
2187  * Assumes the message has been pulled up till the IP header that caused
2188  * the error.
2189  *
2190  * Returns B_FALSE on failure and B_TRUE on success.
2191  */
2192 static boolean_t
2193 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2194     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2195     ip_stack_t *ipst)
2196 {
2197 	ire_t	*ire, *first_ire;
2198 	int	mtu, orig_mtu;
2199 	int	hdr_length;
2200 	ipaddr_t nexthop_addr;
2201 	boolean_t disable_pmtud;
2202 
2203 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2204 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2205 	ASSERT(ill != NULL);
2206 
2207 	hdr_length = IPH_HDR_LENGTH(ipha);
2208 
2209 	/* Drop if the original packet contained a source route */
2210 	if (ip_source_route_included(ipha)) {
2211 		return (B_FALSE);
2212 	}
2213 	/*
2214 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2215 	 * header.
2216 	 */
2217 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2218 	    mp->b_wptr) {
2219 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2220 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2221 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2222 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2223 			return (B_FALSE);
2224 		}
2225 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2226 		ipha = (ipha_t *)&icmph[1];
2227 	}
2228 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2229 	if (nexthop_addr != INADDR_ANY) {
2230 		/* nexthop set */
2231 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2232 		    nexthop_addr, 0, NULL, ALL_ZONES, msg_getlabel(mp),
2233 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2234 	} else {
2235 		/* nexthop not set */
2236 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2237 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2238 	}
2239 
2240 	if (!first_ire) {
2241 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2242 		    ntohl(ipha->ipha_dst)));
2243 		return (B_FALSE);
2244 	}
2245 
2246 	/* Check for MTU discovery advice as described in RFC 1191 */
2247 	mtu = ntohs(icmph->icmph_du_mtu);
2248 	orig_mtu = mtu;
2249 	disable_pmtud = B_FALSE;
2250 
2251 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2252 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2253 	    ire = ire->ire_next) {
2254 		/*
2255 		 * Look for the connection to which this ICMP message is
2256 		 * directed. If it has the IP_NEXTHOP option set, then the
2257 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2258 		 * option. Else the search is limited to regular IREs.
2259 		 */
2260 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2261 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2262 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2263 		    (nexthop_addr != INADDR_ANY)))
2264 			continue;
2265 
2266 		mutex_enter(&ire->ire_lock);
2267 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2268 			uint32_t length;
2269 			int	i;
2270 
2271 			/*
2272 			 * Use the table from RFC 1191 to figure out
2273 			 * the next "plateau" based on the length in
2274 			 * the original IP packet.
2275 			 */
2276 			length = ntohs(ipha->ipha_length);
2277 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2278 			    uint32_t, length);
2279 			if (ire->ire_max_frag <= length &&
2280 			    ire->ire_max_frag >= length - hdr_length) {
2281 				/*
2282 				 * Handle broken BSD 4.2 systems that
2283 				 * return the wrong iph_length in ICMP
2284 				 * errors.
2285 				 */
2286 				length -= hdr_length;
2287 			}
2288 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2289 				if (length > icmp_frag_size_table[i])
2290 					break;
2291 			}
2292 			if (i == A_CNT(icmp_frag_size_table)) {
2293 				/* Smaller than 68! */
2294 				disable_pmtud = B_TRUE;
2295 				mtu = ipst->ips_ip_pmtu_min;
2296 			} else {
2297 				mtu = icmp_frag_size_table[i];
2298 				if (mtu < ipst->ips_ip_pmtu_min) {
2299 					mtu = ipst->ips_ip_pmtu_min;
2300 					disable_pmtud = B_TRUE;
2301 				}
2302 			}
2303 			/* Fool the ULP into believing our guessed PMTU. */
2304 			icmph->icmph_du_zero = 0;
2305 			icmph->icmph_du_mtu = htons(mtu);
2306 		}
2307 		if (disable_pmtud)
2308 			ire->ire_frag_flag = 0;
2309 		/* Reduce the IRE max frag value as advised. */
2310 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2311 		if (ire->ire_max_frag == mtu) {
2312 			/* Decreased it */
2313 			ire->ire_marks |= IRE_MARK_PMTU;
2314 		}
2315 		mutex_exit(&ire->ire_lock);
2316 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2317 		    ire, int, orig_mtu, int, mtu);
2318 	}
2319 	rw_exit(&first_ire->ire_bucket->irb_lock);
2320 	ire_refrele(first_ire);
2321 	return (B_TRUE);
2322 }
2323 
2324 /*
2325  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2326  * calls this function.
2327  */
2328 static mblk_t *
2329 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2330 {
2331 	ipha_t *ipha;
2332 	icmph_t *icmph;
2333 	ipha_t *in_ipha;
2334 	int length;
2335 
2336 	ASSERT(mp->b_datap->db_type == M_DATA);
2337 
2338 	/*
2339 	 * For Self-encapsulated packets, we added an extra IP header
2340 	 * without the options. Inner IP header is the one from which
2341 	 * the outer IP header was formed. Thus, we need to remove the
2342 	 * outer IP header. To do this, we pullup the whole message
2343 	 * and overlay whatever follows the outer IP header over the
2344 	 * outer IP header.
2345 	 */
2346 
2347 	if (!pullupmsg(mp, -1))
2348 		return (NULL);
2349 
2350 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2351 	ipha = (ipha_t *)&icmph[1];
2352 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2353 
2354 	/*
2355 	 * The length that we want to overlay is following the inner
2356 	 * IP header. Subtracting the IP header + icmp header + outer
2357 	 * IP header's length should give us the length that we want to
2358 	 * overlay.
2359 	 */
2360 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2361 	    hdr_length;
2362 	/*
2363 	 * Overlay whatever follows the inner header over the
2364 	 * outer header.
2365 	 */
2366 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2367 
2368 	/* Set the wptr to account for the outer header */
2369 	mp->b_wptr -= hdr_length;
2370 	return (mp);
2371 }
2372 
2373 /*
2374  * Try to pass the ICMP message upstream in case the ULP cares.
2375  *
2376  * If the packet that caused the ICMP error is secure, we send
2377  * it to AH/ESP to make sure that the attached packet has a
2378  * valid association. ipha in the code below points to the
2379  * IP header of the packet that caused the error.
2380  *
2381  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2382  * in the context of IPsec. Normally we tell the upper layer
2383  * whenever we send the ire (including ip_bind), the IPsec header
2384  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2385  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2386  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2387  * same thing. As TCP has the IPsec options size that needs to be
2388  * adjusted, we just pass the MTU unchanged.
2389  *
2390  * IFN could have been generated locally or by some router.
2391  *
2392  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2393  *	    This happens because IP adjusted its value of MTU on an
2394  *	    earlier IFN message and could not tell the upper layer,
2395  *	    the new adjusted value of MTU e.g. Packet was encrypted
2396  *	    or there was not enough information to fanout to upper
2397  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2398  *	    generates the IFN, where IPsec processing has *not* been
2399  *	    done.
2400  *
2401  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2402  *	    could have generated this. This happens because ire_max_frag
2403  *	    value in IP was set to a new value, while the IPsec processing
2404  *	    was being done and after we made the fragmentation check in
2405  *	    ip_wput_ire. Thus on return from IPsec processing,
2406  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2407  *	    and generates the IFN. As IPsec processing is over, we fanout
2408  *	    to AH/ESP to remove the header.
2409  *
2410  *	    In both these cases, ipsec_in_loopback will be set indicating
2411  *	    that IFN was generated locally.
2412  *
2413  * ROUTER : IFN could be secure or non-secure.
2414  *
2415  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2416  *	      packet in error has AH/ESP headers to validate the AH/ESP
2417  *	      headers. AH/ESP will verify whether there is a valid SA or
2418  *	      not and send it back. We will fanout again if we have more
2419  *	      data in the packet.
2420  *
2421  *	      If the packet in error does not have AH/ESP, we handle it
2422  *	      like any other case.
2423  *
2424  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2425  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2426  *	      for validation. AH/ESP will verify whether there is a
2427  *	      valid SA or not and send it back. We will fanout again if
2428  *	      we have more data in the packet.
2429  *
2430  *	      If the packet in error does not have AH/ESP, we handle it
2431  *	      like any other case.
2432  */
2433 static void
2434 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2435     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2436     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2437     zoneid_t zoneid)
2438 {
2439 	uint16_t *up;	/* Pointer to ports in ULP header */
2440 	uint32_t ports;	/* reversed ports for fanout */
2441 	ipha_t ripha;	/* With reversed addresses */
2442 	mblk_t *first_mp;
2443 	ipsec_in_t *ii;
2444 	tcph_t	*tcph;
2445 	conn_t	*connp;
2446 	ip_stack_t *ipst;
2447 
2448 	ASSERT(ill != NULL);
2449 
2450 	ASSERT(recv_ill != NULL);
2451 	ipst = recv_ill->ill_ipst;
2452 
2453 	first_mp = mp;
2454 	if (mctl_present) {
2455 		mp = first_mp->b_cont;
2456 		ASSERT(mp != NULL);
2457 
2458 		ii = (ipsec_in_t *)first_mp->b_rptr;
2459 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2460 	} else {
2461 		ii = NULL;
2462 	}
2463 
2464 	switch (ipha->ipha_protocol) {
2465 	case IPPROTO_UDP:
2466 		/*
2467 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2468 		 * transport header.
2469 		 */
2470 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2471 		    mp->b_wptr) {
2472 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2473 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2474 				goto discard_pkt;
2475 			}
2476 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2477 			ipha = (ipha_t *)&icmph[1];
2478 		}
2479 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2480 
2481 		/*
2482 		 * Attempt to find a client stream based on port.
2483 		 * Note that we do a reverse lookup since the header is
2484 		 * in the form we sent it out.
2485 		 * The ripha header is only used for the IP_UDP_MATCH and we
2486 		 * only set the src and dst addresses and protocol.
2487 		 */
2488 		ripha.ipha_src = ipha->ipha_dst;
2489 		ripha.ipha_dst = ipha->ipha_src;
2490 		ripha.ipha_protocol = ipha->ipha_protocol;
2491 		((uint16_t *)&ports)[0] = up[1];
2492 		((uint16_t *)&ports)[1] = up[0];
2493 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2494 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2495 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2496 		    icmph->icmph_type, icmph->icmph_code));
2497 
2498 		/* Have to change db_type after any pullupmsg */
2499 		DB_TYPE(mp) = M_CTL;
2500 
2501 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2502 		    mctl_present, ip_policy, recv_ill, zoneid);
2503 		return;
2504 
2505 	case IPPROTO_TCP:
2506 		/*
2507 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2508 		 * transport header.
2509 		 */
2510 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2511 		    mp->b_wptr) {
2512 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2513 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2514 				goto discard_pkt;
2515 			}
2516 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2517 			ipha = (ipha_t *)&icmph[1];
2518 		}
2519 		/*
2520 		 * Find a TCP client stream for this packet.
2521 		 * Note that we do a reverse lookup since the header is
2522 		 * in the form we sent it out.
2523 		 */
2524 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2525 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2526 		    ipst);
2527 		if (connp == NULL)
2528 			goto discard_pkt;
2529 
2530 		/* Have to change db_type after any pullupmsg */
2531 		DB_TYPE(mp) = M_CTL;
2532 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2533 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2534 		return;
2535 
2536 	case IPPROTO_SCTP:
2537 		/*
2538 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2539 		 * transport header.
2540 		 */
2541 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2542 		    mp->b_wptr) {
2543 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2544 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2545 				goto discard_pkt;
2546 			}
2547 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2548 			ipha = (ipha_t *)&icmph[1];
2549 		}
2550 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2551 		/*
2552 		 * Find a SCTP client stream for this packet.
2553 		 * Note that we do a reverse lookup since the header is
2554 		 * in the form we sent it out.
2555 		 * The ripha header is only used for the matching and we
2556 		 * only set the src and dst addresses, protocol, and version.
2557 		 */
2558 		ripha.ipha_src = ipha->ipha_dst;
2559 		ripha.ipha_dst = ipha->ipha_src;
2560 		ripha.ipha_protocol = ipha->ipha_protocol;
2561 		ripha.ipha_version_and_hdr_length =
2562 		    ipha->ipha_version_and_hdr_length;
2563 		((uint16_t *)&ports)[0] = up[1];
2564 		((uint16_t *)&ports)[1] = up[0];
2565 
2566 		/* Have to change db_type after any pullupmsg */
2567 		DB_TYPE(mp) = M_CTL;
2568 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2569 		    mctl_present, ip_policy, zoneid);
2570 		return;
2571 
2572 	case IPPROTO_ESP:
2573 	case IPPROTO_AH: {
2574 		int ipsec_rc;
2575 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2576 
2577 		/*
2578 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2579 		 * We will re-use the IPSEC_IN if it is already present as
2580 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2581 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2582 		 * one and attach it in the front.
2583 		 */
2584 		if (ii != NULL) {
2585 			/*
2586 			 * ip_fanout_proto_again converts the ICMP errors
2587 			 * that come back from AH/ESP to M_DATA so that
2588 			 * if it is non-AH/ESP and we do a pullupmsg in
2589 			 * this function, it would work. Convert it back
2590 			 * to M_CTL before we send up as this is a ICMP
2591 			 * error. This could have been generated locally or
2592 			 * by some router. Validate the inner IPsec
2593 			 * headers.
2594 			 *
2595 			 * NOTE : ill_index is used by ip_fanout_proto_again
2596 			 * to locate the ill.
2597 			 */
2598 			ASSERT(ill != NULL);
2599 			ii->ipsec_in_ill_index =
2600 			    ill->ill_phyint->phyint_ifindex;
2601 			ii->ipsec_in_rill_index =
2602 			    recv_ill->ill_phyint->phyint_ifindex;
2603 			DB_TYPE(first_mp->b_cont) = M_CTL;
2604 		} else {
2605 			/*
2606 			 * IPSEC_IN is not present. We attach a ipsec_in
2607 			 * message and send up to IPsec for validating
2608 			 * and removing the IPsec headers. Clear
2609 			 * ipsec_in_secure so that when we return
2610 			 * from IPsec, we don't mistakenly think that this
2611 			 * is a secure packet came from the network.
2612 			 *
2613 			 * NOTE : ill_index is used by ip_fanout_proto_again
2614 			 * to locate the ill.
2615 			 */
2616 			ASSERT(first_mp == mp);
2617 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2618 			if (first_mp == NULL) {
2619 				freemsg(mp);
2620 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2621 				return;
2622 			}
2623 			ii = (ipsec_in_t *)first_mp->b_rptr;
2624 
2625 			/* This is not a secure packet */
2626 			ii->ipsec_in_secure = B_FALSE;
2627 			first_mp->b_cont = mp;
2628 			DB_TYPE(mp) = M_CTL;
2629 			ASSERT(ill != NULL);
2630 			ii->ipsec_in_ill_index =
2631 			    ill->ill_phyint->phyint_ifindex;
2632 			ii->ipsec_in_rill_index =
2633 			    recv_ill->ill_phyint->phyint_ifindex;
2634 		}
2635 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2636 
2637 		if (!ipsec_loaded(ipss)) {
2638 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2639 			return;
2640 		}
2641 
2642 		if (ipha->ipha_protocol == IPPROTO_ESP)
2643 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2644 		else
2645 			ipsec_rc = ipsecah_icmp_error(first_mp);
2646 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2647 			return;
2648 
2649 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2650 		return;
2651 	}
2652 	default:
2653 		/*
2654 		 * The ripha header is only used for the lookup and we
2655 		 * only set the src and dst addresses and protocol.
2656 		 */
2657 		ripha.ipha_src = ipha->ipha_dst;
2658 		ripha.ipha_dst = ipha->ipha_src;
2659 		ripha.ipha_protocol = ipha->ipha_protocol;
2660 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2661 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2662 		    ntohl(ipha->ipha_dst),
2663 		    icmph->icmph_type, icmph->icmph_code));
2664 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2665 			ipha_t *in_ipha;
2666 
2667 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2668 			    mp->b_wptr) {
2669 				if (!pullupmsg(mp, (uchar_t *)ipha +
2670 				    hdr_length + sizeof (ipha_t) -
2671 				    mp->b_rptr)) {
2672 					goto discard_pkt;
2673 				}
2674 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2675 				ipha = (ipha_t *)&icmph[1];
2676 			}
2677 			/*
2678 			 * Caller has verified that length has to be
2679 			 * at least the size of IP header.
2680 			 */
2681 			ASSERT(hdr_length >= sizeof (ipha_t));
2682 			/*
2683 			 * Check the sanity of the inner IP header like
2684 			 * we did for the outer header.
2685 			 */
2686 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2687 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2688 				goto discard_pkt;
2689 			}
2690 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2691 				goto discard_pkt;
2692 			}
2693 			/* Check for Self-encapsulated tunnels */
2694 			if (in_ipha->ipha_src == ipha->ipha_src &&
2695 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2696 
2697 				mp = icmp_inbound_self_encap_error(mp,
2698 				    iph_hdr_length, hdr_length);
2699 				if (mp == NULL)
2700 					goto discard_pkt;
2701 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2702 				ipha = (ipha_t *)&icmph[1];
2703 				hdr_length = IPH_HDR_LENGTH(ipha);
2704 				/*
2705 				 * The packet in error is self-encapsualted.
2706 				 * And we are finding it further encapsulated
2707 				 * which we could not have possibly generated.
2708 				 */
2709 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2710 					goto discard_pkt;
2711 				}
2712 				icmp_inbound_error_fanout(q, ill, first_mp,
2713 				    icmph, ipha, iph_hdr_length, hdr_length,
2714 				    mctl_present, ip_policy, recv_ill, zoneid);
2715 				return;
2716 			}
2717 		}
2718 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2719 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2720 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2721 		    ii != NULL &&
2722 		    ii->ipsec_in_loopback &&
2723 		    ii->ipsec_in_secure) {
2724 			/*
2725 			 * For IP tunnels that get a looped-back
2726 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2727 			 * reported new MTU to take into account the IPsec
2728 			 * headers protecting this configured tunnel.
2729 			 *
2730 			 * This allows the tunnel module (tun.c) to blindly
2731 			 * accept the MTU reported in an ICMP "too big"
2732 			 * message.
2733 			 *
2734 			 * Non-looped back ICMP messages will just be
2735 			 * handled by the security protocols (if needed),
2736 			 * and the first subsequent packet will hit this
2737 			 * path.
2738 			 */
2739 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2740 			    ipsec_in_extra_length(first_mp));
2741 		}
2742 		/* Have to change db_type after any pullupmsg */
2743 		DB_TYPE(mp) = M_CTL;
2744 
2745 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2746 		    ip_policy, recv_ill, zoneid);
2747 		return;
2748 	}
2749 	/* NOTREACHED */
2750 discard_pkt:
2751 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2752 drop_pkt:;
2753 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2754 	freemsg(first_mp);
2755 }
2756 
2757 /*
2758  * Common IP options parser.
2759  *
2760  * Setup routine: fill in *optp with options-parsing state, then
2761  * tail-call ipoptp_next to return the first option.
2762  */
2763 uint8_t
2764 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2765 {
2766 	uint32_t totallen; /* total length of all options */
2767 
2768 	totallen = ipha->ipha_version_and_hdr_length -
2769 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2770 	totallen <<= 2;
2771 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2772 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2773 	optp->ipoptp_flags = 0;
2774 	return (ipoptp_next(optp));
2775 }
2776 
2777 /*
2778  * Common IP options parser: extract next option.
2779  */
2780 uint8_t
2781 ipoptp_next(ipoptp_t *optp)
2782 {
2783 	uint8_t *end = optp->ipoptp_end;
2784 	uint8_t *cur = optp->ipoptp_next;
2785 	uint8_t opt, len, pointer;
2786 
2787 	/*
2788 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2789 	 * has been corrupted.
2790 	 */
2791 	ASSERT(cur <= end);
2792 
2793 	if (cur == end)
2794 		return (IPOPT_EOL);
2795 
2796 	opt = cur[IPOPT_OPTVAL];
2797 
2798 	/*
2799 	 * Skip any NOP options.
2800 	 */
2801 	while (opt == IPOPT_NOP) {
2802 		cur++;
2803 		if (cur == end)
2804 			return (IPOPT_EOL);
2805 		opt = cur[IPOPT_OPTVAL];
2806 	}
2807 
2808 	if (opt == IPOPT_EOL)
2809 		return (IPOPT_EOL);
2810 
2811 	/*
2812 	 * Option requiring a length.
2813 	 */
2814 	if ((cur + 1) >= end) {
2815 		optp->ipoptp_flags |= IPOPTP_ERROR;
2816 		return (IPOPT_EOL);
2817 	}
2818 	len = cur[IPOPT_OLEN];
2819 	if (len < 2) {
2820 		optp->ipoptp_flags |= IPOPTP_ERROR;
2821 		return (IPOPT_EOL);
2822 	}
2823 	optp->ipoptp_cur = cur;
2824 	optp->ipoptp_len = len;
2825 	optp->ipoptp_next = cur + len;
2826 	if (cur + len > end) {
2827 		optp->ipoptp_flags |= IPOPTP_ERROR;
2828 		return (IPOPT_EOL);
2829 	}
2830 
2831 	/*
2832 	 * For the options which require a pointer field, make sure
2833 	 * its there, and make sure it points to either something
2834 	 * inside this option, or the end of the option.
2835 	 */
2836 	switch (opt) {
2837 	case IPOPT_RR:
2838 	case IPOPT_TS:
2839 	case IPOPT_LSRR:
2840 	case IPOPT_SSRR:
2841 		if (len <= IPOPT_OFFSET) {
2842 			optp->ipoptp_flags |= IPOPTP_ERROR;
2843 			return (opt);
2844 		}
2845 		pointer = cur[IPOPT_OFFSET];
2846 		if (pointer - 1 > len) {
2847 			optp->ipoptp_flags |= IPOPTP_ERROR;
2848 			return (opt);
2849 		}
2850 		break;
2851 	}
2852 
2853 	/*
2854 	 * Sanity check the pointer field based on the type of the
2855 	 * option.
2856 	 */
2857 	switch (opt) {
2858 	case IPOPT_RR:
2859 	case IPOPT_SSRR:
2860 	case IPOPT_LSRR:
2861 		if (pointer < IPOPT_MINOFF_SR)
2862 			optp->ipoptp_flags |= IPOPTP_ERROR;
2863 		break;
2864 	case IPOPT_TS:
2865 		if (pointer < IPOPT_MINOFF_IT)
2866 			optp->ipoptp_flags |= IPOPTP_ERROR;
2867 		/*
2868 		 * Note that the Internet Timestamp option also
2869 		 * contains two four bit fields (the Overflow field,
2870 		 * and the Flag field), which follow the pointer
2871 		 * field.  We don't need to check that these fields
2872 		 * fall within the length of the option because this
2873 		 * was implicitely done above.  We've checked that the
2874 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2875 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2876 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2877 		 */
2878 		ASSERT(len > IPOPT_POS_OV_FLG);
2879 		break;
2880 	}
2881 
2882 	return (opt);
2883 }
2884 
2885 /*
2886  * Use the outgoing IP header to create an IP_OPTIONS option the way
2887  * it was passed down from the application.
2888  */
2889 int
2890 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2891 {
2892 	ipoptp_t	opts;
2893 	const uchar_t	*opt;
2894 	uint8_t		optval;
2895 	uint8_t		optlen;
2896 	uint32_t	len = 0;
2897 	uchar_t	*buf1 = buf;
2898 
2899 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2900 	len += IP_ADDR_LEN;
2901 	bzero(buf1, IP_ADDR_LEN);
2902 
2903 	/*
2904 	 * OK to cast away const here, as we don't store through the returned
2905 	 * opts.ipoptp_cur pointer.
2906 	 */
2907 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2908 	    optval != IPOPT_EOL;
2909 	    optval = ipoptp_next(&opts)) {
2910 		int	off;
2911 
2912 		opt = opts.ipoptp_cur;
2913 		optlen = opts.ipoptp_len;
2914 		switch (optval) {
2915 		case IPOPT_SSRR:
2916 		case IPOPT_LSRR:
2917 
2918 			/*
2919 			 * Insert ipha_dst as the first entry in the source
2920 			 * route and move down the entries on step.
2921 			 * The last entry gets placed at buf1.
2922 			 */
2923 			buf[IPOPT_OPTVAL] = optval;
2924 			buf[IPOPT_OLEN] = optlen;
2925 			buf[IPOPT_OFFSET] = optlen;
2926 
2927 			off = optlen - IP_ADDR_LEN;
2928 			if (off < 0) {
2929 				/* No entries in source route */
2930 				break;
2931 			}
2932 			/* Last entry in source route */
2933 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2934 			off -= IP_ADDR_LEN;
2935 
2936 			while (off > 0) {
2937 				bcopy(opt + off,
2938 				    buf + off + IP_ADDR_LEN,
2939 				    IP_ADDR_LEN);
2940 				off -= IP_ADDR_LEN;
2941 			}
2942 			/* ipha_dst into first slot */
2943 			bcopy(&ipha->ipha_dst,
2944 			    buf + off + IP_ADDR_LEN,
2945 			    IP_ADDR_LEN);
2946 			buf += optlen;
2947 			len += optlen;
2948 			break;
2949 
2950 		case IPOPT_COMSEC:
2951 		case IPOPT_SECURITY:
2952 			/* if passing up a label is not ok, then remove */
2953 			if (is_system_labeled())
2954 				break;
2955 			/* FALLTHROUGH */
2956 		default:
2957 			bcopy(opt, buf, optlen);
2958 			buf += optlen;
2959 			len += optlen;
2960 			break;
2961 		}
2962 	}
2963 done:
2964 	/* Pad the resulting options */
2965 	while (len & 0x3) {
2966 		*buf++ = IPOPT_EOL;
2967 		len++;
2968 	}
2969 	return (len);
2970 }
2971 
2972 /*
2973  * Update any record route or timestamp options to include this host.
2974  * Reverse any source route option.
2975  * This routine assumes that the options are well formed i.e. that they
2976  * have already been checked.
2977  */
2978 static void
2979 icmp_options_update(ipha_t *ipha)
2980 {
2981 	ipoptp_t	opts;
2982 	uchar_t		*opt;
2983 	uint8_t		optval;
2984 	ipaddr_t	src;		/* Our local address */
2985 	ipaddr_t	dst;
2986 
2987 	ip2dbg(("icmp_options_update\n"));
2988 	src = ipha->ipha_src;
2989 	dst = ipha->ipha_dst;
2990 
2991 	for (optval = ipoptp_first(&opts, ipha);
2992 	    optval != IPOPT_EOL;
2993 	    optval = ipoptp_next(&opts)) {
2994 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2995 		opt = opts.ipoptp_cur;
2996 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2997 		    optval, opts.ipoptp_len));
2998 		switch (optval) {
2999 			int off1, off2;
3000 		case IPOPT_SSRR:
3001 		case IPOPT_LSRR:
3002 			/*
3003 			 * Reverse the source route.  The first entry
3004 			 * should be the next to last one in the current
3005 			 * source route (the last entry is our address).
3006 			 * The last entry should be the final destination.
3007 			 */
3008 			off1 = IPOPT_MINOFF_SR - 1;
3009 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3010 			if (off2 < 0) {
3011 				/* No entries in source route */
3012 				ip1dbg((
3013 				    "icmp_options_update: bad src route\n"));
3014 				break;
3015 			}
3016 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3017 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3018 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3019 			off2 -= IP_ADDR_LEN;
3020 
3021 			while (off1 < off2) {
3022 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3023 				bcopy((char *)opt + off2, (char *)opt + off1,
3024 				    IP_ADDR_LEN);
3025 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3026 				off1 += IP_ADDR_LEN;
3027 				off2 -= IP_ADDR_LEN;
3028 			}
3029 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3030 			break;
3031 		}
3032 	}
3033 }
3034 
3035 /*
3036  * Process received ICMP Redirect messages.
3037  */
3038 static void
3039 icmp_redirect(ill_t *ill, mblk_t *mp)
3040 {
3041 	ipha_t	*ipha;
3042 	int	iph_hdr_length;
3043 	icmph_t	*icmph;
3044 	ipha_t	*ipha_err;
3045 	ire_t	*ire;
3046 	ire_t	*prev_ire;
3047 	ire_t	*save_ire;
3048 	ipaddr_t  src, dst, gateway;
3049 	iulp_t	ulp_info = { 0 };
3050 	int	error;
3051 	ip_stack_t *ipst;
3052 
3053 	ASSERT(ill != NULL);
3054 	ipst = ill->ill_ipst;
3055 
3056 	ipha = (ipha_t *)mp->b_rptr;
3057 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3058 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3059 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3060 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3061 		freemsg(mp);
3062 		return;
3063 	}
3064 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3065 	ipha_err = (ipha_t *)&icmph[1];
3066 	src = ipha->ipha_src;
3067 	dst = ipha_err->ipha_dst;
3068 	gateway = icmph->icmph_rd_gateway;
3069 	/* Make sure the new gateway is reachable somehow. */
3070 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3071 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3072 	/*
3073 	 * Make sure we had a route for the dest in question and that
3074 	 * that route was pointing to the old gateway (the source of the
3075 	 * redirect packet.)
3076 	 */
3077 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3078 	    NULL, MATCH_IRE_GW, ipst);
3079 	/*
3080 	 * Check that
3081 	 *	the redirect was not from ourselves
3082 	 *	the new gateway and the old gateway are directly reachable
3083 	 */
3084 	if (!prev_ire ||
3085 	    !ire ||
3086 	    ire->ire_type == IRE_LOCAL) {
3087 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3088 		freemsg(mp);
3089 		if (ire != NULL)
3090 			ire_refrele(ire);
3091 		if (prev_ire != NULL)
3092 			ire_refrele(prev_ire);
3093 		return;
3094 	}
3095 
3096 	/*
3097 	 * Should we use the old ULP info to create the new gateway?  From
3098 	 * a user's perspective, we should inherit the info so that it
3099 	 * is a "smooth" transition.  If we do not do that, then new
3100 	 * connections going thru the new gateway will have no route metrics,
3101 	 * which is counter-intuitive to user.  From a network point of
3102 	 * view, this may or may not make sense even though the new gateway
3103 	 * is still directly connected to us so the route metrics should not
3104 	 * change much.
3105 	 *
3106 	 * But if the old ire_uinfo is not initialized, we do another
3107 	 * recursive lookup on the dest using the new gateway.  There may
3108 	 * be a route to that.  If so, use it to initialize the redirect
3109 	 * route.
3110 	 */
3111 	if (prev_ire->ire_uinfo.iulp_set) {
3112 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3113 	} else {
3114 		ire_t *tmp_ire;
3115 		ire_t *sire;
3116 
3117 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3118 		    ALL_ZONES, 0, NULL,
3119 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3120 		    ipst);
3121 		if (sire != NULL) {
3122 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3123 			/*
3124 			 * If sire != NULL, ire_ftable_lookup() should not
3125 			 * return a NULL value.
3126 			 */
3127 			ASSERT(tmp_ire != NULL);
3128 			ire_refrele(tmp_ire);
3129 			ire_refrele(sire);
3130 		} else if (tmp_ire != NULL) {
3131 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3132 			    sizeof (iulp_t));
3133 			ire_refrele(tmp_ire);
3134 		}
3135 	}
3136 	if (prev_ire->ire_type == IRE_CACHE)
3137 		ire_delete(prev_ire);
3138 	ire_refrele(prev_ire);
3139 	/*
3140 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3141 	 * require TOS routing
3142 	 */
3143 	switch (icmph->icmph_code) {
3144 	case 0:
3145 	case 1:
3146 		/* TODO: TOS specificity for cases 2 and 3 */
3147 	case 2:
3148 	case 3:
3149 		break;
3150 	default:
3151 		freemsg(mp);
3152 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3153 		ire_refrele(ire);
3154 		return;
3155 	}
3156 	/*
3157 	 * Create a Route Association.  This will allow us to remember that
3158 	 * someone we believe told us to use the particular gateway.
3159 	 */
3160 	save_ire = ire;
3161 	ire = ire_create(
3162 	    (uchar_t *)&dst,			/* dest addr */
3163 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3164 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3165 	    (uchar_t *)&gateway,		/* gateway addr */
3166 	    &save_ire->ire_max_frag,		/* max frag */
3167 	    NULL,				/* no src nce */
3168 	    NULL,				/* no rfq */
3169 	    NULL,				/* no stq */
3170 	    IRE_HOST,
3171 	    NULL,				/* ipif */
3172 	    0,					/* cmask */
3173 	    0,					/* phandle */
3174 	    0,					/* ihandle */
3175 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3176 	    &ulp_info,
3177 	    NULL,				/* tsol_gc_t */
3178 	    NULL,				/* gcgrp */
3179 	    ipst);
3180 
3181 	if (ire == NULL) {
3182 		freemsg(mp);
3183 		ire_refrele(save_ire);
3184 		return;
3185 	}
3186 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3187 	ire_refrele(save_ire);
3188 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3189 
3190 	if (error == 0) {
3191 		ire_refrele(ire);		/* Held in ire_add_v4 */
3192 		/* tell routing sockets that we received a redirect */
3193 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3194 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3195 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3196 	}
3197 
3198 	/*
3199 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3200 	 * This together with the added IRE has the effect of
3201 	 * modifying an existing redirect.
3202 	 */
3203 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3204 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3205 	if (prev_ire != NULL) {
3206 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3207 			ire_delete(prev_ire);
3208 		ire_refrele(prev_ire);
3209 	}
3210 
3211 	freemsg(mp);
3212 }
3213 
3214 /*
3215  * Generate an ICMP parameter problem message.
3216  */
3217 static void
3218 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3219 	ip_stack_t *ipst)
3220 {
3221 	icmph_t	icmph;
3222 	boolean_t mctl_present;
3223 	mblk_t *first_mp;
3224 
3225 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3226 
3227 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3228 		if (mctl_present)
3229 			freeb(first_mp);
3230 		return;
3231 	}
3232 
3233 	bzero(&icmph, sizeof (icmph_t));
3234 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3235 	icmph.icmph_pp_ptr = ptr;
3236 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3237 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3238 	    ipst);
3239 }
3240 
3241 /*
3242  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3243  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3244  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3245  * an icmp error packet can be sent.
3246  * Assigns an appropriate source address to the packet. If ipha_dst is
3247  * one of our addresses use it for source. Otherwise pick a source based
3248  * on a route lookup back to ipha_src.
3249  * Note that ipha_src must be set here since the
3250  * packet is likely to arrive on an ill queue in ip_wput() which will
3251  * not set a source address.
3252  */
3253 static void
3254 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3255     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3256 {
3257 	ipaddr_t dst;
3258 	icmph_t	*icmph;
3259 	ipha_t	*ipha;
3260 	uint_t	len_needed;
3261 	size_t	msg_len;
3262 	mblk_t	*mp1;
3263 	ipaddr_t src;
3264 	ire_t	*ire;
3265 	mblk_t *ipsec_mp;
3266 	ipsec_out_t	*io = NULL;
3267 
3268 	if (mctl_present) {
3269 		/*
3270 		 * If it is :
3271 		 *
3272 		 * 1) a IPSEC_OUT, then this is caused by outbound
3273 		 *    datagram originating on this host. IPsec processing
3274 		 *    may or may not have been done. Refer to comments above
3275 		 *    icmp_inbound_error_fanout for details.
3276 		 *
3277 		 * 2) a IPSEC_IN if we are generating a icmp_message
3278 		 *    for an incoming datagram destined for us i.e called
3279 		 *    from ip_fanout_send_icmp.
3280 		 */
3281 		ipsec_info_t *in;
3282 		ipsec_mp = mp;
3283 		mp = ipsec_mp->b_cont;
3284 
3285 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3286 		ipha = (ipha_t *)mp->b_rptr;
3287 
3288 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3289 		    in->ipsec_info_type == IPSEC_IN);
3290 
3291 		if (in->ipsec_info_type == IPSEC_IN) {
3292 			/*
3293 			 * Convert the IPSEC_IN to IPSEC_OUT.
3294 			 */
3295 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3296 				BUMP_MIB(&ipst->ips_ip_mib,
3297 				    ipIfStatsOutDiscards);
3298 				return;
3299 			}
3300 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3301 		} else {
3302 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3303 			io = (ipsec_out_t *)in;
3304 			/*
3305 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3306 			 * ire lookup.
3307 			 */
3308 			io->ipsec_out_proc_begin = B_FALSE;
3309 		}
3310 		ASSERT(zoneid != ALL_ZONES);
3311 		/*
3312 		 * The IPSEC_IN (now an IPSEC_OUT) didn't have its zoneid
3313 		 * initialized.  We need to do that now.
3314 		 */
3315 		io->ipsec_out_zoneid = zoneid;
3316 	} else {
3317 		/*
3318 		 * This is in clear. The icmp message we are building
3319 		 * here should go out in clear.
3320 		 *
3321 		 * Pardon the convolution of it all, but it's easier to
3322 		 * allocate a "use cleartext" IPSEC_IN message and convert
3323 		 * it than it is to allocate a new one.
3324 		 */
3325 		ipsec_in_t *ii;
3326 		ASSERT(DB_TYPE(mp) == M_DATA);
3327 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3328 		if (ipsec_mp == NULL) {
3329 			freemsg(mp);
3330 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3331 			return;
3332 		}
3333 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3334 
3335 		/* This is not a secure packet */
3336 		ii->ipsec_in_secure = B_FALSE;
3337 		/*
3338 		 * For trusted extensions using a shared IP address we can
3339 		 * send using any zoneid.
3340 		 */
3341 		if (zoneid == ALL_ZONES)
3342 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3343 		else
3344 			ii->ipsec_in_zoneid = zoneid;
3345 		ipsec_mp->b_cont = mp;
3346 		ipha = (ipha_t *)mp->b_rptr;
3347 		/*
3348 		 * Convert the IPSEC_IN to IPSEC_OUT.
3349 		 */
3350 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3351 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3352 			return;
3353 		}
3354 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3355 	}
3356 
3357 	/* Remember our eventual destination */
3358 	dst = ipha->ipha_src;
3359 
3360 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3361 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3362 	if (ire != NULL &&
3363 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3364 		src = ipha->ipha_dst;
3365 	} else {
3366 		if (ire != NULL)
3367 			ire_refrele(ire);
3368 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3369 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3370 		    ipst);
3371 		if (ire == NULL) {
3372 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3373 			freemsg(ipsec_mp);
3374 			return;
3375 		}
3376 		src = ire->ire_src_addr;
3377 	}
3378 
3379 	if (ire != NULL)
3380 		ire_refrele(ire);
3381 
3382 	/*
3383 	 * Check if we can send back more then 8 bytes in addition to
3384 	 * the IP header.  We try to send 64 bytes of data and the internal
3385 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3386 	 */
3387 	len_needed = IPH_HDR_LENGTH(ipha);
3388 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3389 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3390 
3391 		if (!pullupmsg(mp, -1)) {
3392 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3393 			freemsg(ipsec_mp);
3394 			return;
3395 		}
3396 		ipha = (ipha_t *)mp->b_rptr;
3397 
3398 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3399 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3400 			    len_needed));
3401 		} else {
3402 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3403 
3404 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3405 			len_needed += ip_hdr_length_v6(mp, ip6h);
3406 		}
3407 	}
3408 	len_needed += ipst->ips_ip_icmp_return;
3409 	msg_len = msgdsize(mp);
3410 	if (msg_len > len_needed) {
3411 		(void) adjmsg(mp, len_needed - msg_len);
3412 		msg_len = len_needed;
3413 	}
3414 	/* Make sure we propagate the cred/label for TX */
3415 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3416 	if (mp1 == NULL) {
3417 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3418 		freemsg(ipsec_mp);
3419 		return;
3420 	}
3421 	mp1->b_cont = mp;
3422 	mp = mp1;
3423 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3424 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3425 	    io->ipsec_out_type == IPSEC_OUT);
3426 	ipsec_mp->b_cont = mp;
3427 
3428 	/*
3429 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3430 	 * node generates be accepted in peace by all on-host destinations.
3431 	 * If we do NOT assume that all on-host destinations trust
3432 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3433 	 * (Look for ipsec_out_icmp_loopback).
3434 	 */
3435 	io->ipsec_out_icmp_loopback = B_TRUE;
3436 
3437 	ipha = (ipha_t *)mp->b_rptr;
3438 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3439 	*ipha = icmp_ipha;
3440 	ipha->ipha_src = src;
3441 	ipha->ipha_dst = dst;
3442 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3443 	msg_len += sizeof (icmp_ipha) + len;
3444 	if (msg_len > IP_MAXPACKET) {
3445 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3446 		msg_len = IP_MAXPACKET;
3447 	}
3448 	ipha->ipha_length = htons((uint16_t)msg_len);
3449 	icmph = (icmph_t *)&ipha[1];
3450 	bcopy(stuff, icmph, len);
3451 	icmph->icmph_checksum = 0;
3452 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3453 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3454 	put(q, ipsec_mp);
3455 }
3456 
3457 /*
3458  * Determine if an ICMP error packet can be sent given the rate limit.
3459  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3460  * in milliseconds) and a burst size. Burst size number of packets can
3461  * be sent arbitrarely closely spaced.
3462  * The state is tracked using two variables to implement an approximate
3463  * token bucket filter:
3464  *	icmp_pkt_err_last - lbolt value when the last burst started
3465  *	icmp_pkt_err_sent - number of packets sent in current burst
3466  */
3467 boolean_t
3468 icmp_err_rate_limit(ip_stack_t *ipst)
3469 {
3470 	clock_t now = TICK_TO_MSEC(lbolt);
3471 	uint_t refilled; /* Number of packets refilled in tbf since last */
3472 	/* Guard against changes by loading into local variable */
3473 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3474 
3475 	if (err_interval == 0)
3476 		return (B_FALSE);
3477 
3478 	if (ipst->ips_icmp_pkt_err_last > now) {
3479 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3480 		ipst->ips_icmp_pkt_err_last = 0;
3481 		ipst->ips_icmp_pkt_err_sent = 0;
3482 	}
3483 	/*
3484 	 * If we are in a burst update the token bucket filter.
3485 	 * Update the "last" time to be close to "now" but make sure
3486 	 * we don't loose precision.
3487 	 */
3488 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3489 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3490 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3491 			ipst->ips_icmp_pkt_err_sent = 0;
3492 		} else {
3493 			ipst->ips_icmp_pkt_err_sent -= refilled;
3494 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3495 		}
3496 	}
3497 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3498 		/* Start of new burst */
3499 		ipst->ips_icmp_pkt_err_last = now;
3500 	}
3501 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3502 		ipst->ips_icmp_pkt_err_sent++;
3503 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3504 		    ipst->ips_icmp_pkt_err_sent));
3505 		return (B_FALSE);
3506 	}
3507 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3508 	return (B_TRUE);
3509 }
3510 
3511 /*
3512  * Check if it is ok to send an IPv4 ICMP error packet in
3513  * response to the IPv4 packet in mp.
3514  * Free the message and return null if no
3515  * ICMP error packet should be sent.
3516  */
3517 static mblk_t *
3518 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3519 {
3520 	icmph_t	*icmph;
3521 	ipha_t	*ipha;
3522 	uint_t	len_needed;
3523 	ire_t	*src_ire;
3524 	ire_t	*dst_ire;
3525 
3526 	if (!mp)
3527 		return (NULL);
3528 	ipha = (ipha_t *)mp->b_rptr;
3529 	if (ip_csum_hdr(ipha)) {
3530 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3531 		freemsg(mp);
3532 		return (NULL);
3533 	}
3534 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3535 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3536 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3537 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3538 	if (src_ire != NULL || dst_ire != NULL ||
3539 	    CLASSD(ipha->ipha_dst) ||
3540 	    CLASSD(ipha->ipha_src) ||
3541 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3542 		/* Note: only errors to the fragment with offset 0 */
3543 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3544 		freemsg(mp);
3545 		if (src_ire != NULL)
3546 			ire_refrele(src_ire);
3547 		if (dst_ire != NULL)
3548 			ire_refrele(dst_ire);
3549 		return (NULL);
3550 	}
3551 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3552 		/*
3553 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3554 		 * errors in response to any ICMP errors.
3555 		 */
3556 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3557 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3558 			if (!pullupmsg(mp, len_needed)) {
3559 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3560 				freemsg(mp);
3561 				return (NULL);
3562 			}
3563 			ipha = (ipha_t *)mp->b_rptr;
3564 		}
3565 		icmph = (icmph_t *)
3566 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3567 		switch (icmph->icmph_type) {
3568 		case ICMP_DEST_UNREACHABLE:
3569 		case ICMP_SOURCE_QUENCH:
3570 		case ICMP_TIME_EXCEEDED:
3571 		case ICMP_PARAM_PROBLEM:
3572 		case ICMP_REDIRECT:
3573 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3574 			freemsg(mp);
3575 			return (NULL);
3576 		default:
3577 			break;
3578 		}
3579 	}
3580 	/*
3581 	 * If this is a labeled system, then check to see if we're allowed to
3582 	 * send a response to this particular sender.  If not, then just drop.
3583 	 */
3584 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3585 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3586 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3587 		freemsg(mp);
3588 		return (NULL);
3589 	}
3590 	if (icmp_err_rate_limit(ipst)) {
3591 		/*
3592 		 * Only send ICMP error packets every so often.
3593 		 * This should be done on a per port/source basis,
3594 		 * but for now this will suffice.
3595 		 */
3596 		freemsg(mp);
3597 		return (NULL);
3598 	}
3599 	return (mp);
3600 }
3601 
3602 /*
3603  * Generate an ICMP redirect message.
3604  */
3605 static void
3606 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3607 {
3608 	icmph_t	icmph;
3609 
3610 	/*
3611 	 * We are called from ip_rput where we could
3612 	 * not have attached an IPSEC_IN.
3613 	 */
3614 	ASSERT(mp->b_datap->db_type == M_DATA);
3615 
3616 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3617 		return;
3618 	}
3619 
3620 	bzero(&icmph, sizeof (icmph_t));
3621 	icmph.icmph_type = ICMP_REDIRECT;
3622 	icmph.icmph_code = 1;
3623 	icmph.icmph_rd_gateway = gateway;
3624 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3625 	/* Redirects sent by router, and router is global zone */
3626 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3627 }
3628 
3629 /*
3630  * Generate an ICMP time exceeded message.
3631  */
3632 void
3633 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3634     ip_stack_t *ipst)
3635 {
3636 	icmph_t	icmph;
3637 	boolean_t mctl_present;
3638 	mblk_t *first_mp;
3639 
3640 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3641 
3642 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3643 		if (mctl_present)
3644 			freeb(first_mp);
3645 		return;
3646 	}
3647 
3648 	bzero(&icmph, sizeof (icmph_t));
3649 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3650 	icmph.icmph_code = code;
3651 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3652 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3653 	    ipst);
3654 }
3655 
3656 /*
3657  * Generate an ICMP unreachable message.
3658  */
3659 void
3660 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3661     ip_stack_t *ipst)
3662 {
3663 	icmph_t	icmph;
3664 	mblk_t *first_mp;
3665 	boolean_t mctl_present;
3666 
3667 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3668 
3669 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3670 		if (mctl_present)
3671 			freeb(first_mp);
3672 		return;
3673 	}
3674 
3675 	bzero(&icmph, sizeof (icmph_t));
3676 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3677 	icmph.icmph_code = code;
3678 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3679 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3680 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3681 	    zoneid, ipst);
3682 }
3683 
3684 /*
3685  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3686  * duplicate.  As long as someone else holds the address, the interface will
3687  * stay down.  When that conflict goes away, the interface is brought back up.
3688  * This is done so that accidental shutdowns of addresses aren't made
3689  * permanent.  Your server will recover from a failure.
3690  *
3691  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3692  * user space process (dhcpagent).
3693  *
3694  * Recovery completes if ARP reports that the address is now ours (via
3695  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3696  *
3697  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3698  */
3699 static void
3700 ipif_dup_recovery(void *arg)
3701 {
3702 	ipif_t *ipif = arg;
3703 	ill_t *ill = ipif->ipif_ill;
3704 	mblk_t *arp_add_mp;
3705 	mblk_t *arp_del_mp;
3706 	ip_stack_t *ipst = ill->ill_ipst;
3707 
3708 	ipif->ipif_recovery_id = 0;
3709 
3710 	/*
3711 	 * No lock needed for moving or condemned check, as this is just an
3712 	 * optimization.
3713 	 */
3714 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3715 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3716 	    (ipif->ipif_state_flags & (IPIF_CONDEMNED))) {
3717 		/* No reason to try to bring this address back. */
3718 		return;
3719 	}
3720 
3721 	/* ACE_F_UNVERIFIED restarts DAD */
3722 	if ((arp_add_mp = ipif_area_alloc(ipif, ACE_F_UNVERIFIED)) == NULL)
3723 		goto alloc_fail;
3724 
3725 	if (ipif->ipif_arp_del_mp == NULL) {
3726 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3727 			goto alloc_fail;
3728 		ipif->ipif_arp_del_mp = arp_del_mp;
3729 	}
3730 
3731 	putnext(ill->ill_rq, arp_add_mp);
3732 	return;
3733 
3734 alloc_fail:
3735 	/*
3736 	 * On allocation failure, just restart the timer.  Note that the ipif
3737 	 * is down here, so no other thread could be trying to start a recovery
3738 	 * timer.  The ill_lock protects the condemned flag and the recovery
3739 	 * timer ID.
3740 	 */
3741 	freemsg(arp_add_mp);
3742 	mutex_enter(&ill->ill_lock);
3743 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3744 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3745 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3746 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3747 	}
3748 	mutex_exit(&ill->ill_lock);
3749 }
3750 
3751 /*
3752  * This is for exclusive changes due to ARP.  Either tear down an interface due
3753  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3754  */
3755 /* ARGSUSED */
3756 static void
3757 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3758 {
3759 	ill_t	*ill = rq->q_ptr;
3760 	arh_t *arh;
3761 	ipaddr_t src;
3762 	ipif_t	*ipif;
3763 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3764 	char hbuf[MAC_STR_LEN];
3765 	char sbuf[INET_ADDRSTRLEN];
3766 	const char *failtype;
3767 	boolean_t bring_up;
3768 	ip_stack_t *ipst = ill->ill_ipst;
3769 
3770 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3771 	case AR_CN_READY:
3772 		failtype = NULL;
3773 		bring_up = B_TRUE;
3774 		break;
3775 	case AR_CN_FAILED:
3776 		failtype = "in use";
3777 		bring_up = B_FALSE;
3778 		break;
3779 	default:
3780 		failtype = "claimed";
3781 		bring_up = B_FALSE;
3782 		break;
3783 	}
3784 
3785 	arh = (arh_t *)mp->b_cont->b_rptr;
3786 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3787 
3788 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3789 	    sizeof (hbuf));
3790 	(void) ip_dot_addr(src, sbuf);
3791 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3792 
3793 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3794 		    ipif->ipif_lcl_addr != src) {
3795 			continue;
3796 		}
3797 
3798 		/*
3799 		 * If we failed on a recovery probe, then restart the timer to
3800 		 * try again later.
3801 		 */
3802 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3803 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3804 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3805 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3806 		    ipst->ips_ip_dup_recovery > 0 &&
3807 		    ipif->ipif_recovery_id == 0) {
3808 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3809 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3810 			continue;
3811 		}
3812 
3813 		/*
3814 		 * If what we're trying to do has already been done, then do
3815 		 * nothing.
3816 		 */
3817 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3818 			continue;
3819 
3820 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3821 
3822 		if (failtype == NULL) {
3823 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3824 			    ibuf);
3825 		} else {
3826 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3827 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3828 		}
3829 
3830 		if (bring_up) {
3831 			ASSERT(ill->ill_dl_up);
3832 			/*
3833 			 * Free up the ARP delete message so we can allocate
3834 			 * a fresh one through the normal path.
3835 			 */
3836 			freemsg(ipif->ipif_arp_del_mp);
3837 			ipif->ipif_arp_del_mp = NULL;
3838 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3839 			    EINPROGRESS) {
3840 				ipif->ipif_addr_ready = 1;
3841 				(void) ipif_up_done(ipif);
3842 				ASSERT(ill->ill_move_ipif == NULL);
3843 			}
3844 			continue;
3845 		}
3846 
3847 		mutex_enter(&ill->ill_lock);
3848 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3849 		ipif->ipif_flags |= IPIF_DUPLICATE;
3850 		ill->ill_ipif_dup_count++;
3851 		mutex_exit(&ill->ill_lock);
3852 		/*
3853 		 * Already exclusive on the ill; no need to handle deferred
3854 		 * processing here.
3855 		 */
3856 		(void) ipif_down(ipif, NULL, NULL);
3857 		ipif_down_tail(ipif);
3858 		mutex_enter(&ill->ill_lock);
3859 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3860 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3861 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3862 		    ipst->ips_ip_dup_recovery > 0) {
3863 			ASSERT(ipif->ipif_recovery_id == 0);
3864 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3865 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3866 		}
3867 		mutex_exit(&ill->ill_lock);
3868 	}
3869 	freemsg(mp);
3870 }
3871 
3872 /* ARGSUSED */
3873 static void
3874 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3875 {
3876 	ill_t	*ill = rq->q_ptr;
3877 	arh_t *arh;
3878 	ipaddr_t src;
3879 	ipif_t	*ipif;
3880 
3881 	arh = (arh_t *)mp->b_cont->b_rptr;
3882 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3883 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3884 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3885 			(void) ipif_resolver_up(ipif, Res_act_defend);
3886 	}
3887 	freemsg(mp);
3888 }
3889 
3890 /*
3891  * News from ARP.  ARP sends notification of interesting events down
3892  * to its clients using M_CTL messages with the interesting ARP packet
3893  * attached via b_cont.
3894  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3895  * queue as opposed to ARP sending the message to all the clients, i.e. all
3896  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3897  * table if a cache IRE is found to delete all the entries for the address in
3898  * the packet.
3899  */
3900 static void
3901 ip_arp_news(queue_t *q, mblk_t *mp)
3902 {
3903 	arcn_t		*arcn;
3904 	arh_t		*arh;
3905 	ire_t		*ire = NULL;
3906 	char		hbuf[MAC_STR_LEN];
3907 	char		sbuf[INET_ADDRSTRLEN];
3908 	ipaddr_t	src;
3909 	in6_addr_t	v6src;
3910 	boolean_t	isv6 = B_FALSE;
3911 	ipif_t		*ipif;
3912 	ill_t		*ill;
3913 	ip_stack_t	*ipst;
3914 
3915 	if (CONN_Q(q)) {
3916 		conn_t *connp = Q_TO_CONN(q);
3917 
3918 		ipst = connp->conn_netstack->netstack_ip;
3919 	} else {
3920 		ill_t *ill = (ill_t *)q->q_ptr;
3921 
3922 		ipst = ill->ill_ipst;
3923 	}
3924 
3925 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3926 		if (q->q_next) {
3927 			putnext(q, mp);
3928 		} else
3929 			freemsg(mp);
3930 		return;
3931 	}
3932 	arh = (arh_t *)mp->b_cont->b_rptr;
3933 	/* Is it one we are interested in? */
3934 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3935 		isv6 = B_TRUE;
3936 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3937 		    IPV6_ADDR_LEN);
3938 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3939 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3940 		    IP_ADDR_LEN);
3941 	} else {
3942 		freemsg(mp);
3943 		return;
3944 	}
3945 
3946 	ill = q->q_ptr;
3947 
3948 	arcn = (arcn_t *)mp->b_rptr;
3949 	switch (arcn->arcn_code) {
3950 	case AR_CN_BOGON:
3951 		/*
3952 		 * Someone is sending ARP packets with a source protocol
3953 		 * address that we have published and for which we believe our
3954 		 * entry is authoritative and (when ill_arp_extend is set)
3955 		 * verified to be unique on the network.
3956 		 *
3957 		 * The ARP module internally handles the cases where the sender
3958 		 * is just probing (for DAD) and where the hardware address of
3959 		 * a non-authoritative entry has changed.  Thus, these are the
3960 		 * real conflicts, and we have to do resolution.
3961 		 *
3962 		 * We back away quickly from the address if it's from DHCP or
3963 		 * otherwise temporary and hasn't been used recently (or at
3964 		 * all).  We'd like to include "deprecated" addresses here as
3965 		 * well (as there's no real reason to defend something we're
3966 		 * discarding), but IPMP "reuses" this flag to mean something
3967 		 * other than the standard meaning.
3968 		 *
3969 		 * If the ARP module above is not extended (meaning that it
3970 		 * doesn't know how to defend the address), then we just log
3971 		 * the problem as we always did and continue on.  It's not
3972 		 * right, but there's little else we can do, and those old ATM
3973 		 * users are going away anyway.
3974 		 */
3975 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3976 		    hbuf, sizeof (hbuf));
3977 		(void) ip_dot_addr(src, sbuf);
3978 		if (isv6) {
3979 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3980 			    ipst);
3981 		} else {
3982 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3983 		}
3984 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3985 			uint32_t now;
3986 			uint32_t maxage;
3987 			clock_t lused;
3988 			uint_t maxdefense;
3989 			uint_t defs;
3990 
3991 			/*
3992 			 * First, figure out if this address hasn't been used
3993 			 * in a while.  If it hasn't, then it's a better
3994 			 * candidate for abandoning.
3995 			 */
3996 			ipif = ire->ire_ipif;
3997 			ASSERT(ipif != NULL);
3998 			now = gethrestime_sec();
3999 			maxage = now - ire->ire_create_time;
4000 			if (maxage > ipst->ips_ip_max_temp_idle)
4001 				maxage = ipst->ips_ip_max_temp_idle;
4002 			lused = drv_hztousec(ddi_get_lbolt() -
4003 			    ire->ire_last_used_time) / MICROSEC + 1;
4004 			if (lused >= maxage && (ipif->ipif_flags &
4005 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4006 				maxdefense = ipst->ips_ip_max_temp_defend;
4007 			else
4008 				maxdefense = ipst->ips_ip_max_defend;
4009 
4010 			/*
4011 			 * Now figure out how many times we've defended
4012 			 * ourselves.  Ignore defenses that happened long in
4013 			 * the past.
4014 			 */
4015 			mutex_enter(&ire->ire_lock);
4016 			if ((defs = ire->ire_defense_count) > 0 &&
4017 			    now - ire->ire_defense_time >
4018 			    ipst->ips_ip_defend_interval) {
4019 				ire->ire_defense_count = defs = 0;
4020 			}
4021 			ire->ire_defense_count++;
4022 			ire->ire_defense_time = now;
4023 			mutex_exit(&ire->ire_lock);
4024 			ill_refhold(ill);
4025 			ire_refrele(ire);
4026 
4027 			/*
4028 			 * If we've defended ourselves too many times already,
4029 			 * then give up and tear down the interface(s) using
4030 			 * this address.  Otherwise, defend by sending out a
4031 			 * gratuitous ARP.
4032 			 */
4033 			if (defs >= maxdefense && ill->ill_arp_extend) {
4034 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4035 				    B_FALSE);
4036 			} else {
4037 				cmn_err(CE_WARN,
4038 				    "node %s is using our IP address %s on %s",
4039 				    hbuf, sbuf, ill->ill_name);
4040 				/*
4041 				 * If this is an old (ATM) ARP module, then
4042 				 * don't try to defend the address.  Remain
4043 				 * compatible with the old behavior.  Defend
4044 				 * only with new ARP.
4045 				 */
4046 				if (ill->ill_arp_extend) {
4047 					qwriter_ip(ill, q, mp, ip_arp_defend,
4048 					    NEW_OP, B_FALSE);
4049 				} else {
4050 					ill_refrele(ill);
4051 				}
4052 			}
4053 			return;
4054 		}
4055 		cmn_err(CE_WARN,
4056 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4057 		    hbuf, sbuf, ill->ill_name);
4058 		if (ire != NULL)
4059 			ire_refrele(ire);
4060 		break;
4061 	case AR_CN_ANNOUNCE:
4062 		if (isv6) {
4063 			/*
4064 			 * For XRESOLV interfaces.
4065 			 * Delete the IRE cache entry and NCE for this
4066 			 * v6 address
4067 			 */
4068 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4069 			/*
4070 			 * If v6src is a non-zero, it's a router address
4071 			 * as below. Do the same sort of thing to clean
4072 			 * out off-net IRE_CACHE entries that go through
4073 			 * the router.
4074 			 */
4075 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4076 				ire_walk_v6(ire_delete_cache_gw_v6,
4077 				    (char *)&v6src, ALL_ZONES, ipst);
4078 			}
4079 		} else {
4080 			nce_hw_map_t hwm;
4081 
4082 			/*
4083 			 * ARP gives us a copy of any packet where it thinks
4084 			 * the address has changed, so that we can update our
4085 			 * caches.  We're responsible for caching known answers
4086 			 * in the current design.  We check whether the
4087 			 * hardware address really has changed in all of our
4088 			 * entries that have cached this mapping, and if so, we
4089 			 * blow them away.  This way we will immediately pick
4090 			 * up the rare case of a host changing hardware
4091 			 * address.
4092 			 */
4093 			if (src == 0)
4094 				break;
4095 			hwm.hwm_addr = src;
4096 			hwm.hwm_hwlen = arh->arh_hlen;
4097 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4098 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4099 			ndp_walk_common(ipst->ips_ndp4, NULL,
4100 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4101 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4102 		}
4103 		break;
4104 	case AR_CN_READY:
4105 		/* No external v6 resolver has a contract to use this */
4106 		if (isv6)
4107 			break;
4108 		/* If the link is down, we'll retry this later */
4109 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4110 			break;
4111 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4112 		    NULL, NULL, ipst);
4113 		if (ipif != NULL) {
4114 			/*
4115 			 * If this is a duplicate recovery, then we now need to
4116 			 * go exclusive to bring this thing back up.
4117 			 */
4118 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4119 			    IPIF_DUPLICATE) {
4120 				ipif_refrele(ipif);
4121 				ill_refhold(ill);
4122 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4123 				    B_FALSE);
4124 				return;
4125 			}
4126 			/*
4127 			 * If this is the first notice that this address is
4128 			 * ready, then let the user know now.
4129 			 */
4130 			if ((ipif->ipif_flags & IPIF_UP) &&
4131 			    !ipif->ipif_addr_ready) {
4132 				ipif_mask_reply(ipif);
4133 				ipif_up_notify(ipif);
4134 			}
4135 			ipif->ipif_addr_ready = 1;
4136 			ipif_refrele(ipif);
4137 		}
4138 		ire = ire_cache_lookup(src, ALL_ZONES, msg_getlabel(mp), ipst);
4139 		if (ire != NULL) {
4140 			ire->ire_defense_count = 0;
4141 			ire_refrele(ire);
4142 		}
4143 		break;
4144 	case AR_CN_FAILED:
4145 		/* No external v6 resolver has a contract to use this */
4146 		if (isv6)
4147 			break;
4148 		if (!ill->ill_arp_extend) {
4149 			(void) mac_colon_addr((uint8_t *)(arh + 1),
4150 			    arh->arh_hlen, hbuf, sizeof (hbuf));
4151 			(void) ip_dot_addr(src, sbuf);
4152 
4153 			cmn_err(CE_WARN,
4154 			    "node %s is using our IP address %s on %s",
4155 			    hbuf, sbuf, ill->ill_name);
4156 			break;
4157 		}
4158 		ill_refhold(ill);
4159 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4160 		return;
4161 	}
4162 	freemsg(mp);
4163 }
4164 
4165 /*
4166  * Create a mblk suitable for carrying the interface index and/or source link
4167  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4168  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4169  * application.
4170  */
4171 mblk_t *
4172 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4173     ip_stack_t *ipst)
4174 {
4175 	mblk_t		*mp;
4176 	ip_pktinfo_t	*pinfo;
4177 	ipha_t 		*ipha;
4178 	struct ether_header *pether;
4179 	boolean_t	ipmp_ill_held = B_FALSE;
4180 
4181 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4182 	if (mp == NULL) {
4183 		ip1dbg(("ip_add_info: allocation failure.\n"));
4184 		return (data_mp);
4185 	}
4186 
4187 	ipha = (ipha_t *)data_mp->b_rptr;
4188 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4189 	bzero(pinfo, sizeof (ip_pktinfo_t));
4190 	pinfo->ip_pkt_flags = (uchar_t)flags;
4191 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4192 
4193 	pether = (struct ether_header *)((char *)ipha
4194 	    - sizeof (struct ether_header));
4195 
4196 	/*
4197 	 * Make sure the interface is an ethernet type, since this option
4198 	 * is currently supported only on this type of interface. Also make
4199 	 * sure we are pointing correctly above db_base.
4200 	 */
4201 	if ((flags & IPF_RECVSLLA) &&
4202 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4203 	    (ill->ill_type == IFT_ETHER) &&
4204 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4205 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4206 		bcopy(pether->ether_shost.ether_addr_octet,
4207 		    pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4208 	} else {
4209 		/*
4210 		 * Clear the bit. Indicate to upper layer that IP is not
4211 		 * sending this ancillary info.
4212 		 */
4213 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4214 	}
4215 
4216 	/*
4217 	 * If `ill' is in an IPMP group, use the IPMP ill to determine
4218 	 * IPF_RECVIF and IPF_RECVADDR.  (This currently assumes that
4219 	 * IPF_RECVADDR support on test addresses is not needed.)
4220 	 *
4221 	 * Note that `ill' may already be an IPMP ill if e.g. we're
4222 	 * processing a packet looped back to an IPMP data address
4223 	 * (since those IRE_LOCALs are tied to IPMP ills).
4224 	 */
4225 	if (IS_UNDER_IPMP(ill)) {
4226 		if ((ill = ipmp_ill_hold_ipmp_ill(ill)) == NULL) {
4227 			ip1dbg(("ip_add_info: cannot hold IPMP ill.\n"));
4228 			freemsg(mp);
4229 			return (data_mp);
4230 		}
4231 		ipmp_ill_held = B_TRUE;
4232 	}
4233 
4234 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4235 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4236 	if (flags & IPF_RECVADDR) {
4237 		ipif_t	*ipif;
4238 		ire_t	*ire;
4239 
4240 		/*
4241 		 * Only valid for V4
4242 		 */
4243 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4244 		    (IPV4_VERSION << 4));
4245 
4246 		ipif = ipif_get_next_ipif(NULL, ill);
4247 		if (ipif != NULL) {
4248 			/*
4249 			 * Since a decision has already been made to deliver the
4250 			 * packet, there is no need to test for SECATTR and
4251 			 * ZONEONLY.
4252 			 * When a multicast packet is transmitted
4253 			 * a cache entry is created for the multicast address.
4254 			 * When delivering a copy of the packet or when new
4255 			 * packets are received we do not want to match on the
4256 			 * cached entry so explicitly match on
4257 			 * IRE_LOCAL and IRE_LOOPBACK
4258 			 */
4259 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4260 			    IRE_LOCAL | IRE_LOOPBACK,
4261 			    ipif, zoneid, NULL,
4262 			    MATCH_IRE_TYPE | MATCH_IRE_ILL, ipst);
4263 			if (ire == NULL) {
4264 				/*
4265 				 * packet must have come on a different
4266 				 * interface.
4267 				 * Since a decision has already been made to
4268 				 * deliver the packet, there is no need to test
4269 				 * for SECATTR and ZONEONLY.
4270 				 * Only match on local and broadcast ire's.
4271 				 * See detailed comment above.
4272 				 */
4273 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4274 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4275 				    NULL, MATCH_IRE_TYPE, ipst);
4276 			}
4277 
4278 			if (ire == NULL) {
4279 				/*
4280 				 * This is either a multicast packet or
4281 				 * the address has been removed since
4282 				 * the packet was received.
4283 				 * Return INADDR_ANY so that normal source
4284 				 * selection occurs for the response.
4285 				 */
4286 
4287 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4288 			} else {
4289 				pinfo->ip_pkt_match_addr.s_addr =
4290 				    ire->ire_src_addr;
4291 				ire_refrele(ire);
4292 			}
4293 			ipif_refrele(ipif);
4294 		} else {
4295 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4296 		}
4297 	}
4298 
4299 	if (ipmp_ill_held)
4300 		ill_refrele(ill);
4301 
4302 	mp->b_datap->db_type = M_CTL;
4303 	mp->b_wptr += sizeof (ip_pktinfo_t);
4304 	mp->b_cont = data_mp;
4305 
4306 	return (mp);
4307 }
4308 
4309 /*
4310  * Used to determine the most accurate cred_t to use for TX.
4311  * First priority is SCM_UCRED having set the label in the message,
4312  * which is used for MLP on UDP. Second priority is the open credentials
4313  * with the peer's label (aka conn_effective_cred), which is needed for
4314  * MLP on TCP/SCTP and for MAC-Exempt. Last priority is the open credentials.
4315  */
4316 cred_t *
4317 ip_best_cred(mblk_t *mp, conn_t *connp, pid_t *pidp)
4318 {
4319 	cred_t *cr;
4320 
4321 	cr = msg_getcred(mp, pidp);
4322 	if (cr != NULL && crgetlabel(cr) != NULL)
4323 		return (cr);
4324 	*pidp = NOPID;
4325 	return (CONN_CRED(connp));
4326 }
4327 
4328 /*
4329  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4330  * part of the bind request.
4331  */
4332 
4333 boolean_t
4334 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4335 {
4336 	ipsec_in_t *ii;
4337 
4338 	ASSERT(policy_mp != NULL);
4339 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4340 
4341 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4342 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4343 
4344 	connp->conn_policy = ii->ipsec_in_policy;
4345 	ii->ipsec_in_policy = NULL;
4346 
4347 	if (ii->ipsec_in_action != NULL) {
4348 		if (connp->conn_latch == NULL) {
4349 			connp->conn_latch = iplatch_create();
4350 			if (connp->conn_latch == NULL)
4351 				return (B_FALSE);
4352 		}
4353 		ipsec_latch_inbound(connp->conn_latch, ii);
4354 	}
4355 	return (B_TRUE);
4356 }
4357 
4358 static void
4359 ip_bind_post_handling(conn_t *connp, mblk_t *mp, boolean_t ire_requested)
4360 {
4361 	/*
4362 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4363 	 * We can't do this in ip_bind_get_ire because the policy
4364 	 * may not have been inherited at that point in time and hence
4365 	 * conn_out_enforce_policy may not be set.
4366 	 */
4367 	if (ire_requested && connp->conn_out_enforce_policy &&
4368 	    mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE) {
4369 		ire_t *ire = (ire_t *)mp->b_rptr;
4370 		ASSERT(MBLKL(mp) >= sizeof (ire_t));
4371 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4372 	}
4373 }
4374 
4375 /*
4376  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4377  * and to arrange for power-fanout assist.  The ULP is identified by
4378  * adding a single byte at the end of the original bind message.
4379  * A ULP other than UDP or TCP that wishes to be recognized passes
4380  * down a bind with a zero length address.
4381  *
4382  * The binding works as follows:
4383  * - A zero byte address means just bind to the protocol.
4384  * - A four byte address is treated as a request to validate
4385  *   that the address is a valid local address, appropriate for
4386  *   an application to bind to. This does not affect any fanout
4387  *   information in IP.
4388  * - A sizeof sin_t byte address is used to bind to only the local address
4389  *   and port.
4390  * - A sizeof ipa_conn_t byte address contains complete fanout information
4391  *   consisting of local and remote addresses and ports.  In
4392  *   this case, the addresses are both validated as appropriate
4393  *   for this operation, and, if so, the information is retained
4394  *   for use in the inbound fanout.
4395  *
4396  * The ULP (except in the zero-length bind) can append an
4397  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4398  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4399  * a copy of the source or destination IRE (source for local bind;
4400  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4401  * policy information contained should be copied on to the conn.
4402  *
4403  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4404  */
4405 mblk_t *
4406 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4407 {
4408 	ssize_t		len;
4409 	struct T_bind_req	*tbr;
4410 	sin_t		*sin;
4411 	ipa_conn_t	*ac;
4412 	uchar_t		*ucp;
4413 	mblk_t		*mp1;
4414 	boolean_t	ire_requested;
4415 	int		error = 0;
4416 	int		protocol;
4417 	ipa_conn_x_t	*acx;
4418 	cred_t		*cr;
4419 
4420 	/*
4421 	 * All Solaris components should pass a db_credp
4422 	 * for this TPI message, hence we ASSERT.
4423 	 * But in case there is some other M_PROTO that looks
4424 	 * like a TPI message sent by some other kernel
4425 	 * component, we check and return an error.
4426 	 */
4427 	cr = msg_getcred(mp, NULL);
4428 	ASSERT(cr != NULL);
4429 	if (cr == NULL) {
4430 		error = EINVAL;
4431 		goto bad_addr;
4432 	}
4433 
4434 	ASSERT(!connp->conn_af_isv6);
4435 	connp->conn_pkt_isv6 = B_FALSE;
4436 
4437 	len = MBLKL(mp);
4438 	if (len < (sizeof (*tbr) + 1)) {
4439 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4440 		    "ip_bind: bogus msg, len %ld", len);
4441 		/* XXX: Need to return something better */
4442 		goto bad_addr;
4443 	}
4444 	/* Back up and extract the protocol identifier. */
4445 	mp->b_wptr--;
4446 	protocol = *mp->b_wptr & 0xFF;
4447 	tbr = (struct T_bind_req *)mp->b_rptr;
4448 	/* Reset the message type in preparation for shipping it back. */
4449 	DB_TYPE(mp) = M_PCPROTO;
4450 
4451 	connp->conn_ulp = (uint8_t)protocol;
4452 
4453 	/*
4454 	 * Check for a zero length address.  This is from a protocol that
4455 	 * wants to register to receive all packets of its type.
4456 	 */
4457 	if (tbr->ADDR_length == 0) {
4458 		/*
4459 		 * These protocols are now intercepted in ip_bind_v6().
4460 		 * Reject protocol-level binds here for now.
4461 		 *
4462 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4463 		 * so that the protocol type cannot be SCTP.
4464 		 */
4465 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4466 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4467 			goto bad_addr;
4468 		}
4469 
4470 		/*
4471 		 *
4472 		 * The udp module never sends down a zero-length address,
4473 		 * and allowing this on a labeled system will break MLP
4474 		 * functionality.
4475 		 */
4476 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4477 			goto bad_addr;
4478 
4479 		if (connp->conn_mac_exempt)
4480 			goto bad_addr;
4481 
4482 		/* No hash here really.  The table is big enough. */
4483 		connp->conn_srcv6 = ipv6_all_zeros;
4484 
4485 		ipcl_proto_insert(connp, protocol);
4486 
4487 		tbr->PRIM_type = T_BIND_ACK;
4488 		return (mp);
4489 	}
4490 
4491 	/* Extract the address pointer from the message. */
4492 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4493 	    tbr->ADDR_length);
4494 	if (ucp == NULL) {
4495 		ip1dbg(("ip_bind: no address\n"));
4496 		goto bad_addr;
4497 	}
4498 	if (!OK_32PTR(ucp)) {
4499 		ip1dbg(("ip_bind: unaligned address\n"));
4500 		goto bad_addr;
4501 	}
4502 	/*
4503 	 * Check for trailing mps.
4504 	 */
4505 
4506 	mp1 = mp->b_cont;
4507 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4508 
4509 	switch (tbr->ADDR_length) {
4510 	default:
4511 		ip1dbg(("ip_bind: bad address length %d\n",
4512 		    (int)tbr->ADDR_length));
4513 		goto bad_addr;
4514 
4515 	case IP_ADDR_LEN:
4516 		/* Verification of local address only */
4517 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4518 		    *(ipaddr_t *)ucp, 0, B_FALSE);
4519 		break;
4520 
4521 	case sizeof (sin_t):
4522 		sin = (sin_t *)ucp;
4523 		error = ip_bind_laddr_v4(connp, &mp1, protocol,
4524 		    sin->sin_addr.s_addr, sin->sin_port, B_TRUE);
4525 		break;
4526 
4527 	case sizeof (ipa_conn_t):
4528 		ac = (ipa_conn_t *)ucp;
4529 		/* For raw socket, the local port is not set. */
4530 		if (ac->ac_lport == 0)
4531 			ac->ac_lport = connp->conn_lport;
4532 		/* Always verify destination reachability. */
4533 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4534 		    &ac->ac_laddr, ac->ac_lport, ac->ac_faddr, ac->ac_fport,
4535 		    B_TRUE, B_TRUE, cr);
4536 		break;
4537 
4538 	case sizeof (ipa_conn_x_t):
4539 		acx = (ipa_conn_x_t *)ucp;
4540 		/*
4541 		 * Whether or not to verify destination reachability depends
4542 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4543 		 */
4544 		error = ip_bind_connected_v4(connp, &mp1, protocol,
4545 		    &acx->acx_conn.ac_laddr, acx->acx_conn.ac_lport,
4546 		    acx->acx_conn.ac_faddr, acx->acx_conn.ac_fport,
4547 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0, cr);
4548 		break;
4549 	}
4550 	ASSERT(error != EINPROGRESS);
4551 	if (error != 0)
4552 		goto bad_addr;
4553 
4554 	ip_bind_post_handling(connp, mp->b_cont, ire_requested);
4555 
4556 	/* Send it home. */
4557 	mp->b_datap->db_type = M_PCPROTO;
4558 	tbr->PRIM_type = T_BIND_ACK;
4559 	return (mp);
4560 
4561 bad_addr:
4562 	/*
4563 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4564 	 * a unix errno.
4565 	 */
4566 	if (error > 0)
4567 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4568 	else
4569 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4570 	return (mp);
4571 }
4572 
4573 /*
4574  * Here address is verified to be a valid local address.
4575  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4576  * address is also considered a valid local address.
4577  * In the case of a broadcast/multicast address, however, the
4578  * upper protocol is expected to reset the src address
4579  * to 0 if it sees a IRE_BROADCAST type returned so that
4580  * no packets are emitted with broadcast/multicast address as
4581  * source address (that violates hosts requirements RFC 1122)
4582  * The addresses valid for bind are:
4583  *	(1) - INADDR_ANY (0)
4584  *	(2) - IP address of an UP interface
4585  *	(3) - IP address of a DOWN interface
4586  *	(4) - valid local IP broadcast addresses. In this case
4587  *	the conn will only receive packets destined to
4588  *	the specified broadcast address.
4589  *	(5) - a multicast address. In this case
4590  *	the conn will only receive packets destined to
4591  *	the specified multicast address. Note: the
4592  *	application still has to issue an
4593  *	IP_ADD_MEMBERSHIP socket option.
4594  *
4595  * On error, return -1 for TBADADDR otherwise pass the
4596  * errno with TSYSERR reply.
4597  *
4598  * In all the above cases, the bound address must be valid in the current zone.
4599  * When the address is loopback, multicast or broadcast, there might be many
4600  * matching IREs so bind has to look up based on the zone.
4601  *
4602  * Note: lport is in network byte order.
4603  *
4604  */
4605 int
4606 ip_bind_laddr_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4607     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4608 {
4609 	int		error = 0;
4610 	ire_t		*src_ire;
4611 	zoneid_t	zoneid;
4612 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4613 	mblk_t		*mp = NULL;
4614 	boolean_t	ire_requested = B_FALSE;
4615 	boolean_t	ipsec_policy_set = B_FALSE;
4616 
4617 	if (mpp)
4618 		mp = *mpp;
4619 
4620 	if (mp != NULL) {
4621 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4622 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4623 	}
4624 
4625 	/*
4626 	 * If it was previously connected, conn_fully_bound would have
4627 	 * been set.
4628 	 */
4629 	connp->conn_fully_bound = B_FALSE;
4630 
4631 	src_ire = NULL;
4632 
4633 	zoneid = IPCL_ZONEID(connp);
4634 
4635 	if (src_addr) {
4636 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4637 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4638 		/*
4639 		 * If an address other than 0.0.0.0 is requested,
4640 		 * we verify that it is a valid address for bind
4641 		 * Note: Following code is in if-else-if form for
4642 		 * readability compared to a condition check.
4643 		 */
4644 		/* LINTED - statement has no consequence */
4645 		if (IRE_IS_LOCAL(src_ire)) {
4646 			/*
4647 			 * (2) Bind to address of local UP interface
4648 			 */
4649 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4650 			/*
4651 			 * (4) Bind to broadcast address
4652 			 * Note: permitted only from transports that
4653 			 * request IRE
4654 			 */
4655 			if (!ire_requested)
4656 				error = EADDRNOTAVAIL;
4657 		} else {
4658 			/*
4659 			 * (3) Bind to address of local DOWN interface
4660 			 * (ipif_lookup_addr() looks up all interfaces
4661 			 * but we do not get here for UP interfaces
4662 			 * - case (2) above)
4663 			 */
4664 			/* LINTED - statement has no consequent */
4665 			if (ip_addr_exists(src_addr, zoneid, ipst)) {
4666 				/* The address exists */
4667 			} else if (CLASSD(src_addr)) {
4668 				error = 0;
4669 				if (src_ire != NULL)
4670 					ire_refrele(src_ire);
4671 				/*
4672 				 * (5) bind to multicast address.
4673 				 * Fake out the IRE returned to upper
4674 				 * layer to be a broadcast IRE.
4675 				 */
4676 				src_ire = ire_ctable_lookup(
4677 				    INADDR_BROADCAST, INADDR_ANY,
4678 				    IRE_BROADCAST, NULL, zoneid, NULL,
4679 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4680 				    ipst);
4681 				if (src_ire == NULL || !ire_requested)
4682 					error = EADDRNOTAVAIL;
4683 			} else {
4684 				/*
4685 				 * Not a valid address for bind
4686 				 */
4687 				error = EADDRNOTAVAIL;
4688 			}
4689 		}
4690 		if (error) {
4691 			/* Red Alert!  Attempting to be a bogon! */
4692 			ip1dbg(("ip_bind_laddr_v4: bad src address 0x%x\n",
4693 			    ntohl(src_addr)));
4694 			goto bad_addr;
4695 		}
4696 	}
4697 
4698 	/*
4699 	 * Allow setting new policies. For example, disconnects come
4700 	 * down as ipa_t bind. As we would have set conn_policy_cached
4701 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4702 	 * can change after the disconnect.
4703 	 */
4704 	connp->conn_policy_cached = B_FALSE;
4705 
4706 	/*
4707 	 * If not fanout_insert this was just an address verification
4708 	 */
4709 	if (fanout_insert) {
4710 		/*
4711 		 * The addresses have been verified. Time to insert in
4712 		 * the correct fanout list.
4713 		 */
4714 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4715 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4716 		connp->conn_lport = lport;
4717 		connp->conn_fport = 0;
4718 		/*
4719 		 * Do we need to add a check to reject Multicast packets
4720 		 */
4721 		error = ipcl_bind_insert(connp, protocol, src_addr, lport);
4722 	}
4723 
4724 	if (error == 0) {
4725 		if (ire_requested) {
4726 			if (!ip_bind_get_ire_v4(mpp, src_ire, NULL, ipst)) {
4727 				error = -1;
4728 				/* Falls through to bad_addr */
4729 			}
4730 		} else if (ipsec_policy_set) {
4731 			if (!ip_bind_ipsec_policy_set(connp, mp)) {
4732 				error = -1;
4733 				/* Falls through to bad_addr */
4734 			}
4735 		}
4736 	}
4737 bad_addr:
4738 	if (error != 0) {
4739 		if (connp->conn_anon_port) {
4740 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4741 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4742 			    B_FALSE);
4743 		}
4744 		connp->conn_mlp_type = mlptSingle;
4745 	}
4746 	if (src_ire != NULL)
4747 		IRE_REFRELE(src_ire);
4748 	return (error);
4749 }
4750 
4751 int
4752 ip_proto_bind_laddr_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
4753     ipaddr_t src_addr, uint16_t lport, boolean_t fanout_insert)
4754 {
4755 	int error;
4756 	mblk_t	*mp = NULL;
4757 	boolean_t ire_requested;
4758 
4759 	if (ire_mpp)
4760 		mp = *ire_mpp;
4761 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4762 
4763 	ASSERT(!connp->conn_af_isv6);
4764 	connp->conn_pkt_isv6 = B_FALSE;
4765 	connp->conn_ulp = protocol;
4766 
4767 	error = ip_bind_laddr_v4(connp, ire_mpp, protocol, src_addr, lport,
4768 	    fanout_insert);
4769 	if (error == 0) {
4770 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
4771 		    ire_requested);
4772 	} else if (error < 0) {
4773 		error = -TBADADDR;
4774 	}
4775 	return (error);
4776 }
4777 
4778 /*
4779  * Verify that both the source and destination addresses
4780  * are valid.  If verify_dst is false, then the destination address may be
4781  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4782  * destination reachability, while tunnels do not.
4783  * Note that we allow connect to broadcast and multicast
4784  * addresses when ire_requested is set. Thus the ULP
4785  * has to check for IRE_BROADCAST and multicast.
4786  *
4787  * Returns zero if ok.
4788  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4789  * (for use with TSYSERR reply).
4790  *
4791  * Note: lport and fport are in network byte order.
4792  */
4793 int
4794 ip_bind_connected_v4(conn_t *connp, mblk_t **mpp, uint8_t protocol,
4795     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4796     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
4797 {
4798 
4799 	ire_t		*src_ire;
4800 	ire_t		*dst_ire;
4801 	int		error = 0;
4802 	ire_t		*sire = NULL;
4803 	ire_t		*md_dst_ire = NULL;
4804 	ire_t		*lso_dst_ire = NULL;
4805 	ill_t		*ill = NULL;
4806 	zoneid_t	zoneid;
4807 	ipaddr_t	src_addr = *src_addrp;
4808 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4809 	mblk_t		*mp = NULL;
4810 	boolean_t	ire_requested = B_FALSE;
4811 	boolean_t	ipsec_policy_set = B_FALSE;
4812 	ts_label_t	*tsl = NULL;
4813 	cred_t		*effective_cred = NULL;
4814 
4815 	if (mpp)
4816 		mp = *mpp;
4817 
4818 	if (mp != NULL) {
4819 		ire_requested = (DB_TYPE(mp) == IRE_DB_REQ_TYPE);
4820 		ipsec_policy_set = (DB_TYPE(mp) == IPSEC_POLICY_SET);
4821 	}
4822 
4823 	src_ire = dst_ire = NULL;
4824 
4825 	/*
4826 	 * If we never got a disconnect before, clear it now.
4827 	 */
4828 	connp->conn_fully_bound = B_FALSE;
4829 
4830 	zoneid = IPCL_ZONEID(connp);
4831 
4832 	/*
4833 	 * Check whether Trusted Solaris policy allows communication with this
4834 	 * host, and pretend that the destination is unreachable if not.
4835 	 *
4836 	 * This is never a problem for TCP, since that transport is known to
4837 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4838 	 * handling.  If the remote is unreachable, it will be detected at that
4839 	 * point, so there's no reason to check it here.
4840 	 *
4841 	 * Note that for sendto (and other datagram-oriented friends), this
4842 	 * check is done as part of the data path label computation instead.
4843 	 * The check here is just to make non-TCP connect() report the right
4844 	 * error.
4845 	 */
4846 	if (is_system_labeled() && !IPCL_IS_TCP(connp)) {
4847 		if ((error = tsol_check_dest(cr, &dst_addr, IPV4_VERSION,
4848 		    connp->conn_mac_exempt, &effective_cred)) != 0) {
4849 			if (ip_debug > 2) {
4850 				pr_addr_dbg(
4851 				    "ip_bind_connected_v4:"
4852 				    " no label for dst %s\n",
4853 				    AF_INET, &dst_addr);
4854 			}
4855 			goto bad_addr;
4856 		}
4857 
4858 		/*
4859 		 * tsol_check_dest() may have created a new cred with
4860 		 * a modified security label. Use that cred if it exists
4861 		 * for ire lookups.
4862 		 */
4863 		if (effective_cred == NULL) {
4864 			tsl = crgetlabel(cr);
4865 		} else {
4866 			tsl = crgetlabel(effective_cred);
4867 		}
4868 	}
4869 
4870 	if (CLASSD(dst_addr)) {
4871 		/* Pick up an IRE_BROADCAST */
4872 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4873 		    NULL, zoneid, tsl,
4874 		    (MATCH_IRE_RECURSIVE |
4875 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4876 		    MATCH_IRE_SECATTR), ipst);
4877 	} else {
4878 		/*
4879 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4880 		 * and onlink ipif is not found set ENETUNREACH error.
4881 		 */
4882 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4883 			ipif_t *ipif;
4884 
4885 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4886 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4887 			if (ipif == NULL) {
4888 				error = ENETUNREACH;
4889 				goto bad_addr;
4890 			}
4891 			ipif_refrele(ipif);
4892 		}
4893 
4894 		if (connp->conn_nexthop_set) {
4895 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4896 			    0, 0, NULL, NULL, zoneid, tsl,
4897 			    MATCH_IRE_SECATTR, ipst);
4898 		} else {
4899 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4900 			    &sire, zoneid, tsl,
4901 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4902 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4903 			    MATCH_IRE_SECATTR), ipst);
4904 		}
4905 	}
4906 	/*
4907 	 * dst_ire can't be a broadcast when not ire_requested.
4908 	 * We also prevent ire's with src address INADDR_ANY to
4909 	 * be used, which are created temporarily for
4910 	 * sending out packets from endpoints that have
4911 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4912 	 * reachable.  If verify_dst is false, the destination needn't be
4913 	 * reachable.
4914 	 *
4915 	 * If we match on a reject or black hole, then we've got a
4916 	 * local failure.  May as well fail out the connect() attempt,
4917 	 * since it's never going to succeed.
4918 	 */
4919 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4920 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4921 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4922 		/*
4923 		 * If we're verifying destination reachability, we always want
4924 		 * to complain here.
4925 		 *
4926 		 * If we're not verifying destination reachability but the
4927 		 * destination has a route, we still want to fail on the
4928 		 * temporary address and broadcast address tests.
4929 		 */
4930 		if (verify_dst || (dst_ire != NULL)) {
4931 			if (ip_debug > 2) {
4932 				pr_addr_dbg("ip_bind_connected_v4:"
4933 				    "bad connected dst %s\n",
4934 				    AF_INET, &dst_addr);
4935 			}
4936 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4937 				error = ENETUNREACH;
4938 			else
4939 				error = EHOSTUNREACH;
4940 			goto bad_addr;
4941 		}
4942 	}
4943 
4944 	/*
4945 	 * If the app does a connect(), it means that it will most likely
4946 	 * send more than 1 packet to the destination.  It makes sense
4947 	 * to clear the temporary flag.
4948 	 */
4949 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4950 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4951 		irb_t *irb = dst_ire->ire_bucket;
4952 
4953 		rw_enter(&irb->irb_lock, RW_WRITER);
4954 		/*
4955 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4956 		 * the lock to guarantee irb_tmp_ire_cnt.
4957 		 */
4958 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4959 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4960 			irb->irb_tmp_ire_cnt--;
4961 		}
4962 		rw_exit(&irb->irb_lock);
4963 	}
4964 
4965 	/*
4966 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4967 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4968 	 * eligibility tests for passive connects are handled separately
4969 	 * through tcp_adapt_ire().  We do this before the source address
4970 	 * selection, because dst_ire may change after a call to
4971 	 * ipif_select_source().  This is a best-effort check, as the
4972 	 * packet for this connection may not actually go through
4973 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4974 	 * calling ip_newroute().  This is why we further check on the
4975 	 * IRE during LSO/Multidata packet transmission in
4976 	 * tcp_lsosend()/tcp_multisend().
4977 	 */
4978 	if (!ipsec_policy_set && dst_ire != NULL &&
4979 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4980 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4981 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4982 			lso_dst_ire = dst_ire;
4983 			IRE_REFHOLD(lso_dst_ire);
4984 		} else if (ipst->ips_ip_multidata_outbound &&
4985 		    ILL_MDT_CAPABLE(ill)) {
4986 			md_dst_ire = dst_ire;
4987 			IRE_REFHOLD(md_dst_ire);
4988 		}
4989 	}
4990 
4991 	if (dst_ire != NULL && dst_ire->ire_type == IRE_LOCAL &&
4992 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4993 		/*
4994 		 * If the IRE belongs to a different zone, look for a matching
4995 		 * route in the forwarding table and use the source address from
4996 		 * that route.
4997 		 */
4998 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4999 		    zoneid, 0, NULL,
5000 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
5001 		    MATCH_IRE_RJ_BHOLE, ipst);
5002 		if (src_ire == NULL) {
5003 			error = EHOSTUNREACH;
5004 			goto bad_addr;
5005 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
5006 			if (!(src_ire->ire_type & IRE_HOST))
5007 				error = ENETUNREACH;
5008 			else
5009 				error = EHOSTUNREACH;
5010 			goto bad_addr;
5011 		}
5012 		if (src_addr == INADDR_ANY)
5013 			src_addr = src_ire->ire_src_addr;
5014 		ire_refrele(src_ire);
5015 		src_ire = NULL;
5016 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
5017 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
5018 			src_addr = sire->ire_src_addr;
5019 			ire_refrele(dst_ire);
5020 			dst_ire = sire;
5021 			sire = NULL;
5022 		} else {
5023 			/*
5024 			 * Pick a source address so that a proper inbound
5025 			 * load spreading would happen.
5026 			 */
5027 			ill_t *ire_ill = dst_ire->ire_ipif->ipif_ill;
5028 			ipif_t *src_ipif = NULL;
5029 			ire_t *ipif_ire;
5030 
5031 			/*
5032 			 * Supply a local source address such that inbound
5033 			 * load spreading happens.
5034 			 *
5035 			 * Determine the best source address on this ill for
5036 			 * the destination.
5037 			 *
5038 			 * 1) For broadcast, we should return a broadcast ire
5039 			 *    found above so that upper layers know that the
5040 			 *    destination address is a broadcast address.
5041 			 *
5042 			 * 2) If the ipif is DEPRECATED, select a better
5043 			 *    source address.  Similarly, if the ipif is on
5044 			 *    the IPMP meta-interface, pick a source address
5045 			 *    at random to improve inbound load spreading.
5046 			 *
5047 			 * 3) If the outgoing interface is part of a usesrc
5048 			 *    group, then try selecting a source address from
5049 			 *    the usesrc ILL.
5050 			 */
5051 			if ((dst_ire->ire_zoneid != zoneid &&
5052 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5053 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
5054 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5055 			    (IS_IPMP(ire_ill) ||
5056 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5057 			    (ire_ill->ill_usesrc_ifindex != 0)))) {
5058 				/*
5059 				 * If the destination is reachable via a
5060 				 * given gateway, the selected source address
5061 				 * should be in the same subnet as the gateway.
5062 				 * Otherwise, the destination is not reachable.
5063 				 *
5064 				 * If there are no interfaces on the same subnet
5065 				 * as the destination, ipif_select_source gives
5066 				 * first non-deprecated interface which might be
5067 				 * on a different subnet than the gateway.
5068 				 * This is not desirable. Hence pass the dst_ire
5069 				 * source address to ipif_select_source.
5070 				 * It is sure that the destination is reachable
5071 				 * with the dst_ire source address subnet.
5072 				 * So passing dst_ire source address to
5073 				 * ipif_select_source will make sure that the
5074 				 * selected source will be on the same subnet
5075 				 * as dst_ire source address.
5076 				 */
5077 				ipaddr_t saddr =
5078 				    dst_ire->ire_ipif->ipif_src_addr;
5079 				src_ipif = ipif_select_source(ire_ill,
5080 				    saddr, zoneid);
5081 				if (src_ipif != NULL) {
5082 					if (IS_VNI(src_ipif->ipif_ill)) {
5083 						/*
5084 						 * For VNI there is no
5085 						 * interface route
5086 						 */
5087 						src_addr =
5088 						    src_ipif->ipif_src_addr;
5089 					} else {
5090 						ipif_ire =
5091 						    ipif_to_ire(src_ipif);
5092 						if (ipif_ire != NULL) {
5093 							IRE_REFRELE(dst_ire);
5094 							dst_ire = ipif_ire;
5095 						}
5096 						src_addr =
5097 						    dst_ire->ire_src_addr;
5098 					}
5099 					ipif_refrele(src_ipif);
5100 				} else {
5101 					src_addr = dst_ire->ire_src_addr;
5102 				}
5103 			} else {
5104 				src_addr = dst_ire->ire_src_addr;
5105 			}
5106 		}
5107 	}
5108 
5109 	/*
5110 	 * We do ire_route_lookup() here (and not
5111 	 * interface lookup as we assert that
5112 	 * src_addr should only come from an
5113 	 * UP interface for hard binding.
5114 	 */
5115 	ASSERT(src_ire == NULL);
5116 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5117 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5118 	/* src_ire must be a local|loopback */
5119 	if (!IRE_IS_LOCAL(src_ire)) {
5120 		if (ip_debug > 2) {
5121 			pr_addr_dbg("ip_bind_connected_v4: bad connected "
5122 			    "src %s\n", AF_INET, &src_addr);
5123 		}
5124 		error = EADDRNOTAVAIL;
5125 		goto bad_addr;
5126 	}
5127 
5128 	/*
5129 	 * If the source address is a loopback address, the
5130 	 * destination had best be local or multicast.
5131 	 * The transports that can't handle multicast will reject
5132 	 * those addresses.
5133 	 */
5134 	if (src_ire->ire_type == IRE_LOOPBACK &&
5135 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5136 		ip1dbg(("ip_bind_connected_v4: bad connected loopback\n"));
5137 		error = -1;
5138 		goto bad_addr;
5139 	}
5140 
5141 	/*
5142 	 * Allow setting new policies. For example, disconnects come
5143 	 * down as ipa_t bind. As we would have set conn_policy_cached
5144 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5145 	 * can change after the disconnect.
5146 	 */
5147 	connp->conn_policy_cached = B_FALSE;
5148 
5149 	/*
5150 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5151 	 * can handle their passed-in conn's.
5152 	 */
5153 
5154 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5155 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5156 	connp->conn_lport = lport;
5157 	connp->conn_fport = fport;
5158 	*src_addrp = src_addr;
5159 
5160 	ASSERT(!(ipsec_policy_set && ire_requested));
5161 	if (ire_requested) {
5162 		iulp_t *ulp_info = NULL;
5163 
5164 		/*
5165 		 * Note that sire will not be NULL if this is an off-link
5166 		 * connection and there is not cache for that dest yet.
5167 		 *
5168 		 * XXX Because of an existing bug, if there are multiple
5169 		 * default routes, the IRE returned now may not be the actual
5170 		 * default route used (default routes are chosen in a
5171 		 * round robin fashion).  So if the metrics for different
5172 		 * default routes are different, we may return the wrong
5173 		 * metrics.  This will not be a problem if the existing
5174 		 * bug is fixed.
5175 		 */
5176 		if (sire != NULL) {
5177 			ulp_info = &(sire->ire_uinfo);
5178 		}
5179 		if (!ip_bind_get_ire_v4(mpp, dst_ire, ulp_info, ipst)) {
5180 			error = -1;
5181 			goto bad_addr;
5182 		}
5183 		mp = *mpp;
5184 	} else if (ipsec_policy_set) {
5185 		if (!ip_bind_ipsec_policy_set(connp, mp)) {
5186 			error = -1;
5187 			goto bad_addr;
5188 		}
5189 	}
5190 
5191 	/*
5192 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5193 	 * we'll cache that.  If we don't, we'll inherit global policy.
5194 	 *
5195 	 * We can't insert until the conn reflects the policy. Note that
5196 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5197 	 * connections where we don't have a policy. This is to prevent
5198 	 * global policy lookups in the inbound path.
5199 	 *
5200 	 * If we insert before we set conn_policy_cached,
5201 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5202 	 * because global policy cound be non-empty. We normally call
5203 	 * ipsec_check_policy() for conn_policy_cached connections only if
5204 	 * ipc_in_enforce_policy is set. But in this case,
5205 	 * conn_policy_cached can get set anytime since we made the
5206 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5207 	 * called, which will make the above assumption false.  Thus, we
5208 	 * need to insert after we set conn_policy_cached.
5209 	 */
5210 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5211 		goto bad_addr;
5212 
5213 	if (fanout_insert) {
5214 		/*
5215 		 * The addresses have been verified. Time to insert in
5216 		 * the correct fanout list.
5217 		 */
5218 		error = ipcl_conn_insert(connp, protocol, src_addr,
5219 		    dst_addr, connp->conn_ports);
5220 	}
5221 
5222 	if (error == 0) {
5223 		connp->conn_fully_bound = B_TRUE;
5224 		/*
5225 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5226 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5227 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5228 		 * ip_xxinfo_return(), which performs further checks
5229 		 * against them and upon success, returns the LSO/MDT info
5230 		 * mblk which we will attach to the bind acknowledgment.
5231 		 */
5232 		if (lso_dst_ire != NULL) {
5233 			mblk_t *lsoinfo_mp;
5234 
5235 			ASSERT(ill->ill_lso_capab != NULL);
5236 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5237 			    ill->ill_name, ill->ill_lso_capab)) != NULL) {
5238 				if (mp == NULL) {
5239 					*mpp = lsoinfo_mp;
5240 				} else {
5241 					linkb(mp, lsoinfo_mp);
5242 				}
5243 			}
5244 		} else if (md_dst_ire != NULL) {
5245 			mblk_t *mdinfo_mp;
5246 
5247 			ASSERT(ill->ill_mdt_capab != NULL);
5248 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5249 			    ill->ill_name, ill->ill_mdt_capab)) != NULL) {
5250 				if (mp == NULL) {
5251 					*mpp = mdinfo_mp;
5252 				} else {
5253 					linkb(mp, mdinfo_mp);
5254 				}
5255 			}
5256 		}
5257 	}
5258 bad_addr:
5259 	if (ipsec_policy_set) {
5260 		ASSERT(mp != NULL);
5261 		freeb(mp);
5262 		/*
5263 		 * As of now assume that nothing else accompanies
5264 		 * IPSEC_POLICY_SET.
5265 		 */
5266 		*mpp = NULL;
5267 	}
5268 	if (src_ire != NULL)
5269 		IRE_REFRELE(src_ire);
5270 	if (dst_ire != NULL)
5271 		IRE_REFRELE(dst_ire);
5272 	if (sire != NULL)
5273 		IRE_REFRELE(sire);
5274 	if (md_dst_ire != NULL)
5275 		IRE_REFRELE(md_dst_ire);
5276 	if (lso_dst_ire != NULL)
5277 		IRE_REFRELE(lso_dst_ire);
5278 	if (effective_cred != NULL)
5279 		crfree(effective_cred);
5280 	return (error);
5281 }
5282 
5283 int
5284 ip_proto_bind_connected_v4(conn_t *connp, mblk_t **ire_mpp, uint8_t protocol,
5285     ipaddr_t *src_addrp, uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
5286     boolean_t fanout_insert, boolean_t verify_dst, cred_t *cr)
5287 {
5288 	int error;
5289 	mblk_t	*mp = NULL;
5290 	boolean_t ire_requested;
5291 
5292 	if (ire_mpp)
5293 		mp = *ire_mpp;
5294 	ire_requested = (mp != NULL && DB_TYPE(mp) == IRE_DB_REQ_TYPE);
5295 
5296 	ASSERT(!connp->conn_af_isv6);
5297 	connp->conn_pkt_isv6 = B_FALSE;
5298 	connp->conn_ulp = protocol;
5299 
5300 	/* For raw socket, the local port is not set. */
5301 	if (lport == 0)
5302 		lport = connp->conn_lport;
5303 	error = ip_bind_connected_v4(connp, ire_mpp, protocol,
5304 	    src_addrp, lport, dst_addr, fport, fanout_insert, verify_dst, cr);
5305 	if (error == 0) {
5306 		ip_bind_post_handling(connp, ire_mpp ? *ire_mpp : NULL,
5307 		    ire_requested);
5308 	} else if (error < 0) {
5309 		error = -TBADADDR;
5310 	}
5311 	return (error);
5312 }
5313 
5314 /*
5315  * Get the ire in *mpp. Returns false if it fails (due to lack of space).
5316  * Prefers dst_ire over src_ire.
5317  */
5318 static boolean_t
5319 ip_bind_get_ire_v4(mblk_t **mpp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5320 {
5321 	mblk_t	*mp = *mpp;
5322 	ire_t	*ret_ire;
5323 
5324 	ASSERT(mp != NULL);
5325 
5326 	if (ire != NULL) {
5327 		/*
5328 		 * mp initialized above to IRE_DB_REQ_TYPE
5329 		 * appended mblk. Its <upper protocol>'s
5330 		 * job to make sure there is room.
5331 		 */
5332 		if ((mp->b_datap->db_lim - mp->b_rptr) < sizeof (ire_t))
5333 			return (B_FALSE);
5334 
5335 		mp->b_datap->db_type = IRE_DB_TYPE;
5336 		mp->b_wptr = mp->b_rptr + sizeof (ire_t);
5337 		bcopy(ire, mp->b_rptr, sizeof (ire_t));
5338 		ret_ire = (ire_t *)mp->b_rptr;
5339 		/*
5340 		 * Pass the latest setting of the ip_path_mtu_discovery and
5341 		 * copy the ulp info if any.
5342 		 */
5343 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5344 		    IPH_DF : 0;
5345 		if (ulp_info != NULL) {
5346 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5347 			    sizeof (iulp_t));
5348 		}
5349 		ret_ire->ire_mp = mp;
5350 	} else {
5351 		/*
5352 		 * No IRE was found. Remove IRE mblk.
5353 		 */
5354 		*mpp = mp->b_cont;
5355 		freeb(mp);
5356 	}
5357 	return (B_TRUE);
5358 }
5359 
5360 /*
5361  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5362  * the final piece where we don't.  Return a pointer to the first mblk in the
5363  * result, and update the pointer to the next mblk to chew on.  If anything
5364  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5365  * NULL pointer.
5366  */
5367 mblk_t *
5368 ip_carve_mp(mblk_t **mpp, ssize_t len)
5369 {
5370 	mblk_t	*mp0;
5371 	mblk_t	*mp1;
5372 	mblk_t	*mp2;
5373 
5374 	if (!len || !mpp || !(mp0 = *mpp))
5375 		return (NULL);
5376 	/* If we aren't going to consume the first mblk, we need a dup. */
5377 	if (mp0->b_wptr - mp0->b_rptr > len) {
5378 		mp1 = dupb(mp0);
5379 		if (mp1) {
5380 			/* Partition the data between the two mblks. */
5381 			mp1->b_wptr = mp1->b_rptr + len;
5382 			mp0->b_rptr = mp1->b_wptr;
5383 			/*
5384 			 * after adjustments if mblk not consumed is now
5385 			 * unaligned, try to align it. If this fails free
5386 			 * all messages and let upper layer recover.
5387 			 */
5388 			if (!OK_32PTR(mp0->b_rptr)) {
5389 				if (!pullupmsg(mp0, -1)) {
5390 					freemsg(mp0);
5391 					freemsg(mp1);
5392 					*mpp = NULL;
5393 					return (NULL);
5394 				}
5395 			}
5396 		}
5397 		return (mp1);
5398 	}
5399 	/* Eat through as many mblks as we need to get len bytes. */
5400 	len -= mp0->b_wptr - mp0->b_rptr;
5401 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5402 		if (mp2->b_wptr - mp2->b_rptr > len) {
5403 			/*
5404 			 * We won't consume the entire last mblk.  Like
5405 			 * above, dup and partition it.
5406 			 */
5407 			mp1->b_cont = dupb(mp2);
5408 			mp1 = mp1->b_cont;
5409 			if (!mp1) {
5410 				/*
5411 				 * Trouble.  Rather than go to a lot of
5412 				 * trouble to clean up, we free the messages.
5413 				 * This won't be any worse than losing it on
5414 				 * the wire.
5415 				 */
5416 				freemsg(mp0);
5417 				freemsg(mp2);
5418 				*mpp = NULL;
5419 				return (NULL);
5420 			}
5421 			mp1->b_wptr = mp1->b_rptr + len;
5422 			mp2->b_rptr = mp1->b_wptr;
5423 			/*
5424 			 * after adjustments if mblk not consumed is now
5425 			 * unaligned, try to align it. If this fails free
5426 			 * all messages and let upper layer recover.
5427 			 */
5428 			if (!OK_32PTR(mp2->b_rptr)) {
5429 				if (!pullupmsg(mp2, -1)) {
5430 					freemsg(mp0);
5431 					freemsg(mp2);
5432 					*mpp = NULL;
5433 					return (NULL);
5434 				}
5435 			}
5436 			*mpp = mp2;
5437 			return (mp0);
5438 		}
5439 		/* Decrement len by the amount we just got. */
5440 		len -= mp2->b_wptr - mp2->b_rptr;
5441 	}
5442 	/*
5443 	 * len should be reduced to zero now.  If not our caller has
5444 	 * screwed up.
5445 	 */
5446 	if (len) {
5447 		/* Shouldn't happen! */
5448 		freemsg(mp0);
5449 		*mpp = NULL;
5450 		return (NULL);
5451 	}
5452 	/*
5453 	 * We consumed up to exactly the end of an mblk.  Detach the part
5454 	 * we are returning from the rest of the chain.
5455 	 */
5456 	mp1->b_cont = NULL;
5457 	*mpp = mp2;
5458 	return (mp0);
5459 }
5460 
5461 /* The ill stream is being unplumbed. Called from ip_close */
5462 int
5463 ip_modclose(ill_t *ill)
5464 {
5465 	boolean_t success;
5466 	ipsq_t	*ipsq;
5467 	ipif_t	*ipif;
5468 	queue_t	*q = ill->ill_rq;
5469 	ip_stack_t	*ipst = ill->ill_ipst;
5470 	int	i;
5471 
5472 	/*
5473 	 * The punlink prior to this may have initiated a capability
5474 	 * negotiation. But ipsq_enter will block until that finishes or
5475 	 * times out.
5476 	 */
5477 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5478 
5479 	/*
5480 	 * Open/close/push/pop is guaranteed to be single threaded
5481 	 * per stream by STREAMS. FS guarantees that all references
5482 	 * from top are gone before close is called. So there can't
5483 	 * be another close thread that has set CONDEMNED on this ill.
5484 	 * and cause ipsq_enter to return failure.
5485 	 */
5486 	ASSERT(success);
5487 	ipsq = ill->ill_phyint->phyint_ipsq;
5488 
5489 	/*
5490 	 * Mark it condemned. No new reference will be made to this ill.
5491 	 * Lookup functions will return an error. Threads that try to
5492 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5493 	 * that the refcnt will drop down to zero.
5494 	 */
5495 	mutex_enter(&ill->ill_lock);
5496 	ill->ill_state_flags |= ILL_CONDEMNED;
5497 	for (ipif = ill->ill_ipif; ipif != NULL;
5498 	    ipif = ipif->ipif_next) {
5499 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5500 	}
5501 	/*
5502 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5503 	 * returns  error if ILL_CONDEMNED is set
5504 	 */
5505 	cv_broadcast(&ill->ill_cv);
5506 	mutex_exit(&ill->ill_lock);
5507 
5508 	/*
5509 	 * Send all the deferred DLPI messages downstream which came in
5510 	 * during the small window right before ipsq_enter(). We do this
5511 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5512 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5513 	 */
5514 	ill_dlpi_send_deferred(ill);
5515 
5516 	/*
5517 	 * Shut down fragmentation reassembly.
5518 	 * ill_frag_timer won't start a timer again.
5519 	 * Now cancel any existing timer
5520 	 */
5521 	(void) untimeout(ill->ill_frag_timer_id);
5522 	(void) ill_frag_timeout(ill, 0);
5523 
5524 	/*
5525 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5526 	 * this ill. Then wait for the refcnts to drop to zero.
5527 	 * ill_is_freeable checks whether the ill is really quiescent.
5528 	 * Then make sure that threads that are waiting to enter the
5529 	 * ipsq have seen the error returned by ipsq_enter and have
5530 	 * gone away. Then we call ill_delete_tail which does the
5531 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5532 	 */
5533 	ill_delete(ill);
5534 	mutex_enter(&ill->ill_lock);
5535 	while (!ill_is_freeable(ill))
5536 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5537 	while (ill->ill_waiters)
5538 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5539 
5540 	mutex_exit(&ill->ill_lock);
5541 
5542 	/*
5543 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5544 	 * it held until the end of the function since the cleanup
5545 	 * below needs to be able to use the ip_stack_t.
5546 	 */
5547 	netstack_hold(ipst->ips_netstack);
5548 
5549 	/* qprocsoff is done via ill_delete_tail */
5550 	ill_delete_tail(ill);
5551 	ASSERT(ill->ill_ipst == NULL);
5552 
5553 	/*
5554 	 * Walk through all upper (conn) streams and qenable
5555 	 * those that have queued data.
5556 	 * close synchronization needs this to
5557 	 * be done to ensure that all upper layers blocked
5558 	 * due to flow control to the closing device
5559 	 * get unblocked.
5560 	 */
5561 	ip1dbg(("ip_wsrv: walking\n"));
5562 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
5563 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
5564 	}
5565 
5566 	mutex_enter(&ipst->ips_ip_mi_lock);
5567 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5568 	mutex_exit(&ipst->ips_ip_mi_lock);
5569 
5570 	/*
5571 	 * credp could be null if the open didn't succeed and ip_modopen
5572 	 * itself calls ip_close.
5573 	 */
5574 	if (ill->ill_credp != NULL)
5575 		crfree(ill->ill_credp);
5576 
5577 	/*
5578 	 * Now we are done with the module close pieces that
5579 	 * need the netstack_t.
5580 	 */
5581 	netstack_rele(ipst->ips_netstack);
5582 
5583 	mi_close_free((IDP)ill);
5584 	q->q_ptr = WR(q)->q_ptr = NULL;
5585 
5586 	ipsq_exit(ipsq);
5587 
5588 	return (0);
5589 }
5590 
5591 /*
5592  * This is called as part of close() for IP, UDP, ICMP, and RTS
5593  * in order to quiesce the conn.
5594  */
5595 void
5596 ip_quiesce_conn(conn_t *connp)
5597 {
5598 	boolean_t	drain_cleanup_reqd = B_FALSE;
5599 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5600 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5601 	ip_stack_t	*ipst;
5602 
5603 	ASSERT(!IPCL_IS_TCP(connp));
5604 	ipst = connp->conn_netstack->netstack_ip;
5605 
5606 	/*
5607 	 * Mark the conn as closing, and this conn must not be
5608 	 * inserted in future into any list. Eg. conn_drain_insert(),
5609 	 * won't insert this conn into the conn_drain_list.
5610 	 * Similarly ill_pending_mp_add() will not add any mp to
5611 	 * the pending mp list, after this conn has started closing.
5612 	 *
5613 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5614 	 * cannot get set henceforth.
5615 	 */
5616 	mutex_enter(&connp->conn_lock);
5617 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5618 	connp->conn_state_flags |= CONN_CLOSING;
5619 	if (connp->conn_idl != NULL)
5620 		drain_cleanup_reqd = B_TRUE;
5621 	if (connp->conn_oper_pending_ill != NULL)
5622 		conn_ioctl_cleanup_reqd = B_TRUE;
5623 	if (connp->conn_dhcpinit_ill != NULL) {
5624 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5625 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5626 		connp->conn_dhcpinit_ill = NULL;
5627 	}
5628 	if (connp->conn_ilg_inuse != 0)
5629 		ilg_cleanup_reqd = B_TRUE;
5630 	mutex_exit(&connp->conn_lock);
5631 
5632 	if (conn_ioctl_cleanup_reqd)
5633 		conn_ioctl_cleanup(connp);
5634 
5635 	if (is_system_labeled() && connp->conn_anon_port) {
5636 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5637 		    connp->conn_mlp_type, connp->conn_ulp,
5638 		    ntohs(connp->conn_lport), B_FALSE);
5639 		connp->conn_anon_port = 0;
5640 	}
5641 	connp->conn_mlp_type = mlptSingle;
5642 
5643 	/*
5644 	 * Remove this conn from any fanout list it is on.
5645 	 * and then wait for any threads currently operating
5646 	 * on this endpoint to finish
5647 	 */
5648 	ipcl_hash_remove(connp);
5649 
5650 	/*
5651 	 * Remove this conn from the drain list, and do
5652 	 * any other cleanup that may be required.
5653 	 * (Only non-tcp streams may have a non-null conn_idl.
5654 	 * TCP streams are never flow controlled, and
5655 	 * conn_idl will be null)
5656 	 */
5657 	if (drain_cleanup_reqd)
5658 		conn_drain_tail(connp, B_TRUE);
5659 
5660 	if (connp == ipst->ips_ip_g_mrouter)
5661 		(void) ip_mrouter_done(NULL, ipst);
5662 
5663 	if (ilg_cleanup_reqd)
5664 		ilg_delete_all(connp);
5665 
5666 	conn_delete_ire(connp, NULL);
5667 
5668 	/*
5669 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5670 	 * callers from write side can't be there now because close
5671 	 * is in progress. The only other caller is ipcl_walk
5672 	 * which checks for the condemned flag.
5673 	 */
5674 	mutex_enter(&connp->conn_lock);
5675 	connp->conn_state_flags |= CONN_CONDEMNED;
5676 	while (connp->conn_ref != 1)
5677 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5678 	connp->conn_state_flags |= CONN_QUIESCED;
5679 	mutex_exit(&connp->conn_lock);
5680 }
5681 
5682 /* ARGSUSED */
5683 int
5684 ip_close(queue_t *q, int flags)
5685 {
5686 	conn_t		*connp;
5687 
5688 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5689 
5690 	/*
5691 	 * Call the appropriate delete routine depending on whether this is
5692 	 * a module or device.
5693 	 */
5694 	if (WR(q)->q_next != NULL) {
5695 		/* This is a module close */
5696 		return (ip_modclose((ill_t *)q->q_ptr));
5697 	}
5698 
5699 	connp = q->q_ptr;
5700 	ip_quiesce_conn(connp);
5701 
5702 	qprocsoff(q);
5703 
5704 	/*
5705 	 * Now we are truly single threaded on this stream, and can
5706 	 * delete the things hanging off the connp, and finally the connp.
5707 	 * We removed this connp from the fanout list, it cannot be
5708 	 * accessed thru the fanouts, and we already waited for the
5709 	 * conn_ref to drop to 0. We are already in close, so
5710 	 * there cannot be any other thread from the top. qprocsoff
5711 	 * has completed, and service has completed or won't run in
5712 	 * future.
5713 	 */
5714 	ASSERT(connp->conn_ref == 1);
5715 
5716 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5717 
5718 	connp->conn_ref--;
5719 	ipcl_conn_destroy(connp);
5720 
5721 	q->q_ptr = WR(q)->q_ptr = NULL;
5722 	return (0);
5723 }
5724 
5725 /*
5726  * Wapper around putnext() so that ip_rts_request can merely use
5727  * conn_recv.
5728  */
5729 /*ARGSUSED2*/
5730 static void
5731 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5732 {
5733 	conn_t *connp = (conn_t *)arg1;
5734 
5735 	putnext(connp->conn_rq, mp);
5736 }
5737 
5738 /*
5739  * Called when the module is about to be unloaded
5740  */
5741 void
5742 ip_ddi_destroy(void)
5743 {
5744 	tnet_fini();
5745 
5746 	icmp_ddi_g_destroy();
5747 	rts_ddi_g_destroy();
5748 	udp_ddi_g_destroy();
5749 	sctp_ddi_g_destroy();
5750 	tcp_ddi_g_destroy();
5751 	ipsec_policy_g_destroy();
5752 	ipcl_g_destroy();
5753 	ip_net_g_destroy();
5754 	ip_ire_g_fini();
5755 	inet_minor_destroy(ip_minor_arena_sa);
5756 #if defined(_LP64)
5757 	inet_minor_destroy(ip_minor_arena_la);
5758 #endif
5759 
5760 #ifdef DEBUG
5761 	list_destroy(&ip_thread_list);
5762 	rw_destroy(&ip_thread_rwlock);
5763 	tsd_destroy(&ip_thread_data);
5764 #endif
5765 
5766 	netstack_unregister(NS_IP);
5767 }
5768 
5769 /*
5770  * First step in cleanup.
5771  */
5772 /* ARGSUSED */
5773 static void
5774 ip_stack_shutdown(netstackid_t stackid, void *arg)
5775 {
5776 	ip_stack_t *ipst = (ip_stack_t *)arg;
5777 
5778 #ifdef NS_DEBUG
5779 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5780 #endif
5781 
5782 	/* Get rid of loopback interfaces and their IREs */
5783 	ip_loopback_cleanup(ipst);
5784 
5785 	/*
5786 	 * The *_hook_shutdown()s start the process of notifying any
5787 	 * consumers that things are going away.... nothing is destroyed.
5788 	 */
5789 	ipv4_hook_shutdown(ipst);
5790 	ipv6_hook_shutdown(ipst);
5791 
5792 	mutex_enter(&ipst->ips_capab_taskq_lock);
5793 	ipst->ips_capab_taskq_quit = B_TRUE;
5794 	cv_signal(&ipst->ips_capab_taskq_cv);
5795 	mutex_exit(&ipst->ips_capab_taskq_lock);
5796 
5797 	mutex_enter(&ipst->ips_mrt_lock);
5798 	ipst->ips_mrt_flags |= IP_MRT_STOP;
5799 	cv_signal(&ipst->ips_mrt_cv);
5800 	mutex_exit(&ipst->ips_mrt_lock);
5801 }
5802 
5803 /*
5804  * Free the IP stack instance.
5805  */
5806 static void
5807 ip_stack_fini(netstackid_t stackid, void *arg)
5808 {
5809 	ip_stack_t *ipst = (ip_stack_t *)arg;
5810 	int ret;
5811 
5812 #ifdef NS_DEBUG
5813 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5814 #endif
5815 	/*
5816 	 * At this point, all of the notifications that the events and
5817 	 * protocols are going away have been run, meaning that we can
5818 	 * now set about starting to clean things up.
5819 	 */
5820 	ipv4_hook_destroy(ipst);
5821 	ipv6_hook_destroy(ipst);
5822 	ip_net_destroy(ipst);
5823 
5824 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5825 	cv_destroy(&ipst->ips_capab_taskq_cv);
5826 	list_destroy(&ipst->ips_capab_taskq_list);
5827 
5828 	mutex_enter(&ipst->ips_mrt_lock);
5829 	while (!(ipst->ips_mrt_flags & IP_MRT_DONE))
5830 		cv_wait(&ipst->ips_mrt_done_cv, &ipst->ips_mrt_lock);
5831 	mutex_destroy(&ipst->ips_mrt_lock);
5832 	cv_destroy(&ipst->ips_mrt_cv);
5833 	cv_destroy(&ipst->ips_mrt_done_cv);
5834 
5835 	ipmp_destroy(ipst);
5836 	rw_destroy(&ipst->ips_srcid_lock);
5837 
5838 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5839 	ipst->ips_ip_mibkp = NULL;
5840 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5841 	ipst->ips_icmp_mibkp = NULL;
5842 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5843 	ipst->ips_ip_kstat = NULL;
5844 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5845 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5846 	ipst->ips_ip6_kstat = NULL;
5847 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5848 
5849 	nd_free(&ipst->ips_ip_g_nd);
5850 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5851 	ipst->ips_param_arr = NULL;
5852 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5853 	ipst->ips_ndp_arr = NULL;
5854 
5855 	ip_mrouter_stack_destroy(ipst);
5856 
5857 	mutex_destroy(&ipst->ips_ip_mi_lock);
5858 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5859 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5860 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5861 
5862 	ret = untimeout(ipst->ips_igmp_timeout_id);
5863 	if (ret == -1) {
5864 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5865 	} else {
5866 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5867 		ipst->ips_igmp_timeout_id = 0;
5868 	}
5869 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5870 	if (ret == -1) {
5871 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5872 	} else {
5873 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5874 		ipst->ips_igmp_slowtimeout_id = 0;
5875 	}
5876 	ret = untimeout(ipst->ips_mld_timeout_id);
5877 	if (ret == -1) {
5878 		ASSERT(ipst->ips_mld_timeout_id == 0);
5879 	} else {
5880 		ASSERT(ipst->ips_mld_timeout_id != 0);
5881 		ipst->ips_mld_timeout_id = 0;
5882 	}
5883 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5884 	if (ret == -1) {
5885 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5886 	} else {
5887 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5888 		ipst->ips_mld_slowtimeout_id = 0;
5889 	}
5890 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5891 	if (ret == -1) {
5892 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5893 	} else {
5894 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5895 		ipst->ips_ip_ire_expire_id = 0;
5896 	}
5897 
5898 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5899 	mutex_destroy(&ipst->ips_mld_timer_lock);
5900 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5901 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5902 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5903 	rw_destroy(&ipst->ips_ill_g_lock);
5904 
5905 	ipobs_fini(ipst);
5906 	ip_ire_fini(ipst);
5907 	ip6_asp_free(ipst);
5908 	conn_drain_fini(ipst);
5909 	ipcl_destroy(ipst);
5910 
5911 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5912 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5913 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5914 	ipst->ips_ndp4 = NULL;
5915 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5916 	ipst->ips_ndp6 = NULL;
5917 
5918 	if (ipst->ips_loopback_ksp != NULL) {
5919 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5920 		ipst->ips_loopback_ksp = NULL;
5921 	}
5922 
5923 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5924 	ipst->ips_phyint_g_list = NULL;
5925 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5926 	ipst->ips_ill_g_heads = NULL;
5927 
5928 	ldi_ident_release(ipst->ips_ldi_ident);
5929 	kmem_free(ipst, sizeof (*ipst));
5930 }
5931 
5932 /*
5933  * This function is called from the TSD destructor, and is used to debug
5934  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5935  * details.
5936  */
5937 static void
5938 ip_thread_exit(void *phash)
5939 {
5940 	th_hash_t *thh = phash;
5941 
5942 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5943 	list_remove(&ip_thread_list, thh);
5944 	rw_exit(&ip_thread_rwlock);
5945 	mod_hash_destroy_hash(thh->thh_hash);
5946 	kmem_free(thh, sizeof (*thh));
5947 }
5948 
5949 /*
5950  * Called when the IP kernel module is loaded into the kernel
5951  */
5952 void
5953 ip_ddi_init(void)
5954 {
5955 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5956 
5957 	/*
5958 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5959 	 * initial devices: ip, ip6, tcp, tcp6.
5960 	 */
5961 	/*
5962 	 * If this is a 64-bit kernel, then create two separate arenas -
5963 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5964 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5965 	 */
5966 	ip_minor_arena_la = NULL;
5967 	ip_minor_arena_sa = NULL;
5968 #if defined(_LP64)
5969 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5970 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5971 		cmn_err(CE_PANIC,
5972 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5973 	}
5974 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5975 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5976 		cmn_err(CE_PANIC,
5977 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5978 	}
5979 #else
5980 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5981 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5982 		cmn_err(CE_PANIC,
5983 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5984 	}
5985 #endif
5986 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5987 
5988 	ipcl_g_init();
5989 	ip_ire_g_init();
5990 	ip_net_g_init();
5991 
5992 #ifdef DEBUG
5993 	tsd_create(&ip_thread_data, ip_thread_exit);
5994 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5995 	list_create(&ip_thread_list, sizeof (th_hash_t),
5996 	    offsetof(th_hash_t, thh_link));
5997 #endif
5998 
5999 	/*
6000 	 * We want to be informed each time a stack is created or
6001 	 * destroyed in the kernel, so we can maintain the
6002 	 * set of udp_stack_t's.
6003 	 */
6004 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
6005 	    ip_stack_fini);
6006 
6007 	ipsec_policy_g_init();
6008 	tcp_ddi_g_init();
6009 	sctp_ddi_g_init();
6010 
6011 	tnet_init();
6012 
6013 	udp_ddi_g_init();
6014 	rts_ddi_g_init();
6015 	icmp_ddi_g_init();
6016 }
6017 
6018 /*
6019  * Initialize the IP stack instance.
6020  */
6021 static void *
6022 ip_stack_init(netstackid_t stackid, netstack_t *ns)
6023 {
6024 	ip_stack_t	*ipst;
6025 	ipparam_t	*pa;
6026 	ipndp_t		*na;
6027 	major_t		major;
6028 
6029 #ifdef NS_DEBUG
6030 	printf("ip_stack_init(stack %d)\n", stackid);
6031 #endif
6032 
6033 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6034 	ipst->ips_netstack = ns;
6035 
6036 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6037 	    KM_SLEEP);
6038 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6039 	    KM_SLEEP);
6040 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6041 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6042 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6043 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6044 
6045 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6046 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6047 	ipst->ips_igmp_deferred_next = INFINITY;
6048 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6049 	ipst->ips_mld_deferred_next = INFINITY;
6050 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6051 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6052 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6053 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6054 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6055 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6056 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6057 
6058 	ipcl_init(ipst);
6059 	ip_ire_init(ipst);
6060 	ip6_asp_init(ipst);
6061 	ipif_init(ipst);
6062 	conn_drain_init(ipst);
6063 	ip_mrouter_stack_init(ipst);
6064 
6065 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6066 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6067 	ipst->ips_ipv6_frag_timeout = IPV6_FRAG_TIMEOUT;
6068 	ipst->ips_ipv6_frag_timo_ms = IPV6_FRAG_TIMEOUT * 1000;
6069 
6070 	ipst->ips_ip_multirt_log_interval = 1000;
6071 
6072 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6073 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6074 	ipst->ips_ill_index = 1;
6075 
6076 	ipst->ips_saved_ip_g_forward = -1;
6077 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6078 
6079 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6080 	ipst->ips_param_arr = pa;
6081 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6082 
6083 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6084 	ipst->ips_ndp_arr = na;
6085 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6086 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6087 	    (caddr_t)&ipst->ips_ip_g_forward;
6088 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6089 	    (caddr_t)&ipst->ips_ipv6_forward;
6090 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6091 	    "ip_cgtp_filter") == 0);
6092 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6093 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6094 
6095 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6096 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6097 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6098 
6099 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6100 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6101 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6102 	ipst->ips_ip6_kstat =
6103 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6104 
6105 	ipst->ips_ip_src_id = 1;
6106 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6107 
6108 	ipobs_init(ipst);
6109 	ip_net_init(ipst, ns);
6110 	ipv4_hook_init(ipst);
6111 	ipv6_hook_init(ipst);
6112 	ipmp_init(ipst);
6113 
6114 	/*
6115 	 * Create the taskq dispatcher thread and initialize related stuff.
6116 	 */
6117 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6118 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6119 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6120 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6121 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6122 	    offsetof(mblk_t, b_next));
6123 
6124 	/*
6125 	 * Create the mcast_restart_timers_thread() worker thread.
6126 	 */
6127 	mutex_init(&ipst->ips_mrt_lock, NULL, MUTEX_DEFAULT, NULL);
6128 	cv_init(&ipst->ips_mrt_cv, NULL, CV_DEFAULT, NULL);
6129 	cv_init(&ipst->ips_mrt_done_cv, NULL, CV_DEFAULT, NULL);
6130 	ipst->ips_mrt_thread = thread_create(NULL, 0,
6131 	    mcast_restart_timers_thread, ipst, 0, &p0, TS_RUN, minclsyspri);
6132 
6133 	major = mod_name_to_major(INET_NAME);
6134 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
6135 	return (ipst);
6136 }
6137 
6138 /*
6139  * Allocate and initialize a DLPI template of the specified length.  (May be
6140  * called as writer.)
6141  */
6142 mblk_t *
6143 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6144 {
6145 	mblk_t	*mp;
6146 
6147 	mp = allocb(len, BPRI_MED);
6148 	if (!mp)
6149 		return (NULL);
6150 
6151 	/*
6152 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6153 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6154 	 * that other DLPI are M_PROTO.
6155 	 */
6156 	if (prim == DL_INFO_REQ) {
6157 		mp->b_datap->db_type = M_PCPROTO;
6158 	} else {
6159 		mp->b_datap->db_type = M_PROTO;
6160 	}
6161 
6162 	mp->b_wptr = mp->b_rptr + len;
6163 	bzero(mp->b_rptr, len);
6164 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6165 	return (mp);
6166 }
6167 
6168 /*
6169  * Allocate and initialize a DLPI notification.  (May be called as writer.)
6170  */
6171 mblk_t *
6172 ip_dlnotify_alloc(uint_t notification, uint_t data)
6173 {
6174 	dl_notify_ind_t	*notifyp;
6175 	mblk_t		*mp;
6176 
6177 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
6178 		return (NULL);
6179 
6180 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
6181 	notifyp->dl_notification = notification;
6182 	notifyp->dl_data = data;
6183 	return (mp);
6184 }
6185 
6186 /*
6187  * Debug formatting routine.  Returns a character string representation of the
6188  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6189  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6190  *
6191  * Once the ndd table-printing interfaces are removed, this can be changed to
6192  * standard dotted-decimal form.
6193  */
6194 char *
6195 ip_dot_addr(ipaddr_t addr, char *buf)
6196 {
6197 	uint8_t *ap = (uint8_t *)&addr;
6198 
6199 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6200 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6201 	return (buf);
6202 }
6203 
6204 /*
6205  * Write the given MAC address as a printable string in the usual colon-
6206  * separated format.
6207  */
6208 const char *
6209 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6210 {
6211 	char *bp;
6212 
6213 	if (alen == 0 || buflen < 4)
6214 		return ("?");
6215 	bp = buf;
6216 	for (;;) {
6217 		/*
6218 		 * If there are more MAC address bytes available, but we won't
6219 		 * have any room to print them, then add "..." to the string
6220 		 * instead.  See below for the 'magic number' explanation.
6221 		 */
6222 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6223 			(void) strcpy(bp, "...");
6224 			break;
6225 		}
6226 		(void) sprintf(bp, "%02x", *addr++);
6227 		bp += 2;
6228 		if (--alen == 0)
6229 			break;
6230 		*bp++ = ':';
6231 		buflen -= 3;
6232 		/*
6233 		 * At this point, based on the first 'if' statement above,
6234 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6235 		 * buflen >= 4.  The first case leaves room for the final "xx"
6236 		 * number and trailing NUL byte.  The second leaves room for at
6237 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6238 		 * that statement.
6239 		 */
6240 	}
6241 	return (buf);
6242 }
6243 
6244 /*
6245  * Send an ICMP error after patching up the packet appropriately.  Returns
6246  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6247  */
6248 static boolean_t
6249 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6250     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6251     zoneid_t zoneid, ip_stack_t *ipst)
6252 {
6253 	ipha_t *ipha;
6254 	mblk_t *first_mp;
6255 	boolean_t secure;
6256 	unsigned char db_type;
6257 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6258 
6259 	first_mp = mp;
6260 	if (mctl_present) {
6261 		mp = mp->b_cont;
6262 		secure = ipsec_in_is_secure(first_mp);
6263 		ASSERT(mp != NULL);
6264 	} else {
6265 		/*
6266 		 * If this is an ICMP error being reported - which goes
6267 		 * up as M_CTLs, we need to convert them to M_DATA till
6268 		 * we finish checking with global policy because
6269 		 * ipsec_check_global_policy() assumes M_DATA as clear
6270 		 * and M_CTL as secure.
6271 		 */
6272 		db_type = DB_TYPE(mp);
6273 		DB_TYPE(mp) = M_DATA;
6274 		secure = B_FALSE;
6275 	}
6276 	/*
6277 	 * We are generating an icmp error for some inbound packet.
6278 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6279 	 * Before we generate an error, check with global policy
6280 	 * to see whether this is allowed to enter the system. As
6281 	 * there is no "conn", we are checking with global policy.
6282 	 */
6283 	ipha = (ipha_t *)mp->b_rptr;
6284 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6285 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6286 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6287 		if (first_mp == NULL)
6288 			return (B_FALSE);
6289 	}
6290 
6291 	if (!mctl_present)
6292 		DB_TYPE(mp) = db_type;
6293 
6294 	if (flags & IP_FF_SEND_ICMP) {
6295 		if (flags & IP_FF_HDR_COMPLETE) {
6296 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6297 				freemsg(first_mp);
6298 				return (B_TRUE);
6299 			}
6300 		}
6301 		if (flags & IP_FF_CKSUM) {
6302 			/*
6303 			 * Have to correct checksum since
6304 			 * the packet might have been
6305 			 * fragmented and the reassembly code in ip_rput
6306 			 * does not restore the IP checksum.
6307 			 */
6308 			ipha->ipha_hdr_checksum = 0;
6309 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6310 		}
6311 		switch (icmp_type) {
6312 		case ICMP_DEST_UNREACHABLE:
6313 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6314 			    ipst);
6315 			break;
6316 		default:
6317 			freemsg(first_mp);
6318 			break;
6319 		}
6320 	} else {
6321 		freemsg(first_mp);
6322 		return (B_FALSE);
6323 	}
6324 
6325 	return (B_TRUE);
6326 }
6327 
6328 /*
6329  * Used to send an ICMP error message when a packet is received for
6330  * a protocol that is not supported. The mblk passed as argument
6331  * is consumed by this function.
6332  */
6333 void
6334 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6335     ip_stack_t *ipst)
6336 {
6337 	mblk_t *mp;
6338 	ipha_t *ipha;
6339 	ill_t *ill;
6340 	ipsec_in_t *ii;
6341 
6342 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6343 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6344 
6345 	mp = ipsec_mp->b_cont;
6346 	ipsec_mp->b_cont = NULL;
6347 	ipha = (ipha_t *)mp->b_rptr;
6348 	/* Get ill from index in ipsec_in_t. */
6349 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6350 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6351 	    ipst);
6352 	if (ill != NULL) {
6353 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6354 			if (ip_fanout_send_icmp(q, mp, flags,
6355 			    ICMP_DEST_UNREACHABLE,
6356 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6357 				BUMP_MIB(ill->ill_ip_mib,
6358 				    ipIfStatsInUnknownProtos);
6359 			}
6360 		} else {
6361 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6362 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6363 			    0, B_FALSE, zoneid, ipst)) {
6364 				BUMP_MIB(ill->ill_ip_mib,
6365 				    ipIfStatsInUnknownProtos);
6366 			}
6367 		}
6368 		ill_refrele(ill);
6369 	} else { /* re-link for the freemsg() below. */
6370 		ipsec_mp->b_cont = mp;
6371 	}
6372 
6373 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6374 	freemsg(ipsec_mp);
6375 }
6376 
6377 /*
6378  * See if the inbound datagram has had IPsec processing applied to it.
6379  */
6380 boolean_t
6381 ipsec_in_is_secure(mblk_t *ipsec_mp)
6382 {
6383 	ipsec_in_t *ii;
6384 
6385 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6386 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6387 
6388 	if (ii->ipsec_in_loopback) {
6389 		return (ii->ipsec_in_secure);
6390 	} else {
6391 		return (ii->ipsec_in_ah_sa != NULL ||
6392 		    ii->ipsec_in_esp_sa != NULL ||
6393 		    ii->ipsec_in_decaps);
6394 	}
6395 }
6396 
6397 /*
6398  * Handle protocols with which IP is less intimate.  There
6399  * can be more than one stream bound to a particular
6400  * protocol.  When this is the case, normally each one gets a copy
6401  * of any incoming packets.
6402  *
6403  * IPsec NOTE :
6404  *
6405  * Don't allow a secure packet going up a non-secure connection.
6406  * We don't allow this because
6407  *
6408  * 1) Reply might go out in clear which will be dropped at
6409  *    the sending side.
6410  * 2) If the reply goes out in clear it will give the
6411  *    adversary enough information for getting the key in
6412  *    most of the cases.
6413  *
6414  * Moreover getting a secure packet when we expect clear
6415  * implies that SA's were added without checking for
6416  * policy on both ends. This should not happen once ISAKMP
6417  * is used to negotiate SAs as SAs will be added only after
6418  * verifying the policy.
6419  *
6420  * NOTE : If the packet was tunneled and not multicast we only send
6421  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6422  * back to delivering packets to AF_INET6 raw sockets.
6423  *
6424  * IPQoS Notes:
6425  * Once we have determined the client, invoke IPPF processing.
6426  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6427  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6428  * ip_policy will be false.
6429  *
6430  * Zones notes:
6431  * Currently only applications in the global zone can create raw sockets for
6432  * protocols other than ICMP. So unlike the broadcast / multicast case of
6433  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6434  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6435  */
6436 static void
6437 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6438     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6439     zoneid_t zoneid)
6440 {
6441 	queue_t	*rq;
6442 	mblk_t	*mp1, *first_mp1;
6443 	uint_t	protocol = ipha->ipha_protocol;
6444 	ipaddr_t dst;
6445 	boolean_t one_only;
6446 	mblk_t *first_mp = mp;
6447 	boolean_t secure;
6448 	uint32_t ill_index;
6449 	conn_t	*connp, *first_connp, *next_connp;
6450 	connf_t	*connfp;
6451 	boolean_t shared_addr;
6452 	mib2_ipIfStatsEntry_t *mibptr;
6453 	ip_stack_t *ipst = recv_ill->ill_ipst;
6454 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6455 
6456 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6457 	if (mctl_present) {
6458 		mp = first_mp->b_cont;
6459 		secure = ipsec_in_is_secure(first_mp);
6460 		ASSERT(mp != NULL);
6461 	} else {
6462 		secure = B_FALSE;
6463 	}
6464 	dst = ipha->ipha_dst;
6465 	/*
6466 	 * If the packet was tunneled and not multicast we only send to it
6467 	 * the first match.
6468 	 */
6469 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6470 	    !CLASSD(dst));
6471 
6472 	shared_addr = (zoneid == ALL_ZONES);
6473 	if (shared_addr) {
6474 		/*
6475 		 * We don't allow multilevel ports for raw IP, so no need to
6476 		 * check for that here.
6477 		 */
6478 		zoneid = tsol_packet_to_zoneid(mp);
6479 	}
6480 
6481 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6482 	mutex_enter(&connfp->connf_lock);
6483 	connp = connfp->connf_head;
6484 	for (connp = connfp->connf_head; connp != NULL;
6485 	    connp = connp->conn_next) {
6486 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6487 		    zoneid) &&
6488 		    (!is_system_labeled() ||
6489 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6490 		    connp))) {
6491 			break;
6492 		}
6493 	}
6494 
6495 	if (connp == NULL) {
6496 		/*
6497 		 * No one bound to these addresses.  Is
6498 		 * there a client that wants all
6499 		 * unclaimed datagrams?
6500 		 */
6501 		mutex_exit(&connfp->connf_lock);
6502 		/*
6503 		 * Check for IPPROTO_ENCAP...
6504 		 */
6505 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6506 			/*
6507 			 * If an IPsec mblk is here on a multicast
6508 			 * tunnel (using ip_mroute stuff), check policy here,
6509 			 * THEN ship off to ip_mroute_decap().
6510 			 *
6511 			 * BTW,  If I match a configured IP-in-IP
6512 			 * tunnel, this path will not be reached, and
6513 			 * ip_mroute_decap will never be called.
6514 			 */
6515 			first_mp = ipsec_check_global_policy(first_mp, connp,
6516 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6517 			if (first_mp != NULL) {
6518 				if (mctl_present)
6519 					freeb(first_mp);
6520 				ip_mroute_decap(q, mp, ill);
6521 			} /* Else we already freed everything! */
6522 		} else {
6523 			/*
6524 			 * Otherwise send an ICMP protocol unreachable.
6525 			 */
6526 			if (ip_fanout_send_icmp(q, first_mp, flags,
6527 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6528 			    mctl_present, zoneid, ipst)) {
6529 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6530 			}
6531 		}
6532 		return;
6533 	}
6534 
6535 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
6536 
6537 	CONN_INC_REF(connp);
6538 	first_connp = connp;
6539 
6540 	/*
6541 	 * Only send message to one tunnel driver by immediately
6542 	 * terminating the loop.
6543 	 */
6544 	connp = one_only ? NULL : connp->conn_next;
6545 
6546 	for (;;) {
6547 		while (connp != NULL) {
6548 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6549 			    flags, zoneid) &&
6550 			    (!is_system_labeled() ||
6551 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6552 			    shared_addr, connp)))
6553 				break;
6554 			connp = connp->conn_next;
6555 		}
6556 
6557 		/*
6558 		 * Copy the packet.
6559 		 */
6560 		if (connp == NULL ||
6561 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6562 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6563 			/*
6564 			 * No more interested clients or memory
6565 			 * allocation failed
6566 			 */
6567 			connp = first_connp;
6568 			break;
6569 		}
6570 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
6571 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6572 		CONN_INC_REF(connp);
6573 		mutex_exit(&connfp->connf_lock);
6574 		rq = connp->conn_rq;
6575 
6576 		/*
6577 		 * Check flow control
6578 		 */
6579 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6580 		    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6581 			if (flags & IP_FF_RAWIP) {
6582 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6583 			} else {
6584 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6585 			}
6586 
6587 			freemsg(first_mp1);
6588 		} else {
6589 			/*
6590 			 * Don't enforce here if we're an actual tunnel -
6591 			 * let "tun" do it instead.
6592 			 */
6593 			if (!IPCL_IS_IPTUN(connp) &&
6594 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6595 			    secure)) {
6596 				first_mp1 = ipsec_check_inbound_policy
6597 				    (first_mp1, connp, ipha, NULL,
6598 				    mctl_present);
6599 			}
6600 			if (first_mp1 != NULL) {
6601 				int in_flags = 0;
6602 				/*
6603 				 * ip_fanout_proto also gets called from
6604 				 * icmp_inbound_error_fanout, in which case
6605 				 * the msg type is M_CTL.  Don't add info
6606 				 * in this case for the time being. In future
6607 				 * when there is a need for knowing the
6608 				 * inbound iface index for ICMP error msgs,
6609 				 * then this can be changed.
6610 				 */
6611 				if (connp->conn_recvif)
6612 					in_flags = IPF_RECVIF;
6613 				/*
6614 				 * The ULP may support IP_RECVPKTINFO for both
6615 				 * IP v4 and v6 so pass the appropriate argument
6616 				 * based on conn IP version.
6617 				 */
6618 				if (connp->conn_ip_recvpktinfo) {
6619 					if (connp->conn_af_isv6) {
6620 						/*
6621 						 * V6 only needs index
6622 						 */
6623 						in_flags |= IPF_RECVIF;
6624 					} else {
6625 						/*
6626 						 * V4 needs index +
6627 						 * matching address.
6628 						 */
6629 						in_flags |= IPF_RECVADDR;
6630 					}
6631 				}
6632 				if ((in_flags != 0) &&
6633 				    (mp->b_datap->db_type != M_CTL)) {
6634 					/*
6635 					 * the actual data will be
6636 					 * contained in b_cont upon
6637 					 * successful return of the
6638 					 * following call else
6639 					 * original mblk is returned
6640 					 */
6641 					ASSERT(recv_ill != NULL);
6642 					mp1 = ip_add_info(mp1, recv_ill,
6643 					    in_flags, IPCL_ZONEID(connp), ipst);
6644 				}
6645 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6646 				if (mctl_present)
6647 					freeb(first_mp1);
6648 				(connp->conn_recv)(connp, mp1, NULL);
6649 			}
6650 		}
6651 		mutex_enter(&connfp->connf_lock);
6652 		/* Follow the next pointer before releasing the conn. */
6653 		next_connp = connp->conn_next;
6654 		CONN_DEC_REF(connp);
6655 		connp = next_connp;
6656 	}
6657 
6658 	/* Last one.  Send it upstream. */
6659 	mutex_exit(&connfp->connf_lock);
6660 
6661 	/*
6662 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6663 	 * will be set to false.
6664 	 */
6665 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6666 		ill_index = ill->ill_phyint->phyint_ifindex;
6667 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6668 		if (mp == NULL) {
6669 			CONN_DEC_REF(connp);
6670 			if (mctl_present) {
6671 				freeb(first_mp);
6672 			}
6673 			return;
6674 		}
6675 	}
6676 
6677 	rq = connp->conn_rq;
6678 	/*
6679 	 * Check flow control
6680 	 */
6681 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
6682 	    (!IPCL_IS_NONSTR(connp) && !canputnext(rq))) {
6683 		if (flags & IP_FF_RAWIP) {
6684 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6685 		} else {
6686 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6687 		}
6688 
6689 		freemsg(first_mp);
6690 	} else {
6691 		if (IPCL_IS_IPTUN(connp)) {
6692 			/*
6693 			 * Tunneled packet.  We enforce policy in the tunnel
6694 			 * module itself.
6695 			 *
6696 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6697 			 * a policy check.
6698 			 * FIXME to use conn_recv for tun later.
6699 			 */
6700 			putnext(rq, first_mp);
6701 			CONN_DEC_REF(connp);
6702 			return;
6703 		}
6704 
6705 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6706 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6707 			    ipha, NULL, mctl_present);
6708 		}
6709 
6710 		if (first_mp != NULL) {
6711 			int in_flags = 0;
6712 
6713 			/*
6714 			 * ip_fanout_proto also gets called
6715 			 * from icmp_inbound_error_fanout, in
6716 			 * which case the msg type is M_CTL.
6717 			 * Don't add info in this case for time
6718 			 * being. In future when there is a
6719 			 * need for knowing the inbound iface
6720 			 * index for ICMP error msgs, then this
6721 			 * can be changed
6722 			 */
6723 			if (connp->conn_recvif)
6724 				in_flags = IPF_RECVIF;
6725 			if (connp->conn_ip_recvpktinfo) {
6726 				if (connp->conn_af_isv6) {
6727 					/*
6728 					 * V6 only needs index
6729 					 */
6730 					in_flags |= IPF_RECVIF;
6731 				} else {
6732 					/*
6733 					 * V4 needs index +
6734 					 * matching address.
6735 					 */
6736 					in_flags |= IPF_RECVADDR;
6737 				}
6738 			}
6739 			if ((in_flags != 0) &&
6740 			    (mp->b_datap->db_type != M_CTL)) {
6741 
6742 				/*
6743 				 * the actual data will be contained in
6744 				 * b_cont upon successful return
6745 				 * of the following call else original
6746 				 * mblk is returned
6747 				 */
6748 				ASSERT(recv_ill != NULL);
6749 				mp = ip_add_info(mp, recv_ill,
6750 				    in_flags, IPCL_ZONEID(connp), ipst);
6751 			}
6752 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6753 			(connp->conn_recv)(connp, mp, NULL);
6754 			if (mctl_present)
6755 				freeb(first_mp);
6756 		}
6757 	}
6758 	CONN_DEC_REF(connp);
6759 }
6760 
6761 /*
6762  * Serialize tcp resets by calling tcp_xmit_reset_serialize through
6763  * SQUEUE_ENTER_ONE(SQ_FILL). We do this to ensure the reset is handled on
6764  * the correct squeue, in this case the same squeue as a valid listener with
6765  * no current connection state for the packet we are processing. The function
6766  * is called for synchronizing both IPv4 and IPv6.
6767  */
6768 void
6769 ip_xmit_reset_serialize(mblk_t *mp, int hdrlen, zoneid_t zoneid,
6770     tcp_stack_t *tcps, conn_t *connp)
6771 {
6772 	mblk_t *rst_mp;
6773 	tcp_xmit_reset_event_t *eventp;
6774 
6775 	rst_mp = allocb(sizeof (tcp_xmit_reset_event_t), BPRI_HI);
6776 
6777 	if (rst_mp == NULL) {
6778 		freemsg(mp);
6779 		return;
6780 	}
6781 
6782 	rst_mp->b_datap->db_type = M_PROTO;
6783 	rst_mp->b_wptr += sizeof (tcp_xmit_reset_event_t);
6784 
6785 	eventp = (tcp_xmit_reset_event_t *)rst_mp->b_rptr;
6786 	eventp->tcp_xre_event = TCP_XRE_EVENT_IP_FANOUT_TCP;
6787 	eventp->tcp_xre_iphdrlen = hdrlen;
6788 	eventp->tcp_xre_zoneid = zoneid;
6789 	eventp->tcp_xre_tcps = tcps;
6790 
6791 	rst_mp->b_cont = mp;
6792 	mp = rst_mp;
6793 
6794 	/*
6795 	 * Increment the connref, this ref will be released by the squeue
6796 	 * framework.
6797 	 */
6798 	CONN_INC_REF(connp);
6799 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_xmit_reset, connp,
6800 	    SQ_FILL, SQTAG_XMIT_EARLY_RESET);
6801 }
6802 
6803 /*
6804  * Fanout for TCP packets
6805  * The caller puts <fport, lport> in the ports parameter.
6806  *
6807  * IPQoS Notes
6808  * Before sending it to the client, invoke IPPF processing.
6809  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6810  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6811  * ip_policy is false.
6812  */
6813 static void
6814 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6815     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6816 {
6817 	mblk_t  *first_mp;
6818 	boolean_t secure;
6819 	uint32_t ill_index;
6820 	int	ip_hdr_len;
6821 	tcph_t	*tcph;
6822 	boolean_t syn_present = B_FALSE;
6823 	conn_t	*connp;
6824 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6825 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6826 
6827 	ASSERT(recv_ill != NULL);
6828 
6829 	first_mp = mp;
6830 	if (mctl_present) {
6831 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6832 		mp = first_mp->b_cont;
6833 		secure = ipsec_in_is_secure(first_mp);
6834 		ASSERT(mp != NULL);
6835 	} else {
6836 		secure = B_FALSE;
6837 	}
6838 
6839 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6840 
6841 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6842 	    zoneid, ipst)) == NULL) {
6843 		/*
6844 		 * No connected connection or listener. Send a
6845 		 * TH_RST via tcp_xmit_listeners_reset.
6846 		 */
6847 
6848 		/* Initiate IPPf processing, if needed. */
6849 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6850 			uint32_t ill_index;
6851 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6852 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6853 			if (first_mp == NULL)
6854 				return;
6855 		}
6856 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6857 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6858 		    zoneid));
6859 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6860 		    ipst->ips_netstack->netstack_tcp, NULL);
6861 		return;
6862 	}
6863 
6864 	/*
6865 	 * Allocate the SYN for the TCP connection here itself
6866 	 */
6867 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6868 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6869 		if (IPCL_IS_TCP(connp)) {
6870 			squeue_t *sqp;
6871 
6872 			/*
6873 			 * If the queue belongs to a conn, and fused tcp
6874 			 * loopback is enabled, assign the eager's squeue
6875 			 * to be that of the active connect's. Note that
6876 			 * we don't check for IP_FF_LOOPBACK here since this
6877 			 * routine gets called only for loopback (unlike the
6878 			 * IPv6 counterpart).
6879 			 */
6880 			if (do_tcp_fusion &&
6881 			    CONN_Q(q) && IPCL_IS_TCP(Q_TO_CONN(q)) &&
6882 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6883 			    !secure &&
6884 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy) {
6885 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6886 				sqp = Q_TO_CONN(q)->conn_sqp;
6887 			} else {
6888 				sqp = IP_SQUEUE_GET(lbolt);
6889 			}
6890 
6891 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6892 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6893 			syn_present = B_TRUE;
6894 		}
6895 	}
6896 
6897 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6898 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6899 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6900 		if ((flags & TH_RST) || (flags & TH_URG)) {
6901 			CONN_DEC_REF(connp);
6902 			freemsg(first_mp);
6903 			return;
6904 		}
6905 		if (flags & TH_ACK) {
6906 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
6907 			    ipst->ips_netstack->netstack_tcp, connp);
6908 			CONN_DEC_REF(connp);
6909 			return;
6910 		}
6911 
6912 		CONN_DEC_REF(connp);
6913 		freemsg(first_mp);
6914 		return;
6915 	}
6916 
6917 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6918 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6919 		    NULL, mctl_present);
6920 		if (first_mp == NULL) {
6921 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6922 			CONN_DEC_REF(connp);
6923 			return;
6924 		}
6925 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6926 			ASSERT(syn_present);
6927 			if (mctl_present) {
6928 				ASSERT(first_mp != mp);
6929 				first_mp->b_datap->db_struioflag |=
6930 				    STRUIO_POLICY;
6931 			} else {
6932 				ASSERT(first_mp == mp);
6933 				mp->b_datap->db_struioflag &=
6934 				    ~STRUIO_EAGER;
6935 				mp->b_datap->db_struioflag |=
6936 				    STRUIO_POLICY;
6937 			}
6938 		} else {
6939 			/*
6940 			 * Discard first_mp early since we're dealing with a
6941 			 * fully-connected conn_t and tcp doesn't do policy in
6942 			 * this case.
6943 			 */
6944 			if (mctl_present) {
6945 				freeb(first_mp);
6946 				mctl_present = B_FALSE;
6947 			}
6948 			first_mp = mp;
6949 		}
6950 	}
6951 
6952 	/*
6953 	 * Initiate policy processing here if needed. If we get here from
6954 	 * icmp_inbound_error_fanout, ip_policy is false.
6955 	 */
6956 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6957 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6958 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6959 		if (mp == NULL) {
6960 			CONN_DEC_REF(connp);
6961 			if (mctl_present)
6962 				freeb(first_mp);
6963 			return;
6964 		} else if (mctl_present) {
6965 			ASSERT(first_mp != mp);
6966 			first_mp->b_cont = mp;
6967 		} else {
6968 			first_mp = mp;
6969 		}
6970 	}
6971 
6972 	/* Handle socket options. */
6973 	if (!syn_present &&
6974 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6975 		/* Add header */
6976 		ASSERT(recv_ill != NULL);
6977 		/*
6978 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6979 		 * IPF_RECVIF.
6980 		 */
6981 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6982 		    ipst);
6983 		if (mp == NULL) {
6984 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6985 			CONN_DEC_REF(connp);
6986 			if (mctl_present)
6987 				freeb(first_mp);
6988 			return;
6989 		} else if (mctl_present) {
6990 			/*
6991 			 * ip_add_info might return a new mp.
6992 			 */
6993 			ASSERT(first_mp != mp);
6994 			first_mp->b_cont = mp;
6995 		} else {
6996 			first_mp = mp;
6997 		}
6998 	}
6999 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
7000 	if (IPCL_IS_TCP(connp)) {
7001 		/* do not drain, certain use cases can blow the stack */
7002 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
7003 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
7004 	} else {
7005 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
7006 		(connp->conn_recv)(connp, first_mp, NULL);
7007 		CONN_DEC_REF(connp);
7008 	}
7009 }
7010 
7011 /*
7012  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
7013  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
7014  * is not consumed.
7015  *
7016  * One of four things can happen, all of which affect the passed-in mblk:
7017  *
7018  * 1.) ICMP messages that go through here just get returned TRUE.
7019  *
7020  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
7021  *
7022  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
7023  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
7024  *
7025  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
7026  */
7027 static boolean_t
7028 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
7029     ipsec_stack_t *ipss)
7030 {
7031 	int shift, plen, iph_len;
7032 	ipha_t *ipha;
7033 	udpha_t *udpha;
7034 	uint32_t *spi;
7035 	uint32_t esp_ports;
7036 	uint8_t *orptr;
7037 	boolean_t free_ire;
7038 
7039 	if (DB_TYPE(mp) == M_CTL) {
7040 		/*
7041 		 * ICMP message with UDP inside.  Don't bother stripping, just
7042 		 * send it up.
7043 		 *
7044 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
7045 		 * to ignore errors set by ICMP anyway ('cause they might be
7046 		 * forged), but that's the app's decision, not ours.
7047 		 */
7048 
7049 		/* Bunch of reality checks for DEBUG kernels... */
7050 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
7051 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
7052 
7053 		return (B_TRUE);
7054 	}
7055 
7056 	ipha = (ipha_t *)mp->b_rptr;
7057 	iph_len = IPH_HDR_LENGTH(ipha);
7058 	plen = ntohs(ipha->ipha_length);
7059 
7060 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
7061 		/*
7062 		 * Most likely a keepalive for the benefit of an intervening
7063 		 * NAT.  These aren't for us, per se, so drop it.
7064 		 *
7065 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
7066 		 * byte packets (keepalives are 1-byte), but we'll drop them
7067 		 * also.
7068 		 */
7069 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7070 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7071 		return (B_FALSE);
7072 	}
7073 
7074 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7075 		/* might as well pull it all up - it might be ESP. */
7076 		if (!pullupmsg(mp, -1)) {
7077 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7078 			    DROPPER(ipss, ipds_esp_nomem),
7079 			    &ipss->ipsec_dropper);
7080 			return (B_FALSE);
7081 		}
7082 
7083 		ipha = (ipha_t *)mp->b_rptr;
7084 	}
7085 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7086 	if (*spi == 0) {
7087 		/* UDP packet - remove 0-spi. */
7088 		shift = sizeof (uint32_t);
7089 	} else {
7090 		/* ESP-in-UDP packet - reduce to ESP. */
7091 		ipha->ipha_protocol = IPPROTO_ESP;
7092 		shift = sizeof (udpha_t);
7093 	}
7094 
7095 	/* Fix IP header */
7096 	ipha->ipha_length = htons(plen - shift);
7097 	ipha->ipha_hdr_checksum = 0;
7098 
7099 	orptr = mp->b_rptr;
7100 	mp->b_rptr += shift;
7101 
7102 	udpha = (udpha_t *)(orptr + iph_len);
7103 	if (*spi == 0) {
7104 		ASSERT((uint8_t *)ipha == orptr);
7105 		udpha->uha_length = htons(plen - shift - iph_len);
7106 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7107 		esp_ports = 0;
7108 	} else {
7109 		esp_ports = *((uint32_t *)udpha);
7110 		ASSERT(esp_ports != 0);
7111 	}
7112 	ovbcopy(orptr, orptr + shift, iph_len);
7113 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
7114 		ipha = (ipha_t *)(orptr + shift);
7115 
7116 		free_ire = (ire == NULL);
7117 		if (free_ire) {
7118 			/* Re-acquire ire. */
7119 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7120 			    ipss->ipsec_netstack->netstack_ip);
7121 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7122 				if (ire != NULL)
7123 					ire_refrele(ire);
7124 				/*
7125 				 * Do a regular freemsg(), as this is an IP
7126 				 * error (no local route) not an IPsec one.
7127 				 */
7128 				freemsg(mp);
7129 			}
7130 		}
7131 
7132 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
7133 		if (free_ire)
7134 			ire_refrele(ire);
7135 	}
7136 
7137 	return (esp_ports == 0);
7138 }
7139 
7140 /*
7141  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7142  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7143  * Caller is responsible for dropping references to the conn, and freeing
7144  * first_mp.
7145  *
7146  * IPQoS Notes
7147  * Before sending it to the client, invoke IPPF processing. Policy processing
7148  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7149  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7150  * ip_wput_local, ip_policy is false.
7151  */
7152 static void
7153 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7154     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7155     boolean_t ip_policy)
7156 {
7157 	boolean_t	mctl_present = (first_mp != NULL);
7158 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7159 	uint32_t	ill_index;
7160 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7161 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7162 
7163 	ASSERT(ill != NULL);
7164 
7165 	if (mctl_present)
7166 		first_mp->b_cont = mp;
7167 	else
7168 		first_mp = mp;
7169 
7170 	if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
7171 	    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
7172 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7173 		freemsg(first_mp);
7174 		return;
7175 	}
7176 
7177 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7178 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7179 		    NULL, mctl_present);
7180 		/* Freed by ipsec_check_inbound_policy(). */
7181 		if (first_mp == NULL) {
7182 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7183 			return;
7184 		}
7185 	}
7186 	if (mctl_present)
7187 		freeb(first_mp);
7188 
7189 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7190 	if (connp->conn_udp->udp_nat_t_endpoint) {
7191 		if (mctl_present) {
7192 			/* mctl_present *shouldn't* happen. */
7193 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7194 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7195 			    &ipss->ipsec_dropper);
7196 			return;
7197 		}
7198 
7199 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7200 			return;
7201 	}
7202 
7203 	/* Handle options. */
7204 	if (connp->conn_recvif)
7205 		in_flags = IPF_RECVIF;
7206 	/*
7207 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7208 	 * passed to ip_add_info is based on IP version of connp.
7209 	 */
7210 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7211 		if (connp->conn_af_isv6) {
7212 			/*
7213 			 * V6 only needs index
7214 			 */
7215 			in_flags |= IPF_RECVIF;
7216 		} else {
7217 			/*
7218 			 * V4 needs index + matching address.
7219 			 */
7220 			in_flags |= IPF_RECVADDR;
7221 		}
7222 	}
7223 
7224 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7225 		in_flags |= IPF_RECVSLLA;
7226 
7227 	/*
7228 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7229 	 * freed if the packet is dropped. The caller will do so.
7230 	 */
7231 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7232 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7233 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7234 		if (mp == NULL) {
7235 			return;
7236 		}
7237 	}
7238 	if ((in_flags != 0) &&
7239 	    (mp->b_datap->db_type != M_CTL)) {
7240 		/*
7241 		 * The actual data will be contained in b_cont
7242 		 * upon successful return of the following call
7243 		 * else original mblk is returned
7244 		 */
7245 		ASSERT(recv_ill != NULL);
7246 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7247 		    ipst);
7248 	}
7249 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7250 	/* Send it upstream */
7251 	(connp->conn_recv)(connp, mp, NULL);
7252 }
7253 
7254 /*
7255  * Fanout for UDP packets.
7256  * The caller puts <fport, lport> in the ports parameter.
7257  *
7258  * If SO_REUSEADDR is set all multicast and broadcast packets
7259  * will be delivered to all streams bound to the same port.
7260  *
7261  * Zones notes:
7262  * Multicast and broadcast packets will be distributed to streams in all zones.
7263  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7264  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7265  * packets. To maintain this behavior with multiple zones, the conns are grouped
7266  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7267  * each zone. If unset, all the following conns in the same zone are skipped.
7268  */
7269 static void
7270 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7271     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7272     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7273 {
7274 	uint32_t	dstport, srcport;
7275 	ipaddr_t	dst;
7276 	mblk_t		*first_mp;
7277 	boolean_t	secure;
7278 	in6_addr_t	v6src;
7279 	conn_t		*connp;
7280 	connf_t		*connfp;
7281 	conn_t		*first_connp;
7282 	conn_t		*next_connp;
7283 	mblk_t		*mp1, *first_mp1;
7284 	ipaddr_t	src;
7285 	zoneid_t	last_zoneid;
7286 	boolean_t	reuseaddr;
7287 	boolean_t	shared_addr;
7288 	boolean_t	unlabeled;
7289 	ip_stack_t	*ipst;
7290 
7291 	ASSERT(recv_ill != NULL);
7292 	ipst = recv_ill->ill_ipst;
7293 
7294 	first_mp = mp;
7295 	if (mctl_present) {
7296 		mp = first_mp->b_cont;
7297 		first_mp->b_cont = NULL;
7298 		secure = ipsec_in_is_secure(first_mp);
7299 		ASSERT(mp != NULL);
7300 	} else {
7301 		first_mp = NULL;
7302 		secure = B_FALSE;
7303 	}
7304 
7305 	/* Extract ports in net byte order */
7306 	dstport = htons(ntohl(ports) & 0xFFFF);
7307 	srcport = htons(ntohl(ports) >> 16);
7308 	dst = ipha->ipha_dst;
7309 	src = ipha->ipha_src;
7310 
7311 	unlabeled = B_FALSE;
7312 	if (is_system_labeled())
7313 		/* Cred cannot be null on IPv4 */
7314 		unlabeled = (msg_getlabel(mp)->tsl_flags &
7315 		    TSLF_UNLABELED) != 0;
7316 	shared_addr = (zoneid == ALL_ZONES);
7317 	if (shared_addr) {
7318 		/*
7319 		 * No need to handle exclusive-stack zones since ALL_ZONES
7320 		 * only applies to the shared stack.
7321 		 */
7322 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7323 		/*
7324 		 * If no shared MLP is found, tsol_mlp_findzone returns
7325 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7326 		 * search for the zone based on the packet label.
7327 		 *
7328 		 * If there is such a zone, we prefer to find a
7329 		 * connection in it.  Otherwise, we look for a
7330 		 * MAC-exempt connection in any zone whose label
7331 		 * dominates the default label on the packet.
7332 		 */
7333 		if (zoneid == ALL_ZONES)
7334 			zoneid = tsol_packet_to_zoneid(mp);
7335 		else
7336 			unlabeled = B_FALSE;
7337 	}
7338 
7339 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7340 	mutex_enter(&connfp->connf_lock);
7341 	connp = connfp->connf_head;
7342 	if (!broadcast && !CLASSD(dst)) {
7343 		/*
7344 		 * Not broadcast or multicast. Send to the one (first)
7345 		 * client we find. No need to check conn_wantpacket()
7346 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7347 		 * IPv4 unicast packets.
7348 		 */
7349 		while ((connp != NULL) &&
7350 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7351 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7352 		    !(unlabeled && connp->conn_mac_exempt && shared_addr)))) {
7353 			/*
7354 			 * We keep searching since the conn did not match,
7355 			 * or its zone did not match and it is not either
7356 			 * an allzones conn or a mac exempt conn (if the
7357 			 * sender is unlabeled.)
7358 			 */
7359 			connp = connp->conn_next;
7360 		}
7361 
7362 		if (connp == NULL ||
7363 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7364 			goto notfound;
7365 
7366 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7367 
7368 		if (is_system_labeled() &&
7369 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7370 		    connp))
7371 			goto notfound;
7372 
7373 		CONN_INC_REF(connp);
7374 		mutex_exit(&connfp->connf_lock);
7375 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7376 		    flags, recv_ill, ip_policy);
7377 		IP_STAT(ipst, ip_udp_fannorm);
7378 		CONN_DEC_REF(connp);
7379 		return;
7380 	}
7381 
7382 	/*
7383 	 * Broadcast and multicast case
7384 	 *
7385 	 * Need to check conn_wantpacket().
7386 	 * If SO_REUSEADDR has been set on the first we send the
7387 	 * packet to all clients that have joined the group and
7388 	 * match the port.
7389 	 */
7390 
7391 	while (connp != NULL) {
7392 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7393 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7394 		    (!is_system_labeled() ||
7395 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7396 		    connp)))
7397 			break;
7398 		connp = connp->conn_next;
7399 	}
7400 
7401 	if (connp == NULL ||
7402 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL)
7403 		goto notfound;
7404 
7405 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7406 
7407 	first_connp = connp;
7408 	/*
7409 	 * When SO_REUSEADDR is not set, send the packet only to the first
7410 	 * matching connection in its zone by keeping track of the zoneid.
7411 	 */
7412 	reuseaddr = first_connp->conn_reuseaddr;
7413 	last_zoneid = first_connp->conn_zoneid;
7414 
7415 	CONN_INC_REF(connp);
7416 	connp = connp->conn_next;
7417 	for (;;) {
7418 		while (connp != NULL) {
7419 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7420 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7421 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7422 			    (!is_system_labeled() ||
7423 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7424 			    shared_addr, connp)))
7425 				break;
7426 			connp = connp->conn_next;
7427 		}
7428 		/*
7429 		 * Just copy the data part alone. The mctl part is
7430 		 * needed just for verifying policy and it is never
7431 		 * sent up.
7432 		 */
7433 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7434 		    ((mp1 = copymsg(mp)) == NULL))) {
7435 			/*
7436 			 * No more interested clients or memory
7437 			 * allocation failed
7438 			 */
7439 			connp = first_connp;
7440 			break;
7441 		}
7442 		if (connp->conn_zoneid != last_zoneid) {
7443 			/*
7444 			 * Update the zoneid so that the packet isn't sent to
7445 			 * any more conns in the same zone unless SO_REUSEADDR
7446 			 * is set.
7447 			 */
7448 			reuseaddr = connp->conn_reuseaddr;
7449 			last_zoneid = connp->conn_zoneid;
7450 		}
7451 		if (first_mp != NULL) {
7452 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7453 			    ipsec_info_type == IPSEC_IN);
7454 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7455 			    ipst->ips_netstack);
7456 			if (first_mp1 == NULL) {
7457 				freemsg(mp1);
7458 				connp = first_connp;
7459 				break;
7460 			}
7461 		} else {
7462 			first_mp1 = NULL;
7463 		}
7464 		CONN_INC_REF(connp);
7465 		mutex_exit(&connfp->connf_lock);
7466 		/*
7467 		 * IPQoS notes: We don't send the packet for policy
7468 		 * processing here, will do it for the last one (below).
7469 		 * i.e. we do it per-packet now, but if we do policy
7470 		 * processing per-conn, then we would need to do it
7471 		 * here too.
7472 		 */
7473 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7474 		    ipha, flags, recv_ill, B_FALSE);
7475 		mutex_enter(&connfp->connf_lock);
7476 		/* Follow the next pointer before releasing the conn. */
7477 		next_connp = connp->conn_next;
7478 		IP_STAT(ipst, ip_udp_fanmb);
7479 		CONN_DEC_REF(connp);
7480 		connp = next_connp;
7481 	}
7482 
7483 	/* Last one.  Send it upstream. */
7484 	mutex_exit(&connfp->connf_lock);
7485 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7486 	    recv_ill, ip_policy);
7487 	IP_STAT(ipst, ip_udp_fanmb);
7488 	CONN_DEC_REF(connp);
7489 	return;
7490 
7491 notfound:
7492 
7493 	mutex_exit(&connfp->connf_lock);
7494 	IP_STAT(ipst, ip_udp_fanothers);
7495 	/*
7496 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7497 	 * have already been matched above, since they live in the IPv4
7498 	 * fanout tables. This implies we only need to
7499 	 * check for IPv6 in6addr_any endpoints here.
7500 	 * Thus we compare using ipv6_all_zeros instead of the destination
7501 	 * address, except for the multicast group membership lookup which
7502 	 * uses the IPv4 destination.
7503 	 */
7504 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7505 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7506 	mutex_enter(&connfp->connf_lock);
7507 	connp = connfp->connf_head;
7508 	if (!broadcast && !CLASSD(dst)) {
7509 		while (connp != NULL) {
7510 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7511 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7512 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7513 			    !connp->conn_ipv6_v6only)
7514 				break;
7515 			connp = connp->conn_next;
7516 		}
7517 
7518 		if (connp != NULL && is_system_labeled() &&
7519 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7520 		    connp))
7521 			connp = NULL;
7522 
7523 		if (connp == NULL ||
7524 		    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7525 			/*
7526 			 * No one bound to this port.  Is
7527 			 * there a client that wants all
7528 			 * unclaimed datagrams?
7529 			 */
7530 			mutex_exit(&connfp->connf_lock);
7531 
7532 			if (mctl_present)
7533 				first_mp->b_cont = mp;
7534 			else
7535 				first_mp = mp;
7536 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7537 			    connf_head != NULL) {
7538 				ip_fanout_proto(q, first_mp, ill, ipha,
7539 				    flags | IP_FF_RAWIP, mctl_present,
7540 				    ip_policy, recv_ill, zoneid);
7541 			} else {
7542 				if (ip_fanout_send_icmp(q, first_mp, flags,
7543 				    ICMP_DEST_UNREACHABLE,
7544 				    ICMP_PORT_UNREACHABLE,
7545 				    mctl_present, zoneid, ipst)) {
7546 					BUMP_MIB(ill->ill_ip_mib,
7547 					    udpIfStatsNoPorts);
7548 				}
7549 			}
7550 			return;
7551 		}
7552 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7553 
7554 		CONN_INC_REF(connp);
7555 		mutex_exit(&connfp->connf_lock);
7556 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7557 		    flags, recv_ill, ip_policy);
7558 		CONN_DEC_REF(connp);
7559 		return;
7560 	}
7561 	/*
7562 	 * IPv4 multicast packet being delivered to an AF_INET6
7563 	 * in6addr_any endpoint.
7564 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7565 	 * and not conn_wantpacket_v6() since any multicast membership is
7566 	 * for an IPv4-mapped multicast address.
7567 	 * The packet is sent to all clients in all zones that have joined the
7568 	 * group and match the port.
7569 	 */
7570 	while (connp != NULL) {
7571 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7572 		    srcport, v6src) &&
7573 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7574 		    (!is_system_labeled() ||
7575 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7576 		    connp)))
7577 			break;
7578 		connp = connp->conn_next;
7579 	}
7580 
7581 	if (connp == NULL ||
7582 	    !IPCL_IS_NONSTR(connp) && connp->conn_upq == NULL) {
7583 		/*
7584 		 * No one bound to this port.  Is
7585 		 * there a client that wants all
7586 		 * unclaimed datagrams?
7587 		 */
7588 		mutex_exit(&connfp->connf_lock);
7589 
7590 		if (mctl_present)
7591 			first_mp->b_cont = mp;
7592 		else
7593 			first_mp = mp;
7594 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7595 		    NULL) {
7596 			ip_fanout_proto(q, first_mp, ill, ipha,
7597 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7598 			    recv_ill, zoneid);
7599 		} else {
7600 			/*
7601 			 * We used to attempt to send an icmp error here, but
7602 			 * since this is known to be a multicast packet
7603 			 * and we don't send icmp errors in response to
7604 			 * multicast, just drop the packet and give up sooner.
7605 			 */
7606 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7607 			freemsg(first_mp);
7608 		}
7609 		return;
7610 	}
7611 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
7612 
7613 	first_connp = connp;
7614 
7615 	CONN_INC_REF(connp);
7616 	connp = connp->conn_next;
7617 	for (;;) {
7618 		while (connp != NULL) {
7619 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7620 			    ipv6_all_zeros, srcport, v6src) &&
7621 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7622 			    (!is_system_labeled() ||
7623 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7624 			    shared_addr, connp)))
7625 				break;
7626 			connp = connp->conn_next;
7627 		}
7628 		/*
7629 		 * Just copy the data part alone. The mctl part is
7630 		 * needed just for verifying policy and it is never
7631 		 * sent up.
7632 		 */
7633 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7634 		    ((mp1 = copymsg(mp)) == NULL))) {
7635 			/*
7636 			 * No more intested clients or memory
7637 			 * allocation failed
7638 			 */
7639 			connp = first_connp;
7640 			break;
7641 		}
7642 		if (first_mp != NULL) {
7643 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7644 			    ipsec_info_type == IPSEC_IN);
7645 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7646 			    ipst->ips_netstack);
7647 			if (first_mp1 == NULL) {
7648 				freemsg(mp1);
7649 				connp = first_connp;
7650 				break;
7651 			}
7652 		} else {
7653 			first_mp1 = NULL;
7654 		}
7655 		CONN_INC_REF(connp);
7656 		mutex_exit(&connfp->connf_lock);
7657 		/*
7658 		 * IPQoS notes: We don't send the packet for policy
7659 		 * processing here, will do it for the last one (below).
7660 		 * i.e. we do it per-packet now, but if we do policy
7661 		 * processing per-conn, then we would need to do it
7662 		 * here too.
7663 		 */
7664 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7665 		    ipha, flags, recv_ill, B_FALSE);
7666 		mutex_enter(&connfp->connf_lock);
7667 		/* Follow the next pointer before releasing the conn. */
7668 		next_connp = connp->conn_next;
7669 		CONN_DEC_REF(connp);
7670 		connp = next_connp;
7671 	}
7672 
7673 	/* Last one.  Send it upstream. */
7674 	mutex_exit(&connfp->connf_lock);
7675 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7676 	    recv_ill, ip_policy);
7677 	CONN_DEC_REF(connp);
7678 }
7679 
7680 /*
7681  * Complete the ip_wput header so that it
7682  * is possible to generate ICMP
7683  * errors.
7684  */
7685 int
7686 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7687 {
7688 	ire_t *ire;
7689 
7690 	if (ipha->ipha_src == INADDR_ANY) {
7691 		ire = ire_lookup_local(zoneid, ipst);
7692 		if (ire == NULL) {
7693 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7694 			return (1);
7695 		}
7696 		ipha->ipha_src = ire->ire_addr;
7697 		ire_refrele(ire);
7698 	}
7699 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7700 	ipha->ipha_hdr_checksum = 0;
7701 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7702 	return (0);
7703 }
7704 
7705 /*
7706  * Nobody should be sending
7707  * packets up this stream
7708  */
7709 static void
7710 ip_lrput(queue_t *q, mblk_t *mp)
7711 {
7712 	mblk_t *mp1;
7713 
7714 	switch (mp->b_datap->db_type) {
7715 	case M_FLUSH:
7716 		/* Turn around */
7717 		if (*mp->b_rptr & FLUSHW) {
7718 			*mp->b_rptr &= ~FLUSHR;
7719 			qreply(q, mp);
7720 			return;
7721 		}
7722 		break;
7723 	}
7724 	/* Could receive messages that passed through ar_rput */
7725 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7726 		mp1->b_prev = mp1->b_next = NULL;
7727 	freemsg(mp);
7728 }
7729 
7730 /* Nobody should be sending packets down this stream */
7731 /* ARGSUSED */
7732 void
7733 ip_lwput(queue_t *q, mblk_t *mp)
7734 {
7735 	freemsg(mp);
7736 }
7737 
7738 /*
7739  * Move the first hop in any source route to ipha_dst and remove that part of
7740  * the source route.  Called by other protocols.  Errors in option formatting
7741  * are ignored - will be handled by ip_wput_options Return the final
7742  * destination (either ipha_dst or the last entry in a source route.)
7743  */
7744 ipaddr_t
7745 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7746 {
7747 	ipoptp_t	opts;
7748 	uchar_t		*opt;
7749 	uint8_t		optval;
7750 	uint8_t		optlen;
7751 	ipaddr_t	dst;
7752 	int		i;
7753 	ire_t		*ire;
7754 	ip_stack_t	*ipst = ns->netstack_ip;
7755 
7756 	ip2dbg(("ip_massage_options\n"));
7757 	dst = ipha->ipha_dst;
7758 	for (optval = ipoptp_first(&opts, ipha);
7759 	    optval != IPOPT_EOL;
7760 	    optval = ipoptp_next(&opts)) {
7761 		opt = opts.ipoptp_cur;
7762 		switch (optval) {
7763 			uint8_t off;
7764 		case IPOPT_SSRR:
7765 		case IPOPT_LSRR:
7766 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7767 				ip1dbg(("ip_massage_options: bad src route\n"));
7768 				break;
7769 			}
7770 			optlen = opts.ipoptp_len;
7771 			off = opt[IPOPT_OFFSET];
7772 			off--;
7773 		redo_srr:
7774 			if (optlen < IP_ADDR_LEN ||
7775 			    off > optlen - IP_ADDR_LEN) {
7776 				/* End of source route */
7777 				ip1dbg(("ip_massage_options: end of SR\n"));
7778 				break;
7779 			}
7780 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7781 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7782 			    ntohl(dst)));
7783 			/*
7784 			 * Check if our address is present more than
7785 			 * once as consecutive hops in source route.
7786 			 * XXX verify per-interface ip_forwarding
7787 			 * for source route?
7788 			 */
7789 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7790 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7791 			if (ire != NULL) {
7792 				ire_refrele(ire);
7793 				off += IP_ADDR_LEN;
7794 				goto redo_srr;
7795 			}
7796 			if (dst == htonl(INADDR_LOOPBACK)) {
7797 				ip1dbg(("ip_massage_options: loopback addr in "
7798 				    "source route!\n"));
7799 				break;
7800 			}
7801 			/*
7802 			 * Update ipha_dst to be the first hop and remove the
7803 			 * first hop from the source route (by overwriting
7804 			 * part of the option with NOP options).
7805 			 */
7806 			ipha->ipha_dst = dst;
7807 			/* Put the last entry in dst */
7808 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7809 			    3;
7810 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7811 
7812 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7813 			    ntohl(dst)));
7814 			/* Move down and overwrite */
7815 			opt[IP_ADDR_LEN] = opt[0];
7816 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7817 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7818 			for (i = 0; i < IP_ADDR_LEN; i++)
7819 				opt[i] = IPOPT_NOP;
7820 			break;
7821 		}
7822 	}
7823 	return (dst);
7824 }
7825 
7826 /*
7827  * Return the network mask
7828  * associated with the specified address.
7829  */
7830 ipaddr_t
7831 ip_net_mask(ipaddr_t addr)
7832 {
7833 	uchar_t	*up = (uchar_t *)&addr;
7834 	ipaddr_t mask = 0;
7835 	uchar_t	*maskp = (uchar_t *)&mask;
7836 
7837 #if defined(__i386) || defined(__amd64)
7838 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7839 #endif
7840 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7841 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7842 #endif
7843 	if (CLASSD(addr)) {
7844 		maskp[0] = 0xF0;
7845 		return (mask);
7846 	}
7847 
7848 	/* We assume Class E default netmask to be 32 */
7849 	if (CLASSE(addr))
7850 		return (0xffffffffU);
7851 
7852 	if (addr == 0)
7853 		return (0);
7854 	maskp[0] = 0xFF;
7855 	if ((up[0] & 0x80) == 0)
7856 		return (mask);
7857 
7858 	maskp[1] = 0xFF;
7859 	if ((up[0] & 0xC0) == 0x80)
7860 		return (mask);
7861 
7862 	maskp[2] = 0xFF;
7863 	if ((up[0] & 0xE0) == 0xC0)
7864 		return (mask);
7865 
7866 	/* Otherwise return no mask */
7867 	return ((ipaddr_t)0);
7868 }
7869 
7870 /*
7871  * Helper ill lookup function used by IPsec.
7872  */
7873 ill_t *
7874 ip_grab_ill(mblk_t *first_mp, int ifindex, boolean_t isv6, ip_stack_t *ipst)
7875 {
7876 	ill_t *ret_ill;
7877 
7878 	ASSERT(ifindex != 0);
7879 
7880 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7881 	    ipst);
7882 	if (ret_ill == NULL) {
7883 		if (isv6) {
7884 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
7885 			ip1dbg(("ip_grab_ill (IPv6): bad ifindex %d.\n",
7886 			    ifindex));
7887 		} else {
7888 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
7889 			ip1dbg(("ip_grab_ill (IPv4): bad ifindex %d.\n",
7890 			    ifindex));
7891 		}
7892 		freemsg(first_mp);
7893 		return (NULL);
7894 	}
7895 	return (ret_ill);
7896 }
7897 
7898 /*
7899  * IPv4 -
7900  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7901  * out a packet to a destination address for which we do not have specific
7902  * (or sufficient) routing information.
7903  *
7904  * NOTE : These are the scopes of some of the variables that point at IRE,
7905  *	  which needs to be followed while making any future modifications
7906  *	  to avoid memory leaks.
7907  *
7908  *	- ire and sire are the entries looked up initially by
7909  *	  ire_ftable_lookup.
7910  *	- ipif_ire is used to hold the interface ire associated with
7911  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7912  *	  it before branching out to error paths.
7913  *	- save_ire is initialized before ire_create, so that ire returned
7914  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7915  *	  before breaking out of the switch.
7916  *
7917  *	Thus on failures, we have to REFRELE only ire and sire, if they
7918  *	are not NULL.
7919  */
7920 void
7921 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7922     zoneid_t zoneid, ip_stack_t *ipst)
7923 {
7924 	areq_t	*areq;
7925 	ipaddr_t gw = 0;
7926 	ire_t	*ire = NULL;
7927 	mblk_t	*res_mp;
7928 	ipaddr_t *addrp;
7929 	ipaddr_t nexthop_addr;
7930 	ipif_t  *src_ipif = NULL;
7931 	ill_t	*dst_ill = NULL;
7932 	ipha_t  *ipha;
7933 	ire_t	*sire = NULL;
7934 	mblk_t	*first_mp;
7935 	ire_t	*save_ire;
7936 	ushort_t ire_marks = 0;
7937 	boolean_t mctl_present;
7938 	ipsec_out_t *io;
7939 	mblk_t	*saved_mp;
7940 	ire_t	*first_sire = NULL;
7941 	mblk_t	*copy_mp = NULL;
7942 	mblk_t	*xmit_mp = NULL;
7943 	ipaddr_t save_dst;
7944 	uint32_t multirt_flags =
7945 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7946 	boolean_t multirt_is_resolvable;
7947 	boolean_t multirt_resolve_next;
7948 	boolean_t unspec_src;
7949 	boolean_t ip_nexthop = B_FALSE;
7950 	tsol_ire_gw_secattr_t *attrp = NULL;
7951 	tsol_gcgrp_t *gcgrp = NULL;
7952 	tsol_gcgrp_addr_t ga;
7953 
7954 	if (ip_debug > 2) {
7955 		/* ip1dbg */
7956 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7957 	}
7958 
7959 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7960 	if (mctl_present) {
7961 		io = (ipsec_out_t *)first_mp->b_rptr;
7962 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7963 		ASSERT(zoneid == io->ipsec_out_zoneid);
7964 		ASSERT(zoneid != ALL_ZONES);
7965 	}
7966 
7967 	ipha = (ipha_t *)mp->b_rptr;
7968 
7969 	/* All multicast lookups come through ip_newroute_ipif() */
7970 	if (CLASSD(dst)) {
7971 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7972 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7973 		freemsg(first_mp);
7974 		return;
7975 	}
7976 
7977 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7978 		ip_nexthop = B_TRUE;
7979 		nexthop_addr = io->ipsec_out_nexthop_addr;
7980 	}
7981 	/*
7982 	 * If this IRE is created for forwarding or it is not for
7983 	 * traffic for congestion controlled protocols, mark it as temporary.
7984 	 */
7985 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7986 		ire_marks |= IRE_MARK_TEMPORARY;
7987 
7988 	/*
7989 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7990 	 * chain until it gets the most specific information available.
7991 	 * For example, we know that there is no IRE_CACHE for this dest,
7992 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7993 	 * ire_ftable_lookup will look up the gateway, etc.
7994 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7995 	 * to the destination, of equal netmask length in the forward table,
7996 	 * will be recursively explored. If no information is available
7997 	 * for the final gateway of that route, we force the returned ire
7998 	 * to be equal to sire using MATCH_IRE_PARENT.
7999 	 * At least, in this case we have a starting point (in the buckets)
8000 	 * to look for other routes to the destination in the forward table.
8001 	 * This is actually used only for multirouting, where a list
8002 	 * of routes has to be processed in sequence.
8003 	 *
8004 	 * In the process of coming up with the most specific information,
8005 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8006 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8007 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8008 	 * Two caveats when handling incomplete ire's in ip_newroute:
8009 	 * - we should be careful when accessing its ire_nce (specifically
8010 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8011 	 * - not all legacy code path callers are prepared to handle
8012 	 *   incomplete ire's, so we should not create/add incomplete
8013 	 *   ire_cache entries here. (See discussion about temporary solution
8014 	 *   further below).
8015 	 *
8016 	 * In order to minimize packet dropping, and to preserve existing
8017 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8018 	 * gateway, and instead use the IF_RESOLVER ire to send out
8019 	 * another request to ARP (this is achieved by passing the
8020 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8021 	 * arp response comes back in ip_wput_nondata, we will create
8022 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8023 	 *
8024 	 * Note that this is a temporary solution; the correct solution is
8025 	 * to create an incomplete  per-dst ire_cache entry, and send the
8026 	 * packet out when the gw's nce is resolved. In order to achieve this,
8027 	 * all packet processing must have been completed prior to calling
8028 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8029 	 * to be modified to accomodate this solution.
8030 	 */
8031 	if (ip_nexthop) {
8032 		/*
8033 		 * The first time we come here, we look for an IRE_INTERFACE
8034 		 * entry for the specified nexthop, set the dst to be the
8035 		 * nexthop address and create an IRE_CACHE entry for the
8036 		 * nexthop. The next time around, we are able to find an
8037 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8038 		 * nexthop address and create an IRE_CACHE entry for the
8039 		 * destination address via the specified nexthop.
8040 		 */
8041 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8042 		    msg_getlabel(mp), ipst);
8043 		if (ire != NULL) {
8044 			gw = nexthop_addr;
8045 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8046 		} else {
8047 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8048 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8049 			    msg_getlabel(mp),
8050 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8051 			    ipst);
8052 			if (ire != NULL) {
8053 				dst = nexthop_addr;
8054 			}
8055 		}
8056 	} else {
8057 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8058 		    NULL, &sire, zoneid, 0, msg_getlabel(mp),
8059 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8060 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8061 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8062 		    ipst);
8063 	}
8064 
8065 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8066 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8067 
8068 	/*
8069 	 * This loop is run only once in most cases.
8070 	 * We loop to resolve further routes only when the destination
8071 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8072 	 */
8073 	do {
8074 		/* Clear the previous iteration's values */
8075 		if (src_ipif != NULL) {
8076 			ipif_refrele(src_ipif);
8077 			src_ipif = NULL;
8078 		}
8079 		if (dst_ill != NULL) {
8080 			ill_refrele(dst_ill);
8081 			dst_ill = NULL;
8082 		}
8083 
8084 		multirt_resolve_next = B_FALSE;
8085 		/*
8086 		 * We check if packets have to be multirouted.
8087 		 * In this case, given the current <ire, sire> couple,
8088 		 * we look for the next suitable <ire, sire>.
8089 		 * This check is done in ire_multirt_lookup(),
8090 		 * which applies various criteria to find the next route
8091 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8092 		 * unchanged if it detects it has not been tried yet.
8093 		 */
8094 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8095 			ip3dbg(("ip_newroute: starting next_resolution "
8096 			    "with first_mp %p, tag %d\n",
8097 			    (void *)first_mp,
8098 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8099 
8100 			ASSERT(sire != NULL);
8101 			multirt_is_resolvable =
8102 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8103 			    msg_getlabel(mp), ipst);
8104 
8105 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8106 			    "ire %p, sire %p\n",
8107 			    multirt_is_resolvable,
8108 			    (void *)ire, (void *)sire));
8109 
8110 			if (!multirt_is_resolvable) {
8111 				/*
8112 				 * No more multirt route to resolve; give up
8113 				 * (all routes resolved or no more
8114 				 * resolvable routes).
8115 				 */
8116 				if (ire != NULL) {
8117 					ire_refrele(ire);
8118 					ire = NULL;
8119 				}
8120 			} else {
8121 				ASSERT(sire != NULL);
8122 				ASSERT(ire != NULL);
8123 				/*
8124 				 * We simply use first_sire as a flag that
8125 				 * indicates if a resolvable multirt route
8126 				 * has already been found.
8127 				 * If it is not the case, we may have to send
8128 				 * an ICMP error to report that the
8129 				 * destination is unreachable.
8130 				 * We do not IRE_REFHOLD first_sire.
8131 				 */
8132 				if (first_sire == NULL) {
8133 					first_sire = sire;
8134 				}
8135 			}
8136 		}
8137 		if (ire == NULL) {
8138 			if (ip_debug > 3) {
8139 				/* ip2dbg */
8140 				pr_addr_dbg("ip_newroute: "
8141 				    "can't resolve %s\n", AF_INET, &dst);
8142 			}
8143 			ip3dbg(("ip_newroute: "
8144 			    "ire %p, sire %p, first_sire %p\n",
8145 			    (void *)ire, (void *)sire, (void *)first_sire));
8146 
8147 			if (sire != NULL) {
8148 				ire_refrele(sire);
8149 				sire = NULL;
8150 			}
8151 
8152 			if (first_sire != NULL) {
8153 				/*
8154 				 * At least one multirt route has been found
8155 				 * in the same call to ip_newroute();
8156 				 * there is no need to report an ICMP error.
8157 				 * first_sire was not IRE_REFHOLDed.
8158 				 */
8159 				MULTIRT_DEBUG_UNTAG(first_mp);
8160 				freemsg(first_mp);
8161 				return;
8162 			}
8163 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8164 			    RTA_DST, ipst);
8165 			goto icmp_err_ret;
8166 		}
8167 
8168 		/*
8169 		 * Verify that the returned IRE does not have either
8170 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8171 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8172 		 */
8173 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8174 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8175 			goto icmp_err_ret;
8176 		}
8177 		/*
8178 		 * Increment the ire_ob_pkt_count field for ire if it is an
8179 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8180 		 * increment the same for the parent IRE, sire, if it is some
8181 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8182 		 */
8183 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8184 			UPDATE_OB_PKT_COUNT(ire);
8185 			ire->ire_last_used_time = lbolt;
8186 		}
8187 
8188 		if (sire != NULL) {
8189 			gw = sire->ire_gateway_addr;
8190 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8191 			    IRE_INTERFACE)) == 0);
8192 			UPDATE_OB_PKT_COUNT(sire);
8193 			sire->ire_last_used_time = lbolt;
8194 		}
8195 		/*
8196 		 * We have a route to reach the destination.  Find the
8197 		 * appropriate ill, then get a source address using
8198 		 * ipif_select_source().
8199 		 *
8200 		 * If we are here trying to create an IRE_CACHE for an offlink
8201 		 * destination and have an IRE_CACHE entry for VNI, then use
8202 		 * ire_stq instead since VNI's queue is a black hole.
8203 		 */
8204 		if ((ire->ire_type == IRE_CACHE) &&
8205 		    IS_VNI(ire->ire_ipif->ipif_ill)) {
8206 			dst_ill = ire->ire_stq->q_ptr;
8207 			ill_refhold(dst_ill);
8208 		} else {
8209 			ill_t *ill = ire->ire_ipif->ipif_ill;
8210 
8211 			if (IS_IPMP(ill)) {
8212 				dst_ill =
8213 				    ipmp_illgrp_hold_next_ill(ill->ill_grp);
8214 			} else {
8215 				dst_ill = ill;
8216 				ill_refhold(dst_ill);
8217 			}
8218 		}
8219 
8220 		if (dst_ill == NULL) {
8221 			if (ip_debug > 2) {
8222 				pr_addr_dbg("ip_newroute: no dst "
8223 				    "ill for dst %s\n", AF_INET, &dst);
8224 			}
8225 			goto icmp_err_ret;
8226 		}
8227 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8228 
8229 		/*
8230 		 * Pick the best source address from dst_ill.
8231 		 *
8232 		 * 1) Try to pick the source address from the destination
8233 		 *    route. Clustering assumes that when we have multiple
8234 		 *    prefixes hosted on an interface, the prefix of the
8235 		 *    source address matches the prefix of the destination
8236 		 *    route. We do this only if the address is not
8237 		 *    DEPRECATED.
8238 		 *
8239 		 * 2) If the conn is in a different zone than the ire, we
8240 		 *    need to pick a source address from the right zone.
8241 		 */
8242 		ASSERT(src_ipif == NULL);
8243 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8244 			/*
8245 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8246 			 * Check that the ipif matching the requested source
8247 			 * address still exists.
8248 			 */
8249 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8250 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8251 		}
8252 
8253 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8254 
8255 		if (src_ipif == NULL &&
8256 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8257 			ire_marks |= IRE_MARK_USESRC_CHECK;
8258 			if (!IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) &&
8259 			    IS_IPMP(ire->ire_ipif->ipif_ill) ||
8260 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8261 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8262 			    ire->ire_zoneid != ALL_ZONES) ||
8263 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8264 				/*
8265 				 * If the destination is reachable via a
8266 				 * given gateway, the selected source address
8267 				 * should be in the same subnet as the gateway.
8268 				 * Otherwise, the destination is not reachable.
8269 				 *
8270 				 * If there are no interfaces on the same subnet
8271 				 * as the destination, ipif_select_source gives
8272 				 * first non-deprecated interface which might be
8273 				 * on a different subnet than the gateway.
8274 				 * This is not desirable. Hence pass the dst_ire
8275 				 * source address to ipif_select_source.
8276 				 * It is sure that the destination is reachable
8277 				 * with the dst_ire source address subnet.
8278 				 * So passing dst_ire source address to
8279 				 * ipif_select_source will make sure that the
8280 				 * selected source will be on the same subnet
8281 				 * as dst_ire source address.
8282 				 */
8283 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8284 
8285 				src_ipif = ipif_select_source(dst_ill, saddr,
8286 				    zoneid);
8287 				if (src_ipif == NULL) {
8288 					if (ip_debug > 2) {
8289 						pr_addr_dbg("ip_newroute: "
8290 						    "no src for dst %s ",
8291 						    AF_INET, &dst);
8292 						printf("on interface %s\n",
8293 						    dst_ill->ill_name);
8294 					}
8295 					goto icmp_err_ret;
8296 				}
8297 			} else {
8298 				src_ipif = ire->ire_ipif;
8299 				ASSERT(src_ipif != NULL);
8300 				/* hold src_ipif for uniformity */
8301 				ipif_refhold(src_ipif);
8302 			}
8303 		}
8304 
8305 		/*
8306 		 * Assign a source address while we have the conn.
8307 		 * We can't have ip_wput_ire pick a source address when the
8308 		 * packet returns from arp since we need to look at
8309 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8310 		 * going through arp.
8311 		 *
8312 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8313 		 *	  it uses ip6i to store this information.
8314 		 */
8315 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8316 			ipha->ipha_src = src_ipif->ipif_src_addr;
8317 
8318 		if (ip_debug > 3) {
8319 			/* ip2dbg */
8320 			pr_addr_dbg("ip_newroute: first hop %s\n",
8321 			    AF_INET, &gw);
8322 		}
8323 		ip2dbg(("\tire type %s (%d)\n",
8324 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8325 
8326 		/*
8327 		 * The TTL of multirouted packets is bounded by the
8328 		 * ip_multirt_ttl ndd variable.
8329 		 */
8330 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8331 			/* Force TTL of multirouted packets */
8332 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8333 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8334 				ip2dbg(("ip_newroute: forcing multirt TTL "
8335 				    "to %d (was %d), dst 0x%08x\n",
8336 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8337 				    ntohl(sire->ire_addr)));
8338 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8339 			}
8340 		}
8341 		/*
8342 		 * At this point in ip_newroute(), ire is either the
8343 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8344 		 * destination or an IRE_INTERFACE type that should be used
8345 		 * to resolve an on-subnet destination or an on-subnet
8346 		 * next-hop gateway.
8347 		 *
8348 		 * In the IRE_CACHE case, we have the following :
8349 		 *
8350 		 * 1) src_ipif - used for getting a source address.
8351 		 *
8352 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8353 		 *    means packets using this IRE_CACHE will go out on
8354 		 *    dst_ill.
8355 		 *
8356 		 * 3) The IRE sire will point to the prefix that is the
8357 		 *    longest  matching route for the destination. These
8358 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8359 		 *
8360 		 *    The newly created IRE_CACHE entry for the off-subnet
8361 		 *    destination is tied to both the prefix route and the
8362 		 *    interface route used to resolve the next-hop gateway
8363 		 *    via the ire_phandle and ire_ihandle fields,
8364 		 *    respectively.
8365 		 *
8366 		 * In the IRE_INTERFACE case, we have the following :
8367 		 *
8368 		 * 1) src_ipif - used for getting a source address.
8369 		 *
8370 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8371 		 *    means packets using the IRE_CACHE that we will build
8372 		 *    here will go out on dst_ill.
8373 		 *
8374 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8375 		 *    to be created will only be tied to the IRE_INTERFACE
8376 		 *    that was derived from the ire_ihandle field.
8377 		 *
8378 		 *    If sire is non-NULL, it means the destination is
8379 		 *    off-link and we will first create the IRE_CACHE for the
8380 		 *    gateway. Next time through ip_newroute, we will create
8381 		 *    the IRE_CACHE for the final destination as described
8382 		 *    above.
8383 		 *
8384 		 * In both cases, after the current resolution has been
8385 		 * completed (or possibly initialised, in the IRE_INTERFACE
8386 		 * case), the loop may be re-entered to attempt the resolution
8387 		 * of another RTF_MULTIRT route.
8388 		 *
8389 		 * When an IRE_CACHE entry for the off-subnet destination is
8390 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8391 		 * for further processing in emission loops.
8392 		 */
8393 		save_ire = ire;
8394 		switch (ire->ire_type) {
8395 		case IRE_CACHE: {
8396 			ire_t	*ipif_ire;
8397 
8398 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8399 			if (gw == 0)
8400 				gw = ire->ire_gateway_addr;
8401 			/*
8402 			 * We need 3 ire's to create a new cache ire for an
8403 			 * off-link destination from the cache ire of the
8404 			 * gateway.
8405 			 *
8406 			 *	1. The prefix ire 'sire' (Note that this does
8407 			 *	   not apply to the conn_nexthop_set case)
8408 			 *	2. The cache ire of the gateway 'ire'
8409 			 *	3. The interface ire 'ipif_ire'
8410 			 *
8411 			 * We have (1) and (2). We lookup (3) below.
8412 			 *
8413 			 * If there is no interface route to the gateway,
8414 			 * it is a race condition, where we found the cache
8415 			 * but the interface route has been deleted.
8416 			 */
8417 			if (ip_nexthop) {
8418 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8419 			} else {
8420 				ipif_ire =
8421 				    ire_ihandle_lookup_offlink(ire, sire);
8422 			}
8423 			if (ipif_ire == NULL) {
8424 				ip1dbg(("ip_newroute: "
8425 				    "ire_ihandle_lookup_offlink failed\n"));
8426 				goto icmp_err_ret;
8427 			}
8428 
8429 			/*
8430 			 * Check cached gateway IRE for any security
8431 			 * attributes; if found, associate the gateway
8432 			 * credentials group to the destination IRE.
8433 			 */
8434 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8435 				mutex_enter(&attrp->igsa_lock);
8436 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8437 					GCGRP_REFHOLD(gcgrp);
8438 				mutex_exit(&attrp->igsa_lock);
8439 			}
8440 
8441 			/*
8442 			 * XXX For the source of the resolver mp,
8443 			 * we are using the same DL_UNITDATA_REQ
8444 			 * (from save_ire->ire_nce->nce_res_mp)
8445 			 * though the save_ire is not pointing at the same ill.
8446 			 * This is incorrect. We need to send it up to the
8447 			 * resolver to get the right res_mp. For ethernets
8448 			 * this may be okay (ill_type == DL_ETHER).
8449 			 */
8450 
8451 			ire = ire_create(
8452 			    (uchar_t *)&dst,		/* dest address */
8453 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8454 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8455 			    (uchar_t *)&gw,		/* gateway address */
8456 			    &save_ire->ire_max_frag,
8457 			    save_ire->ire_nce,		/* src nce */
8458 			    dst_ill->ill_rq,		/* recv-from queue */
8459 			    dst_ill->ill_wq,		/* send-to queue */
8460 			    IRE_CACHE,			/* IRE type */
8461 			    src_ipif,
8462 			    (sire != NULL) ?
8463 			    sire->ire_mask : 0, 	/* Parent mask */
8464 			    (sire != NULL) ?
8465 			    sire->ire_phandle : 0,	/* Parent handle */
8466 			    ipif_ire->ire_ihandle,	/* Interface handle */
8467 			    (sire != NULL) ? (sire->ire_flags &
8468 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8469 			    (sire != NULL) ?
8470 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8471 			    NULL,
8472 			    gcgrp,
8473 			    ipst);
8474 
8475 			if (ire == NULL) {
8476 				if (gcgrp != NULL) {
8477 					GCGRP_REFRELE(gcgrp);
8478 					gcgrp = NULL;
8479 				}
8480 				ire_refrele(ipif_ire);
8481 				ire_refrele(save_ire);
8482 				break;
8483 			}
8484 
8485 			/* reference now held by IRE */
8486 			gcgrp = NULL;
8487 
8488 			ire->ire_marks |= ire_marks;
8489 
8490 			/*
8491 			 * Prevent sire and ipif_ire from getting deleted.
8492 			 * The newly created ire is tied to both of them via
8493 			 * the phandle and ihandle respectively.
8494 			 */
8495 			if (sire != NULL) {
8496 				IRB_REFHOLD(sire->ire_bucket);
8497 				/* Has it been removed already ? */
8498 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8499 					IRB_REFRELE(sire->ire_bucket);
8500 					ire_refrele(ipif_ire);
8501 					ire_refrele(save_ire);
8502 					break;
8503 				}
8504 			}
8505 
8506 			IRB_REFHOLD(ipif_ire->ire_bucket);
8507 			/* Has it been removed already ? */
8508 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8509 				IRB_REFRELE(ipif_ire->ire_bucket);
8510 				if (sire != NULL)
8511 					IRB_REFRELE(sire->ire_bucket);
8512 				ire_refrele(ipif_ire);
8513 				ire_refrele(save_ire);
8514 				break;
8515 			}
8516 
8517 			xmit_mp = first_mp;
8518 			/*
8519 			 * In the case of multirouting, a copy
8520 			 * of the packet is done before its sending.
8521 			 * The copy is used to attempt another
8522 			 * route resolution, in a next loop.
8523 			 */
8524 			if (ire->ire_flags & RTF_MULTIRT) {
8525 				copy_mp = copymsg(first_mp);
8526 				if (copy_mp != NULL) {
8527 					xmit_mp = copy_mp;
8528 					MULTIRT_DEBUG_TAG(first_mp);
8529 				}
8530 			}
8531 
8532 			ire_add_then_send(q, ire, xmit_mp);
8533 			ire_refrele(save_ire);
8534 
8535 			/* Assert that sire is not deleted yet. */
8536 			if (sire != NULL) {
8537 				ASSERT(sire->ire_ptpn != NULL);
8538 				IRB_REFRELE(sire->ire_bucket);
8539 			}
8540 
8541 			/* Assert that ipif_ire is not deleted yet. */
8542 			ASSERT(ipif_ire->ire_ptpn != NULL);
8543 			IRB_REFRELE(ipif_ire->ire_bucket);
8544 			ire_refrele(ipif_ire);
8545 
8546 			/*
8547 			 * If copy_mp is not NULL, multirouting was
8548 			 * requested. We loop to initiate a next
8549 			 * route resolution attempt, starting from sire.
8550 			 */
8551 			if (copy_mp != NULL) {
8552 				/*
8553 				 * Search for the next unresolved
8554 				 * multirt route.
8555 				 */
8556 				copy_mp = NULL;
8557 				ipif_ire = NULL;
8558 				ire = NULL;
8559 				multirt_resolve_next = B_TRUE;
8560 				continue;
8561 			}
8562 			if (sire != NULL)
8563 				ire_refrele(sire);
8564 			ipif_refrele(src_ipif);
8565 			ill_refrele(dst_ill);
8566 			return;
8567 		}
8568 		case IRE_IF_NORESOLVER: {
8569 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8570 			    dst_ill->ill_resolver_mp == NULL) {
8571 				ip1dbg(("ip_newroute: dst_ill %p "
8572 				    "for IRE_IF_NORESOLVER ire %p has "
8573 				    "no ill_resolver_mp\n",
8574 				    (void *)dst_ill, (void *)ire));
8575 				break;
8576 			}
8577 
8578 			/*
8579 			 * TSol note: We are creating the ire cache for the
8580 			 * destination 'dst'. If 'dst' is offlink, going
8581 			 * through the first hop 'gw', the security attributes
8582 			 * of 'dst' must be set to point to the gateway
8583 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8584 			 * is possible that 'dst' is a potential gateway that is
8585 			 * referenced by some route that has some security
8586 			 * attributes. Thus in the former case, we need to do a
8587 			 * gcgrp_lookup of 'gw' while in the latter case we
8588 			 * need to do gcgrp_lookup of 'dst' itself.
8589 			 */
8590 			ga.ga_af = AF_INET;
8591 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8592 			    &ga.ga_addr);
8593 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8594 
8595 			ire = ire_create(
8596 			    (uchar_t *)&dst,		/* dest address */
8597 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8598 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8599 			    (uchar_t *)&gw,		/* gateway address */
8600 			    &save_ire->ire_max_frag,
8601 			    NULL,			/* no src nce */
8602 			    dst_ill->ill_rq,		/* recv-from queue */
8603 			    dst_ill->ill_wq,		/* send-to queue */
8604 			    IRE_CACHE,
8605 			    src_ipif,
8606 			    save_ire->ire_mask,		/* Parent mask */
8607 			    (sire != NULL) ?		/* Parent handle */
8608 			    sire->ire_phandle : 0,
8609 			    save_ire->ire_ihandle,	/* Interface handle */
8610 			    (sire != NULL) ? sire->ire_flags &
8611 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8612 			    &(save_ire->ire_uinfo),
8613 			    NULL,
8614 			    gcgrp,
8615 			    ipst);
8616 
8617 			if (ire == NULL) {
8618 				if (gcgrp != NULL) {
8619 					GCGRP_REFRELE(gcgrp);
8620 					gcgrp = NULL;
8621 				}
8622 				ire_refrele(save_ire);
8623 				break;
8624 			}
8625 
8626 			/* reference now held by IRE */
8627 			gcgrp = NULL;
8628 
8629 			ire->ire_marks |= ire_marks;
8630 
8631 			/* Prevent save_ire from getting deleted */
8632 			IRB_REFHOLD(save_ire->ire_bucket);
8633 			/* Has it been removed already ? */
8634 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8635 				IRB_REFRELE(save_ire->ire_bucket);
8636 				ire_refrele(save_ire);
8637 				break;
8638 			}
8639 
8640 			/*
8641 			 * In the case of multirouting, a copy
8642 			 * of the packet is made before it is sent.
8643 			 * The copy is used in the next
8644 			 * loop to attempt another resolution.
8645 			 */
8646 			xmit_mp = first_mp;
8647 			if ((sire != NULL) &&
8648 			    (sire->ire_flags & RTF_MULTIRT)) {
8649 				copy_mp = copymsg(first_mp);
8650 				if (copy_mp != NULL) {
8651 					xmit_mp = copy_mp;
8652 					MULTIRT_DEBUG_TAG(first_mp);
8653 				}
8654 			}
8655 			ire_add_then_send(q, ire, xmit_mp);
8656 
8657 			/* Assert that it is not deleted yet. */
8658 			ASSERT(save_ire->ire_ptpn != NULL);
8659 			IRB_REFRELE(save_ire->ire_bucket);
8660 			ire_refrele(save_ire);
8661 
8662 			if (copy_mp != NULL) {
8663 				/*
8664 				 * If we found a (no)resolver, we ignore any
8665 				 * trailing top priority IRE_CACHE in further
8666 				 * loops. This ensures that we do not omit any
8667 				 * (no)resolver.
8668 				 * This IRE_CACHE, if any, will be processed
8669 				 * by another thread entering ip_newroute().
8670 				 * IRE_CACHE entries, if any, will be processed
8671 				 * by another thread entering ip_newroute(),
8672 				 * (upon resolver response, for instance).
8673 				 * This aims to force parallel multirt
8674 				 * resolutions as soon as a packet must be sent.
8675 				 * In the best case, after the tx of only one
8676 				 * packet, all reachable routes are resolved.
8677 				 * Otherwise, the resolution of all RTF_MULTIRT
8678 				 * routes would require several emissions.
8679 				 */
8680 				multirt_flags &= ~MULTIRT_CACHEGW;
8681 
8682 				/*
8683 				 * Search for the next unresolved multirt
8684 				 * route.
8685 				 */
8686 				copy_mp = NULL;
8687 				save_ire = NULL;
8688 				ire = NULL;
8689 				multirt_resolve_next = B_TRUE;
8690 				continue;
8691 			}
8692 
8693 			/*
8694 			 * Don't need sire anymore
8695 			 */
8696 			if (sire != NULL)
8697 				ire_refrele(sire);
8698 
8699 			ipif_refrele(src_ipif);
8700 			ill_refrele(dst_ill);
8701 			return;
8702 		}
8703 		case IRE_IF_RESOLVER:
8704 			/*
8705 			 * We can't build an IRE_CACHE yet, but at least we
8706 			 * found a resolver that can help.
8707 			 */
8708 			res_mp = dst_ill->ill_resolver_mp;
8709 			if (!OK_RESOLVER_MP(res_mp))
8710 				break;
8711 
8712 			/*
8713 			 * To be at this point in the code with a non-zero gw
8714 			 * means that dst is reachable through a gateway that
8715 			 * we have never resolved.  By changing dst to the gw
8716 			 * addr we resolve the gateway first.
8717 			 * When ire_add_then_send() tries to put the IP dg
8718 			 * to dst, it will reenter ip_newroute() at which
8719 			 * time we will find the IRE_CACHE for the gw and
8720 			 * create another IRE_CACHE in case IRE_CACHE above.
8721 			 */
8722 			if (gw != INADDR_ANY) {
8723 				/*
8724 				 * The source ipif that was determined above was
8725 				 * relative to the destination address, not the
8726 				 * gateway's. If src_ipif was not taken out of
8727 				 * the IRE_IF_RESOLVER entry, we'll need to call
8728 				 * ipif_select_source() again.
8729 				 */
8730 				if (src_ipif != ire->ire_ipif) {
8731 					ipif_refrele(src_ipif);
8732 					src_ipif = ipif_select_source(dst_ill,
8733 					    gw, zoneid);
8734 					if (src_ipif == NULL) {
8735 						if (ip_debug > 2) {
8736 							pr_addr_dbg(
8737 							    "ip_newroute: no "
8738 							    "src for gw %s ",
8739 							    AF_INET, &gw);
8740 							printf("on "
8741 							    "interface %s\n",
8742 							    dst_ill->ill_name);
8743 						}
8744 						goto icmp_err_ret;
8745 					}
8746 				}
8747 				save_dst = dst;
8748 				dst = gw;
8749 				gw = INADDR_ANY;
8750 			}
8751 
8752 			/*
8753 			 * We obtain a partial IRE_CACHE which we will pass
8754 			 * along with the resolver query.  When the response
8755 			 * comes back it will be there ready for us to add.
8756 			 * The ire_max_frag is atomically set under the
8757 			 * irebucket lock in ire_add_v[46].
8758 			 */
8759 
8760 			ire = ire_create_mp(
8761 			    (uchar_t *)&dst,		/* dest address */
8762 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8763 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8764 			    (uchar_t *)&gw,		/* gateway address */
8765 			    NULL,			/* ire_max_frag */
8766 			    NULL,			/* no src nce */
8767 			    dst_ill->ill_rq,		/* recv-from queue */
8768 			    dst_ill->ill_wq,		/* send-to queue */
8769 			    IRE_CACHE,
8770 			    src_ipif,			/* Interface ipif */
8771 			    save_ire->ire_mask,		/* Parent mask */
8772 			    0,
8773 			    save_ire->ire_ihandle,	/* Interface handle */
8774 			    0,				/* flags if any */
8775 			    &(save_ire->ire_uinfo),
8776 			    NULL,
8777 			    NULL,
8778 			    ipst);
8779 
8780 			if (ire == NULL) {
8781 				ire_refrele(save_ire);
8782 				break;
8783 			}
8784 
8785 			if ((sire != NULL) &&
8786 			    (sire->ire_flags & RTF_MULTIRT)) {
8787 				copy_mp = copymsg(first_mp);
8788 				if (copy_mp != NULL)
8789 					MULTIRT_DEBUG_TAG(copy_mp);
8790 			}
8791 
8792 			ire->ire_marks |= ire_marks;
8793 
8794 			/*
8795 			 * Construct message chain for the resolver
8796 			 * of the form:
8797 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8798 			 * Packet could contain a IPSEC_OUT mp.
8799 			 *
8800 			 * NOTE : ire will be added later when the response
8801 			 * comes back from ARP. If the response does not
8802 			 * come back, ARP frees the packet. For this reason,
8803 			 * we can't REFHOLD the bucket of save_ire to prevent
8804 			 * deletions. We may not be able to REFRELE the bucket
8805 			 * if the response never comes back. Thus, before
8806 			 * adding the ire, ire_add_v4 will make sure that the
8807 			 * interface route does not get deleted. This is the
8808 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8809 			 * where we can always prevent deletions because of
8810 			 * the synchronous nature of adding IRES i.e
8811 			 * ire_add_then_send is called after creating the IRE.
8812 			 */
8813 			ASSERT(ire->ire_mp != NULL);
8814 			ire->ire_mp->b_cont = first_mp;
8815 			/* Have saved_mp handy, for cleanup if canput fails */
8816 			saved_mp = mp;
8817 			mp = copyb(res_mp);
8818 			if (mp == NULL) {
8819 				/* Prepare for cleanup */
8820 				mp = saved_mp; /* pkt */
8821 				ire_delete(ire); /* ire_mp */
8822 				ire = NULL;
8823 				ire_refrele(save_ire);
8824 				if (copy_mp != NULL) {
8825 					MULTIRT_DEBUG_UNTAG(copy_mp);
8826 					freemsg(copy_mp);
8827 					copy_mp = NULL;
8828 				}
8829 				break;
8830 			}
8831 			linkb(mp, ire->ire_mp);
8832 
8833 			/*
8834 			 * Fill in the source and dest addrs for the resolver.
8835 			 * NOTE: this depends on memory layouts imposed by
8836 			 * ill_init().
8837 			 */
8838 			areq = (areq_t *)mp->b_rptr;
8839 			addrp = (ipaddr_t *)((char *)areq +
8840 			    areq->areq_sender_addr_offset);
8841 			*addrp = save_ire->ire_src_addr;
8842 
8843 			ire_refrele(save_ire);
8844 			addrp = (ipaddr_t *)((char *)areq +
8845 			    areq->areq_target_addr_offset);
8846 			*addrp = dst;
8847 			/* Up to the resolver. */
8848 			if (canputnext(dst_ill->ill_rq) &&
8849 			    !(dst_ill->ill_arp_closing)) {
8850 				putnext(dst_ill->ill_rq, mp);
8851 				ire = NULL;
8852 				if (copy_mp != NULL) {
8853 					/*
8854 					 * If we found a resolver, we ignore
8855 					 * any trailing top priority IRE_CACHE
8856 					 * in the further loops. This ensures
8857 					 * that we do not omit any resolver.
8858 					 * IRE_CACHE entries, if any, will be
8859 					 * processed next time we enter
8860 					 * ip_newroute().
8861 					 */
8862 					multirt_flags &= ~MULTIRT_CACHEGW;
8863 					/*
8864 					 * Search for the next unresolved
8865 					 * multirt route.
8866 					 */
8867 					first_mp = copy_mp;
8868 					copy_mp = NULL;
8869 					/* Prepare the next resolution loop. */
8870 					mp = first_mp;
8871 					EXTRACT_PKT_MP(mp, first_mp,
8872 					    mctl_present);
8873 					if (mctl_present)
8874 						io = (ipsec_out_t *)
8875 						    first_mp->b_rptr;
8876 					ipha = (ipha_t *)mp->b_rptr;
8877 
8878 					ASSERT(sire != NULL);
8879 
8880 					dst = save_dst;
8881 					multirt_resolve_next = B_TRUE;
8882 					continue;
8883 				}
8884 
8885 				if (sire != NULL)
8886 					ire_refrele(sire);
8887 
8888 				/*
8889 				 * The response will come back in ip_wput
8890 				 * with db_type IRE_DB_TYPE.
8891 				 */
8892 				ipif_refrele(src_ipif);
8893 				ill_refrele(dst_ill);
8894 				return;
8895 			} else {
8896 				/* Prepare for cleanup */
8897 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8898 				    mp);
8899 				mp->b_cont = NULL;
8900 				freeb(mp); /* areq */
8901 				/*
8902 				 * this is an ire that is not added to the
8903 				 * cache. ire_freemblk will handle the release
8904 				 * of any resources associated with the ire.
8905 				 */
8906 				ire_delete(ire); /* ire_mp */
8907 				mp = saved_mp; /* pkt */
8908 				ire = NULL;
8909 				if (copy_mp != NULL) {
8910 					MULTIRT_DEBUG_UNTAG(copy_mp);
8911 					freemsg(copy_mp);
8912 					copy_mp = NULL;
8913 				}
8914 				break;
8915 			}
8916 		default:
8917 			break;
8918 		}
8919 	} while (multirt_resolve_next);
8920 
8921 	ip1dbg(("ip_newroute: dropped\n"));
8922 	/* Did this packet originate externally? */
8923 	if (mp->b_prev) {
8924 		mp->b_next = NULL;
8925 		mp->b_prev = NULL;
8926 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8927 	} else {
8928 		if (dst_ill != NULL) {
8929 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8930 		} else {
8931 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8932 		}
8933 	}
8934 	ASSERT(copy_mp == NULL);
8935 	MULTIRT_DEBUG_UNTAG(first_mp);
8936 	freemsg(first_mp);
8937 	if (ire != NULL)
8938 		ire_refrele(ire);
8939 	if (sire != NULL)
8940 		ire_refrele(sire);
8941 	if (src_ipif != NULL)
8942 		ipif_refrele(src_ipif);
8943 	if (dst_ill != NULL)
8944 		ill_refrele(dst_ill);
8945 	return;
8946 
8947 icmp_err_ret:
8948 	ip1dbg(("ip_newroute: no route\n"));
8949 	if (src_ipif != NULL)
8950 		ipif_refrele(src_ipif);
8951 	if (dst_ill != NULL)
8952 		ill_refrele(dst_ill);
8953 	if (sire != NULL)
8954 		ire_refrele(sire);
8955 	/* Did this packet originate externally? */
8956 	if (mp->b_prev) {
8957 		mp->b_next = NULL;
8958 		mp->b_prev = NULL;
8959 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8960 		q = WR(q);
8961 	} else {
8962 		/*
8963 		 * There is no outgoing ill, so just increment the
8964 		 * system MIB.
8965 		 */
8966 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8967 		/*
8968 		 * Since ip_wput() isn't close to finished, we fill
8969 		 * in enough of the header for credible error reporting.
8970 		 */
8971 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8972 			/* Failed */
8973 			MULTIRT_DEBUG_UNTAG(first_mp);
8974 			freemsg(first_mp);
8975 			if (ire != NULL)
8976 				ire_refrele(ire);
8977 			return;
8978 		}
8979 	}
8980 
8981 	/*
8982 	 * At this point we will have ire only if RTF_BLACKHOLE
8983 	 * or RTF_REJECT flags are set on the IRE. It will not
8984 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8985 	 */
8986 	if (ire != NULL) {
8987 		if (ire->ire_flags & RTF_BLACKHOLE) {
8988 			ire_refrele(ire);
8989 			MULTIRT_DEBUG_UNTAG(first_mp);
8990 			freemsg(first_mp);
8991 			return;
8992 		}
8993 		ire_refrele(ire);
8994 	}
8995 	if (ip_source_routed(ipha, ipst)) {
8996 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8997 		    zoneid, ipst);
8998 		return;
8999 	}
9000 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9001 }
9002 
9003 ip_opt_info_t zero_info;
9004 
9005 /*
9006  * IPv4 -
9007  * ip_newroute_ipif is called by ip_wput_multicast and
9008  * ip_rput_forward_multicast whenever we need to send
9009  * out a packet to a destination address for which we do not have specific
9010  * routing information. It is used when the packet will be sent out
9011  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
9012  * socket option is set or icmp error message wants to go out on a particular
9013  * interface for a unicast packet.
9014  *
9015  * In most cases, the destination address is resolved thanks to the ipif
9016  * intrinsic resolver. However, there are some cases where the call to
9017  * ip_newroute_ipif must take into account the potential presence of
9018  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9019  * that uses the interface. This is specified through flags,
9020  * which can be a combination of:
9021  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9022  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9023  *   and flags. Additionally, the packet source address has to be set to
9024  *   the specified address. The caller is thus expected to set this flag
9025  *   if the packet has no specific source address yet.
9026  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9027  *   flag, the resulting ire will inherit the flag. All unresolved routes
9028  *   to the destination must be explored in the same call to
9029  *   ip_newroute_ipif().
9030  */
9031 static void
9032 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9033     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9034 {
9035 	areq_t	*areq;
9036 	ire_t	*ire = NULL;
9037 	mblk_t	*res_mp;
9038 	ipaddr_t *addrp;
9039 	mblk_t *first_mp;
9040 	ire_t	*save_ire = NULL;
9041 	ipif_t	*src_ipif = NULL;
9042 	ushort_t ire_marks = 0;
9043 	ill_t	*dst_ill = NULL;
9044 	ipha_t *ipha;
9045 	mblk_t	*saved_mp;
9046 	ire_t   *fire = NULL;
9047 	mblk_t  *copy_mp = NULL;
9048 	boolean_t multirt_resolve_next;
9049 	boolean_t unspec_src;
9050 	ipaddr_t ipha_dst;
9051 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9052 
9053 	/*
9054 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9055 	 * here for uniformity
9056 	 */
9057 	ipif_refhold(ipif);
9058 
9059 	/*
9060 	 * This loop is run only once in most cases.
9061 	 * We loop to resolve further routes only when the destination
9062 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9063 	 */
9064 	do {
9065 		if (dst_ill != NULL) {
9066 			ill_refrele(dst_ill);
9067 			dst_ill = NULL;
9068 		}
9069 		if (src_ipif != NULL) {
9070 			ipif_refrele(src_ipif);
9071 			src_ipif = NULL;
9072 		}
9073 		multirt_resolve_next = B_FALSE;
9074 
9075 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9076 		    ipif->ipif_ill->ill_name));
9077 
9078 		first_mp = mp;
9079 		if (DB_TYPE(mp) == M_CTL)
9080 			mp = mp->b_cont;
9081 		ipha = (ipha_t *)mp->b_rptr;
9082 
9083 		/*
9084 		 * Save the packet destination address, we may need it after
9085 		 * the packet has been consumed.
9086 		 */
9087 		ipha_dst = ipha->ipha_dst;
9088 
9089 		/*
9090 		 * If the interface is a pt-pt interface we look for an
9091 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9092 		 * local_address and the pt-pt destination address. Otherwise
9093 		 * we just match the local address.
9094 		 * NOTE: dst could be different than ipha->ipha_dst in case
9095 		 * of sending igmp multicast packets over a point-to-point
9096 		 * connection.
9097 		 * Thus we must be careful enough to check ipha_dst to be a
9098 		 * multicast address, otherwise it will take xmit_if path for
9099 		 * multicast packets resulting into kernel stack overflow by
9100 		 * repeated calls to ip_newroute_ipif from ire_send().
9101 		 */
9102 		if (CLASSD(ipha_dst) &&
9103 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9104 			goto err_ret;
9105 		}
9106 
9107 		/*
9108 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9109 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9110 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9111 		 * propagate its flags to the new ire.
9112 		 */
9113 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9114 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9115 			ip2dbg(("ip_newroute_ipif: "
9116 			    "ipif_lookup_multi_ire("
9117 			    "ipif %p, dst %08x) = fire %p\n",
9118 			    (void *)ipif, ntohl(dst), (void *)fire));
9119 		}
9120 
9121 		/*
9122 		 * Note: While we pick a dst_ill we are really only
9123 		 * interested in the ill for load spreading. The source
9124 		 * ipif is determined by source address selection below.
9125 		 */
9126 		if (IS_IPMP(ipif->ipif_ill)) {
9127 			ipmp_illgrp_t *illg = ipif->ipif_ill->ill_grp;
9128 
9129 			if (CLASSD(ipha_dst))
9130 				dst_ill = ipmp_illgrp_hold_cast_ill(illg);
9131 			else
9132 				dst_ill = ipmp_illgrp_hold_next_ill(illg);
9133 		} else {
9134 			dst_ill = ipif->ipif_ill;
9135 			ill_refhold(dst_ill);
9136 		}
9137 
9138 		if (dst_ill == NULL) {
9139 			if (ip_debug > 2) {
9140 				pr_addr_dbg("ip_newroute_ipif: no dst ill "
9141 				    "for dst %s\n", AF_INET, &dst);
9142 			}
9143 			goto err_ret;
9144 		}
9145 
9146 		/*
9147 		 * Pick a source address preferring non-deprecated ones.
9148 		 * Unlike ip_newroute, we don't do any source address
9149 		 * selection here since for multicast it really does not help
9150 		 * in inbound load spreading as in the unicast case.
9151 		 */
9152 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9153 		    (fire->ire_flags & RTF_SETSRC)) {
9154 			/*
9155 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9156 			 * on that interface. This ire has RTF_SETSRC flag, so
9157 			 * the source address of the packet must be changed.
9158 			 * Check that the ipif matching the requested source
9159 			 * address still exists.
9160 			 */
9161 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9162 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9163 		}
9164 
9165 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9166 
9167 		if (!IS_UNDER_IPMP(ipif->ipif_ill) &&
9168 		    (IS_IPMP(ipif->ipif_ill) ||
9169 		    (!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9170 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9171 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9172 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9173 		    (src_ipif == NULL) &&
9174 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9175 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9176 			if (src_ipif == NULL) {
9177 				if (ip_debug > 2) {
9178 					/* ip1dbg */
9179 					pr_addr_dbg("ip_newroute_ipif: "
9180 					    "no src for dst %s",
9181 					    AF_INET, &dst);
9182 				}
9183 				ip1dbg((" on interface %s\n",
9184 				    dst_ill->ill_name));
9185 				goto err_ret;
9186 			}
9187 			ipif_refrele(ipif);
9188 			ipif = src_ipif;
9189 			ipif_refhold(ipif);
9190 		}
9191 		if (src_ipif == NULL) {
9192 			src_ipif = ipif;
9193 			ipif_refhold(src_ipif);
9194 		}
9195 
9196 		/*
9197 		 * Assign a source address while we have the conn.
9198 		 * We can't have ip_wput_ire pick a source address when the
9199 		 * packet returns from arp since conn_unspec_src might be set
9200 		 * and we lose the conn when going through arp.
9201 		 */
9202 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9203 			ipha->ipha_src = src_ipif->ipif_src_addr;
9204 
9205 		/*
9206 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9207 		 * that the outgoing interface does not have an interface ire.
9208 		 */
9209 		if (CLASSD(ipha_dst) && (connp == NULL ||
9210 		    connp->conn_outgoing_ill == NULL) &&
9211 		    infop->ip_opt_ill_index == 0) {
9212 			/* ipif_to_ire returns an held ire */
9213 			ire = ipif_to_ire(ipif);
9214 			if (ire == NULL)
9215 				goto err_ret;
9216 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9217 				goto err_ret;
9218 			save_ire = ire;
9219 
9220 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9221 			    "flags %04x\n",
9222 			    (void *)ire, (void *)ipif, flags));
9223 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9224 			    (fire->ire_flags & RTF_MULTIRT)) {
9225 				/*
9226 				 * As requested by flags, an IRE_OFFSUBNET was
9227 				 * looked up on that interface. This ire has
9228 				 * RTF_MULTIRT flag, so the resolution loop will
9229 				 * be re-entered to resolve additional routes on
9230 				 * other interfaces. For that purpose, a copy of
9231 				 * the packet is performed at this point.
9232 				 */
9233 				fire->ire_last_used_time = lbolt;
9234 				copy_mp = copymsg(first_mp);
9235 				if (copy_mp) {
9236 					MULTIRT_DEBUG_TAG(copy_mp);
9237 				}
9238 			}
9239 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9240 			    (fire->ire_flags & RTF_SETSRC)) {
9241 				/*
9242 				 * As requested by flags, an IRE_OFFSUBET was
9243 				 * looked up on that interface. This ire has
9244 				 * RTF_SETSRC flag, so the source address of the
9245 				 * packet must be changed.
9246 				 */
9247 				ipha->ipha_src = fire->ire_src_addr;
9248 			}
9249 		} else {
9250 			/*
9251 			 * The only ways we can come here are:
9252 			 * 1) IP_BOUND_IF socket option is set
9253 			 * 2) SO_DONTROUTE socket option is set
9254 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9255 			 * In all cases, the new ire will not be added
9256 			 * into cache table.
9257 			 */
9258 			ASSERT(connp == NULL || connp->conn_dontroute ||
9259 			    connp->conn_outgoing_ill != NULL ||
9260 			    infop->ip_opt_ill_index != 0);
9261 			ire_marks |= IRE_MARK_NOADD;
9262 		}
9263 
9264 		switch (ipif->ipif_net_type) {
9265 		case IRE_IF_NORESOLVER: {
9266 			/* We have what we need to build an IRE_CACHE. */
9267 
9268 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9269 			    (dst_ill->ill_resolver_mp == NULL)) {
9270 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9271 				    "for IRE_IF_NORESOLVER ire %p has "
9272 				    "no ill_resolver_mp\n",
9273 				    (void *)dst_ill, (void *)ire));
9274 				break;
9275 			}
9276 
9277 			/*
9278 			 * The new ire inherits the IRE_OFFSUBNET flags
9279 			 * and source address, if this was requested.
9280 			 */
9281 			ire = ire_create(
9282 			    (uchar_t *)&dst,		/* dest address */
9283 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9284 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9285 			    NULL,			/* gateway address */
9286 			    &ipif->ipif_mtu,
9287 			    NULL,			/* no src nce */
9288 			    dst_ill->ill_rq,		/* recv-from queue */
9289 			    dst_ill->ill_wq,		/* send-to queue */
9290 			    IRE_CACHE,
9291 			    src_ipif,
9292 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9293 			    (fire != NULL) ?		/* Parent handle */
9294 			    fire->ire_phandle : 0,
9295 			    (save_ire != NULL) ?	/* Interface handle */
9296 			    save_ire->ire_ihandle : 0,
9297 			    (fire != NULL) ?
9298 			    (fire->ire_flags &
9299 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9300 			    (save_ire == NULL ? &ire_uinfo_null :
9301 			    &save_ire->ire_uinfo),
9302 			    NULL,
9303 			    NULL,
9304 			    ipst);
9305 
9306 			if (ire == NULL) {
9307 				if (save_ire != NULL)
9308 					ire_refrele(save_ire);
9309 				break;
9310 			}
9311 
9312 			ire->ire_marks |= ire_marks;
9313 
9314 			/*
9315 			 * If IRE_MARK_NOADD is set then we need to convert
9316 			 * the max_fragp to a useable value now. This is
9317 			 * normally done in ire_add_v[46]. We also need to
9318 			 * associate the ire with an nce (normally would be
9319 			 * done in ip_wput_nondata()).
9320 			 *
9321 			 * Note that IRE_MARK_NOADD packets created here
9322 			 * do not have a non-null ire_mp pointer. The null
9323 			 * value of ire_bucket indicates that they were
9324 			 * never added.
9325 			 */
9326 			if (ire->ire_marks & IRE_MARK_NOADD) {
9327 				uint_t  max_frag;
9328 
9329 				max_frag = *ire->ire_max_fragp;
9330 				ire->ire_max_fragp = NULL;
9331 				ire->ire_max_frag = max_frag;
9332 
9333 				if ((ire->ire_nce = ndp_lookup_v4(
9334 				    ire_to_ill(ire),
9335 				    (ire->ire_gateway_addr != INADDR_ANY ?
9336 				    &ire->ire_gateway_addr : &ire->ire_addr),
9337 				    B_FALSE)) == NULL) {
9338 					if (save_ire != NULL)
9339 						ire_refrele(save_ire);
9340 					break;
9341 				}
9342 				ASSERT(ire->ire_nce->nce_state ==
9343 				    ND_REACHABLE);
9344 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9345 			}
9346 
9347 			/* Prevent save_ire from getting deleted */
9348 			if (save_ire != NULL) {
9349 				IRB_REFHOLD(save_ire->ire_bucket);
9350 				/* Has it been removed already ? */
9351 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9352 					IRB_REFRELE(save_ire->ire_bucket);
9353 					ire_refrele(save_ire);
9354 					break;
9355 				}
9356 			}
9357 
9358 			ire_add_then_send(q, ire, first_mp);
9359 
9360 			/* Assert that save_ire is not deleted yet. */
9361 			if (save_ire != NULL) {
9362 				ASSERT(save_ire->ire_ptpn != NULL);
9363 				IRB_REFRELE(save_ire->ire_bucket);
9364 				ire_refrele(save_ire);
9365 				save_ire = NULL;
9366 			}
9367 			if (fire != NULL) {
9368 				ire_refrele(fire);
9369 				fire = NULL;
9370 			}
9371 
9372 			/*
9373 			 * the resolution loop is re-entered if this
9374 			 * was requested through flags and if we
9375 			 * actually are in a multirouting case.
9376 			 */
9377 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9378 				boolean_t need_resolve =
9379 				    ire_multirt_need_resolve(ipha_dst,
9380 				    msg_getlabel(copy_mp), ipst);
9381 				if (!need_resolve) {
9382 					MULTIRT_DEBUG_UNTAG(copy_mp);
9383 					freemsg(copy_mp);
9384 					copy_mp = NULL;
9385 				} else {
9386 					/*
9387 					 * ipif_lookup_group() calls
9388 					 * ire_lookup_multi() that uses
9389 					 * ire_ftable_lookup() to find
9390 					 * an IRE_INTERFACE for the group.
9391 					 * In the multirt case,
9392 					 * ire_lookup_multi() then invokes
9393 					 * ire_multirt_lookup() to find
9394 					 * the next resolvable ire.
9395 					 * As a result, we obtain an new
9396 					 * interface, derived from the
9397 					 * next ire.
9398 					 */
9399 					ipif_refrele(ipif);
9400 					ipif = ipif_lookup_group(ipha_dst,
9401 					    zoneid, ipst);
9402 					ip2dbg(("ip_newroute_ipif: "
9403 					    "multirt dst %08x, ipif %p\n",
9404 					    htonl(dst), (void *)ipif));
9405 					if (ipif != NULL) {
9406 						mp = copy_mp;
9407 						copy_mp = NULL;
9408 						multirt_resolve_next = B_TRUE;
9409 						continue;
9410 					} else {
9411 						freemsg(copy_mp);
9412 					}
9413 				}
9414 			}
9415 			if (ipif != NULL)
9416 				ipif_refrele(ipif);
9417 			ill_refrele(dst_ill);
9418 			ipif_refrele(src_ipif);
9419 			return;
9420 		}
9421 		case IRE_IF_RESOLVER:
9422 			/*
9423 			 * We can't build an IRE_CACHE yet, but at least
9424 			 * we found a resolver that can help.
9425 			 */
9426 			res_mp = dst_ill->ill_resolver_mp;
9427 			if (!OK_RESOLVER_MP(res_mp))
9428 				break;
9429 
9430 			/*
9431 			 * We obtain a partial IRE_CACHE which we will pass
9432 			 * along with the resolver query.  When the response
9433 			 * comes back it will be there ready for us to add.
9434 			 * The new ire inherits the IRE_OFFSUBNET flags
9435 			 * and source address, if this was requested.
9436 			 * The ire_max_frag is atomically set under the
9437 			 * irebucket lock in ire_add_v[46]. Only in the
9438 			 * case of IRE_MARK_NOADD, we set it here itself.
9439 			 */
9440 			ire = ire_create_mp(
9441 			    (uchar_t *)&dst,		/* dest address */
9442 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9443 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9444 			    NULL,			/* gateway address */
9445 			    (ire_marks & IRE_MARK_NOADD) ?
9446 			    ipif->ipif_mtu : 0,		/* max_frag */
9447 			    NULL,			/* no src nce */
9448 			    dst_ill->ill_rq,		/* recv-from queue */
9449 			    dst_ill->ill_wq,		/* send-to queue */
9450 			    IRE_CACHE,
9451 			    src_ipif,
9452 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9453 			    (fire != NULL) ?		/* Parent handle */
9454 			    fire->ire_phandle : 0,
9455 			    (save_ire != NULL) ?	/* Interface handle */
9456 			    save_ire->ire_ihandle : 0,
9457 			    (fire != NULL) ?		/* flags if any */
9458 			    (fire->ire_flags &
9459 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9460 			    (save_ire == NULL ? &ire_uinfo_null :
9461 			    &save_ire->ire_uinfo),
9462 			    NULL,
9463 			    NULL,
9464 			    ipst);
9465 
9466 			if (save_ire != NULL) {
9467 				ire_refrele(save_ire);
9468 				save_ire = NULL;
9469 			}
9470 			if (ire == NULL)
9471 				break;
9472 
9473 			ire->ire_marks |= ire_marks;
9474 			/*
9475 			 * Construct message chain for the resolver of the
9476 			 * form:
9477 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9478 			 *
9479 			 * NOTE : ire will be added later when the response
9480 			 * comes back from ARP. If the response does not
9481 			 * come back, ARP frees the packet. For this reason,
9482 			 * we can't REFHOLD the bucket of save_ire to prevent
9483 			 * deletions. We may not be able to REFRELE the
9484 			 * bucket if the response never comes back.
9485 			 * Thus, before adding the ire, ire_add_v4 will make
9486 			 * sure that the interface route does not get deleted.
9487 			 * This is the only case unlike ip_newroute_v6,
9488 			 * ip_newroute_ipif_v6 where we can always prevent
9489 			 * deletions because ire_add_then_send is called after
9490 			 * creating the IRE.
9491 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9492 			 * does not add this IRE into the IRE CACHE.
9493 			 */
9494 			ASSERT(ire->ire_mp != NULL);
9495 			ire->ire_mp->b_cont = first_mp;
9496 			/* Have saved_mp handy, for cleanup if canput fails */
9497 			saved_mp = mp;
9498 			mp = copyb(res_mp);
9499 			if (mp == NULL) {
9500 				/* Prepare for cleanup */
9501 				mp = saved_mp; /* pkt */
9502 				ire_delete(ire); /* ire_mp */
9503 				ire = NULL;
9504 				if (copy_mp != NULL) {
9505 					MULTIRT_DEBUG_UNTAG(copy_mp);
9506 					freemsg(copy_mp);
9507 					copy_mp = NULL;
9508 				}
9509 				break;
9510 			}
9511 			linkb(mp, ire->ire_mp);
9512 
9513 			/*
9514 			 * Fill in the source and dest addrs for the resolver.
9515 			 * NOTE: this depends on memory layouts imposed by
9516 			 * ill_init().  There are corner cases above where we
9517 			 * might've created the IRE with an INADDR_ANY source
9518 			 * address (e.g., if the zeroth ipif on an underlying
9519 			 * ill in an IPMP group is 0.0.0.0, but another ipif
9520 			 * on the ill has a usable test address).  If so, tell
9521 			 * ARP to use ipha_src as its sender address.
9522 			 */
9523 			areq = (areq_t *)mp->b_rptr;
9524 			addrp = (ipaddr_t *)((char *)areq +
9525 			    areq->areq_sender_addr_offset);
9526 			if (ire->ire_src_addr != INADDR_ANY)
9527 				*addrp = ire->ire_src_addr;
9528 			else
9529 				*addrp = ipha->ipha_src;
9530 			addrp = (ipaddr_t *)((char *)areq +
9531 			    areq->areq_target_addr_offset);
9532 			*addrp = dst;
9533 			/* Up to the resolver. */
9534 			if (canputnext(dst_ill->ill_rq) &&
9535 			    !(dst_ill->ill_arp_closing)) {
9536 				putnext(dst_ill->ill_rq, mp);
9537 				/*
9538 				 * The response will come back in ip_wput
9539 				 * with db_type IRE_DB_TYPE.
9540 				 */
9541 			} else {
9542 				mp->b_cont = NULL;
9543 				freeb(mp); /* areq */
9544 				ire_delete(ire); /* ire_mp */
9545 				saved_mp->b_next = NULL;
9546 				saved_mp->b_prev = NULL;
9547 				freemsg(first_mp); /* pkt */
9548 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9549 			}
9550 
9551 			if (fire != NULL) {
9552 				ire_refrele(fire);
9553 				fire = NULL;
9554 			}
9555 
9556 			/*
9557 			 * The resolution loop is re-entered if this was
9558 			 * requested through flags and we actually are
9559 			 * in a multirouting case.
9560 			 */
9561 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9562 				boolean_t need_resolve =
9563 				    ire_multirt_need_resolve(ipha_dst,
9564 				    msg_getlabel(copy_mp), ipst);
9565 				if (!need_resolve) {
9566 					MULTIRT_DEBUG_UNTAG(copy_mp);
9567 					freemsg(copy_mp);
9568 					copy_mp = NULL;
9569 				} else {
9570 					/*
9571 					 * ipif_lookup_group() calls
9572 					 * ire_lookup_multi() that uses
9573 					 * ire_ftable_lookup() to find
9574 					 * an IRE_INTERFACE for the group.
9575 					 * In the multirt case,
9576 					 * ire_lookup_multi() then invokes
9577 					 * ire_multirt_lookup() to find
9578 					 * the next resolvable ire.
9579 					 * As a result, we obtain an new
9580 					 * interface, derived from the
9581 					 * next ire.
9582 					 */
9583 					ipif_refrele(ipif);
9584 					ipif = ipif_lookup_group(ipha_dst,
9585 					    zoneid, ipst);
9586 					if (ipif != NULL) {
9587 						mp = copy_mp;
9588 						copy_mp = NULL;
9589 						multirt_resolve_next = B_TRUE;
9590 						continue;
9591 					} else {
9592 						freemsg(copy_mp);
9593 					}
9594 				}
9595 			}
9596 			if (ipif != NULL)
9597 				ipif_refrele(ipif);
9598 			ill_refrele(dst_ill);
9599 			ipif_refrele(src_ipif);
9600 			return;
9601 		default:
9602 			break;
9603 		}
9604 	} while (multirt_resolve_next);
9605 
9606 err_ret:
9607 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9608 	if (fire != NULL)
9609 		ire_refrele(fire);
9610 	ipif_refrele(ipif);
9611 	/* Did this packet originate externally? */
9612 	if (dst_ill != NULL)
9613 		ill_refrele(dst_ill);
9614 	if (src_ipif != NULL)
9615 		ipif_refrele(src_ipif);
9616 	if (mp->b_prev || mp->b_next) {
9617 		mp->b_next = NULL;
9618 		mp->b_prev = NULL;
9619 	} else {
9620 		/*
9621 		 * Since ip_wput() isn't close to finished, we fill
9622 		 * in enough of the header for credible error reporting.
9623 		 */
9624 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9625 			/* Failed */
9626 			freemsg(first_mp);
9627 			if (ire != NULL)
9628 				ire_refrele(ire);
9629 			return;
9630 		}
9631 	}
9632 	/*
9633 	 * At this point we will have ire only if RTF_BLACKHOLE
9634 	 * or RTF_REJECT flags are set on the IRE. It will not
9635 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9636 	 */
9637 	if (ire != NULL) {
9638 		if (ire->ire_flags & RTF_BLACKHOLE) {
9639 			ire_refrele(ire);
9640 			freemsg(first_mp);
9641 			return;
9642 		}
9643 		ire_refrele(ire);
9644 	}
9645 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9646 }
9647 
9648 /* Name/Value Table Lookup Routine */
9649 char *
9650 ip_nv_lookup(nv_t *nv, int value)
9651 {
9652 	if (!nv)
9653 		return (NULL);
9654 	for (; nv->nv_name; nv++) {
9655 		if (nv->nv_value == value)
9656 			return (nv->nv_name);
9657 	}
9658 	return ("unknown");
9659 }
9660 
9661 /*
9662  * This is a module open, i.e. this is a control stream for access
9663  * to a DLPI device.  We allocate an ill_t as the instance data in
9664  * this case.
9665  */
9666 int
9667 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9668 {
9669 	ill_t	*ill;
9670 	int	err;
9671 	zoneid_t zoneid;
9672 	netstack_t *ns;
9673 	ip_stack_t *ipst;
9674 
9675 	/*
9676 	 * Prevent unprivileged processes from pushing IP so that
9677 	 * they can't send raw IP.
9678 	 */
9679 	if (secpolicy_net_rawaccess(credp) != 0)
9680 		return (EPERM);
9681 
9682 	ns = netstack_find_by_cred(credp);
9683 	ASSERT(ns != NULL);
9684 	ipst = ns->netstack_ip;
9685 	ASSERT(ipst != NULL);
9686 
9687 	/*
9688 	 * For exclusive stacks we set the zoneid to zero
9689 	 * to make IP operate as if in the global zone.
9690 	 */
9691 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9692 		zoneid = GLOBAL_ZONEID;
9693 	else
9694 		zoneid = crgetzoneid(credp);
9695 
9696 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9697 	q->q_ptr = WR(q)->q_ptr = ill;
9698 	ill->ill_ipst = ipst;
9699 	ill->ill_zoneid = zoneid;
9700 
9701 	/*
9702 	 * ill_init initializes the ill fields and then sends down
9703 	 * down a DL_INFO_REQ after calling qprocson.
9704 	 */
9705 	err = ill_init(q, ill);
9706 	if (err != 0) {
9707 		mi_free(ill);
9708 		netstack_rele(ipst->ips_netstack);
9709 		q->q_ptr = NULL;
9710 		WR(q)->q_ptr = NULL;
9711 		return (err);
9712 	}
9713 
9714 	/* ill_init initializes the ipsq marking this thread as writer */
9715 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9716 	/* Wait for the DL_INFO_ACK */
9717 	mutex_enter(&ill->ill_lock);
9718 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9719 		/*
9720 		 * Return value of 0 indicates a pending signal.
9721 		 */
9722 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9723 		if (err == 0) {
9724 			mutex_exit(&ill->ill_lock);
9725 			(void) ip_close(q, 0);
9726 			return (EINTR);
9727 		}
9728 	}
9729 	mutex_exit(&ill->ill_lock);
9730 
9731 	/*
9732 	 * ip_rput_other could have set an error  in ill_error on
9733 	 * receipt of M_ERROR.
9734 	 */
9735 
9736 	err = ill->ill_error;
9737 	if (err != 0) {
9738 		(void) ip_close(q, 0);
9739 		return (err);
9740 	}
9741 
9742 	ill->ill_credp = credp;
9743 	crhold(credp);
9744 
9745 	mutex_enter(&ipst->ips_ip_mi_lock);
9746 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9747 	    credp);
9748 	mutex_exit(&ipst->ips_ip_mi_lock);
9749 	if (err) {
9750 		(void) ip_close(q, 0);
9751 		return (err);
9752 	}
9753 	return (0);
9754 }
9755 
9756 /* For /dev/ip aka AF_INET open */
9757 int
9758 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9759 {
9760 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9761 }
9762 
9763 /* For /dev/ip6 aka AF_INET6 open */
9764 int
9765 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9766 {
9767 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9768 }
9769 
9770 /* IP open routine. */
9771 int
9772 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9773     boolean_t isv6)
9774 {
9775 	conn_t 		*connp;
9776 	major_t		maj;
9777 	zoneid_t	zoneid;
9778 	netstack_t	*ns;
9779 	ip_stack_t	*ipst;
9780 
9781 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9782 
9783 	/* Allow reopen. */
9784 	if (q->q_ptr != NULL)
9785 		return (0);
9786 
9787 	if (sflag & MODOPEN) {
9788 		/* This is a module open */
9789 		return (ip_modopen(q, devp, flag, sflag, credp));
9790 	}
9791 
9792 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
9793 		/*
9794 		 * Non streams based socket looking for a stream
9795 		 * to access IP
9796 		 */
9797 		return (ip_helper_stream_setup(q, devp, flag, sflag,
9798 		    credp, isv6));
9799 	}
9800 
9801 	ns = netstack_find_by_cred(credp);
9802 	ASSERT(ns != NULL);
9803 	ipst = ns->netstack_ip;
9804 	ASSERT(ipst != NULL);
9805 
9806 	/*
9807 	 * For exclusive stacks we set the zoneid to zero
9808 	 * to make IP operate as if in the global zone.
9809 	 */
9810 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9811 		zoneid = GLOBAL_ZONEID;
9812 	else
9813 		zoneid = crgetzoneid(credp);
9814 
9815 	/*
9816 	 * We are opening as a device. This is an IP client stream, and we
9817 	 * allocate an conn_t as the instance data.
9818 	 */
9819 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9820 
9821 	/*
9822 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9823 	 * done by netstack_find_by_cred()
9824 	 */
9825 	netstack_rele(ipst->ips_netstack);
9826 
9827 	connp->conn_zoneid = zoneid;
9828 	connp->conn_sqp = NULL;
9829 	connp->conn_initial_sqp = NULL;
9830 	connp->conn_final_sqp = NULL;
9831 
9832 	connp->conn_upq = q;
9833 	q->q_ptr = WR(q)->q_ptr = connp;
9834 
9835 	if (flag & SO_SOCKSTR)
9836 		connp->conn_flags |= IPCL_SOCKET;
9837 
9838 	/* Minor tells us which /dev entry was opened */
9839 	if (isv6) {
9840 		connp->conn_flags |= IPCL_ISV6;
9841 		connp->conn_af_isv6 = B_TRUE;
9842 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9843 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9844 	} else {
9845 		connp->conn_af_isv6 = B_FALSE;
9846 		connp->conn_pkt_isv6 = B_FALSE;
9847 	}
9848 
9849 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9850 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9851 		connp->conn_minor_arena = ip_minor_arena_la;
9852 	} else {
9853 		/*
9854 		 * Either minor numbers in the large arena were exhausted
9855 		 * or a non socket application is doing the open.
9856 		 * Try to allocate from the small arena.
9857 		 */
9858 		if ((connp->conn_dev =
9859 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9860 			/* CONN_DEC_REF takes care of netstack_rele() */
9861 			q->q_ptr = WR(q)->q_ptr = NULL;
9862 			CONN_DEC_REF(connp);
9863 			return (EBUSY);
9864 		}
9865 		connp->conn_minor_arena = ip_minor_arena_sa;
9866 	}
9867 
9868 	maj = getemajor(*devp);
9869 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9870 
9871 	/*
9872 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9873 	 */
9874 	connp->conn_cred = credp;
9875 
9876 	/*
9877 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9878 	 */
9879 	connp->conn_recv = ip_conn_input;
9880 
9881 	crhold(connp->conn_cred);
9882 
9883 	/*
9884 	 * If the caller has the process-wide flag set, then default to MAC
9885 	 * exempt mode.  This allows read-down to unlabeled hosts.
9886 	 */
9887 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9888 		connp->conn_mac_exempt = B_TRUE;
9889 
9890 	connp->conn_rq = q;
9891 	connp->conn_wq = WR(q);
9892 
9893 	/* Non-zero default values */
9894 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9895 
9896 	/*
9897 	 * Make the conn globally visible to walkers
9898 	 */
9899 	ASSERT(connp->conn_ref == 1);
9900 	mutex_enter(&connp->conn_lock);
9901 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9902 	mutex_exit(&connp->conn_lock);
9903 
9904 	qprocson(q);
9905 
9906 	return (0);
9907 }
9908 
9909 /*
9910  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9911  * Note that there is no race since either ip_output function works - it
9912  * is just an optimization to enter the best ip_output routine directly.
9913  */
9914 void
9915 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9916     ip_stack_t *ipst)
9917 {
9918 	if (isv6)  {
9919 		if (bump_mib) {
9920 			BUMP_MIB(&ipst->ips_ip6_mib,
9921 			    ipIfStatsOutSwitchIPVersion);
9922 		}
9923 		connp->conn_send = ip_output_v6;
9924 		connp->conn_pkt_isv6 = B_TRUE;
9925 	} else {
9926 		if (bump_mib) {
9927 			BUMP_MIB(&ipst->ips_ip_mib,
9928 			    ipIfStatsOutSwitchIPVersion);
9929 		}
9930 		connp->conn_send = ip_output;
9931 		connp->conn_pkt_isv6 = B_FALSE;
9932 	}
9933 
9934 }
9935 
9936 /*
9937  * See if IPsec needs loading because of the options in mp.
9938  */
9939 static boolean_t
9940 ipsec_opt_present(mblk_t *mp)
9941 {
9942 	uint8_t *optcp, *next_optcp, *opt_endcp;
9943 	struct opthdr *opt;
9944 	struct T_opthdr *topt;
9945 	int opthdr_len;
9946 	t_uscalar_t optname, optlevel;
9947 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9948 	ipsec_req_t *ipsr;
9949 
9950 	/*
9951 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9952 	 * return TRUE.
9953 	 */
9954 
9955 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9956 	opt_endcp = optcp + tor->OPT_length;
9957 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9958 		opthdr_len = sizeof (struct T_opthdr);
9959 	} else {		/* O_OPTMGMT_REQ */
9960 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9961 		opthdr_len = sizeof (struct opthdr);
9962 	}
9963 	for (; optcp < opt_endcp; optcp = next_optcp) {
9964 		if (optcp + opthdr_len > opt_endcp)
9965 			return (B_FALSE);	/* Not enough option header. */
9966 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9967 			topt = (struct T_opthdr *)optcp;
9968 			optlevel = topt->level;
9969 			optname = topt->name;
9970 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9971 		} else {
9972 			opt = (struct opthdr *)optcp;
9973 			optlevel = opt->level;
9974 			optname = opt->name;
9975 			next_optcp = optcp + opthdr_len +
9976 			    _TPI_ALIGN_OPT(opt->len);
9977 		}
9978 		if ((next_optcp < optcp) || /* wraparound pointer space */
9979 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9980 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9981 			return (B_FALSE); /* bad option buffer */
9982 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9983 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9984 			/*
9985 			 * Check to see if it's an all-bypass or all-zeroes
9986 			 * IPsec request.  Don't bother loading IPsec if
9987 			 * the socket doesn't want to use it.  (A good example
9988 			 * is a bypass request.)
9989 			 *
9990 			 * Basically, if any of the non-NEVER bits are set,
9991 			 * load IPsec.
9992 			 */
9993 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9994 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9995 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9996 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9997 			    != 0)
9998 				return (B_TRUE);
9999 		}
10000 	}
10001 	return (B_FALSE);
10002 }
10003 
10004 /*
10005  * If conn is is waiting for ipsec to finish loading, kick it.
10006  */
10007 /* ARGSUSED */
10008 static void
10009 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10010 {
10011 	t_scalar_t	optreq_prim;
10012 	mblk_t		*mp;
10013 	cred_t		*cr;
10014 	int		err = 0;
10015 
10016 	/*
10017 	 * This function is called, after ipsec loading is complete.
10018 	 * Since IP checks exclusively and atomically (i.e it prevents
10019 	 * ipsec load from completing until ip_optcom_req completes)
10020 	 * whether ipsec load is complete, there cannot be a race with IP
10021 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10022 	 */
10023 	mutex_enter(&connp->conn_lock);
10024 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10025 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10026 		mp = connp->conn_ipsec_opt_mp;
10027 		connp->conn_ipsec_opt_mp = NULL;
10028 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10029 		mutex_exit(&connp->conn_lock);
10030 
10031 		/*
10032 		 * All Solaris components should pass a db_credp
10033 		 * for this TPI message, hence we ASSERT.
10034 		 * But in case there is some other M_PROTO that looks
10035 		 * like a TPI message sent by some other kernel
10036 		 * component, we check and return an error.
10037 		 */
10038 		cr = msg_getcred(mp, NULL);
10039 		ASSERT(cr != NULL);
10040 		if (cr == NULL) {
10041 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
10042 			if (mp != NULL)
10043 				qreply(connp->conn_wq, mp);
10044 			return;
10045 		}
10046 
10047 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10048 
10049 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10050 		if (optreq_prim == T_OPTMGMT_REQ) {
10051 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10052 			    &ip_opt_obj, B_FALSE);
10053 		} else {
10054 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10055 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10056 			    &ip_opt_obj, B_FALSE);
10057 		}
10058 		if (err != EINPROGRESS)
10059 			CONN_OPER_PENDING_DONE(connp);
10060 		return;
10061 	}
10062 	mutex_exit(&connp->conn_lock);
10063 }
10064 
10065 /*
10066  * Called from the ipsec_loader thread, outside any perimeter, to tell
10067  * ip qenable any of the queues waiting for the ipsec loader to
10068  * complete.
10069  */
10070 void
10071 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10072 {
10073 	netstack_t *ns = ipss->ipsec_netstack;
10074 
10075 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10076 }
10077 
10078 /*
10079  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10080  * determines the grp on which it has to become exclusive, queues the mp
10081  * and IPSQ draining restarts the optmgmt
10082  */
10083 static boolean_t
10084 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10085 {
10086 	conn_t *connp = Q_TO_CONN(q);
10087 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10088 
10089 	/*
10090 	 * Take IPsec requests and treat them special.
10091 	 */
10092 	if (ipsec_opt_present(mp)) {
10093 		/* First check if IPsec is loaded. */
10094 		mutex_enter(&ipss->ipsec_loader_lock);
10095 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10096 			mutex_exit(&ipss->ipsec_loader_lock);
10097 			return (B_FALSE);
10098 		}
10099 		mutex_enter(&connp->conn_lock);
10100 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10101 
10102 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10103 		connp->conn_ipsec_opt_mp = mp;
10104 		mutex_exit(&connp->conn_lock);
10105 		mutex_exit(&ipss->ipsec_loader_lock);
10106 
10107 		ipsec_loader_loadnow(ipss);
10108 		return (B_TRUE);
10109 	}
10110 	return (B_FALSE);
10111 }
10112 
10113 /*
10114  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10115  * all of them are copied to the conn_t. If the req is "zero", the policy is
10116  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10117  * fields.
10118  * We keep only the latest setting of the policy and thus policy setting
10119  * is not incremental/cumulative.
10120  *
10121  * Requests to set policies with multiple alternative actions will
10122  * go through a different API.
10123  */
10124 int
10125 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10126 {
10127 	uint_t ah_req = 0;
10128 	uint_t esp_req = 0;
10129 	uint_t se_req = 0;
10130 	ipsec_selkey_t sel;
10131 	ipsec_act_t *actp = NULL;
10132 	uint_t nact;
10133 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10134 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10135 	ipsec_policy_root_t *pr;
10136 	ipsec_policy_head_t *ph;
10137 	int fam;
10138 	boolean_t is_pol_reset;
10139 	int error = 0;
10140 	netstack_t	*ns = connp->conn_netstack;
10141 	ip_stack_t	*ipst = ns->netstack_ip;
10142 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10143 
10144 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10145 
10146 	/*
10147 	 * The IP_SEC_OPT option does not allow variable length parameters,
10148 	 * hence a request cannot be NULL.
10149 	 */
10150 	if (req == NULL)
10151 		return (EINVAL);
10152 
10153 	ah_req = req->ipsr_ah_req;
10154 	esp_req = req->ipsr_esp_req;
10155 	se_req = req->ipsr_self_encap_req;
10156 
10157 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10158 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10159 		return (EINVAL);
10160 
10161 	/*
10162 	 * Are we dealing with a request to reset the policy (i.e.
10163 	 * zero requests).
10164 	 */
10165 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10166 	    (esp_req & REQ_MASK) == 0 &&
10167 	    (se_req & REQ_MASK) == 0);
10168 
10169 	if (!is_pol_reset) {
10170 		/*
10171 		 * If we couldn't load IPsec, fail with "protocol
10172 		 * not supported".
10173 		 * IPsec may not have been loaded for a request with zero
10174 		 * policies, so we don't fail in this case.
10175 		 */
10176 		mutex_enter(&ipss->ipsec_loader_lock);
10177 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10178 			mutex_exit(&ipss->ipsec_loader_lock);
10179 			return (EPROTONOSUPPORT);
10180 		}
10181 		mutex_exit(&ipss->ipsec_loader_lock);
10182 
10183 		/*
10184 		 * Test for valid requests. Invalid algorithms
10185 		 * need to be tested by IPsec code because new
10186 		 * algorithms can be added dynamically.
10187 		 */
10188 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10189 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10190 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10191 			return (EINVAL);
10192 		}
10193 
10194 		/*
10195 		 * Only privileged users can issue these
10196 		 * requests.
10197 		 */
10198 		if (((ah_req & IPSEC_PREF_NEVER) ||
10199 		    (esp_req & IPSEC_PREF_NEVER) ||
10200 		    (se_req & IPSEC_PREF_NEVER)) &&
10201 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10202 			return (EPERM);
10203 		}
10204 
10205 		/*
10206 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10207 		 * are mutually exclusive.
10208 		 */
10209 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10210 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10211 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10212 			/* Both of them are set */
10213 			return (EINVAL);
10214 		}
10215 	}
10216 
10217 	mutex_enter(&connp->conn_lock);
10218 
10219 	/*
10220 	 * If we have already cached policies in ip_bind_connected*(), don't
10221 	 * let them change now. We cache policies for connections
10222 	 * whose src,dst [addr, port] is known.
10223 	 */
10224 	if (connp->conn_policy_cached) {
10225 		mutex_exit(&connp->conn_lock);
10226 		return (EINVAL);
10227 	}
10228 
10229 	/*
10230 	 * We have a zero policies, reset the connection policy if already
10231 	 * set. This will cause the connection to inherit the
10232 	 * global policy, if any.
10233 	 */
10234 	if (is_pol_reset) {
10235 		if (connp->conn_policy != NULL) {
10236 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10237 			connp->conn_policy = NULL;
10238 		}
10239 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10240 		connp->conn_in_enforce_policy = B_FALSE;
10241 		connp->conn_out_enforce_policy = B_FALSE;
10242 		mutex_exit(&connp->conn_lock);
10243 		return (0);
10244 	}
10245 
10246 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10247 	    ipst->ips_netstack);
10248 	if (ph == NULL)
10249 		goto enomem;
10250 
10251 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10252 	if (actp == NULL)
10253 		goto enomem;
10254 
10255 	/*
10256 	 * Always allocate IPv4 policy entries, since they can also
10257 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10258 	 */
10259 	bzero(&sel, sizeof (sel));
10260 	sel.ipsl_valid = IPSL_IPV4;
10261 
10262 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10263 	    ipst->ips_netstack);
10264 	if (pin4 == NULL)
10265 		goto enomem;
10266 
10267 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10268 	    ipst->ips_netstack);
10269 	if (pout4 == NULL)
10270 		goto enomem;
10271 
10272 	if (connp->conn_af_isv6) {
10273 		/*
10274 		 * We're looking at a v6 socket, also allocate the
10275 		 * v6-specific entries...
10276 		 */
10277 		sel.ipsl_valid = IPSL_IPV6;
10278 		pin6 = ipsec_policy_create(&sel, actp, nact,
10279 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10280 		if (pin6 == NULL)
10281 			goto enomem;
10282 
10283 		pout6 = ipsec_policy_create(&sel, actp, nact,
10284 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10285 		if (pout6 == NULL)
10286 			goto enomem;
10287 
10288 		/*
10289 		 * .. and file them away in the right place.
10290 		 */
10291 		fam = IPSEC_AF_V6;
10292 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10293 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10294 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10295 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10296 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10297 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10298 	}
10299 
10300 	ipsec_actvec_free(actp, nact);
10301 
10302 	/*
10303 	 * File the v4 policies.
10304 	 */
10305 	fam = IPSEC_AF_V4;
10306 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10307 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10308 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10309 
10310 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10311 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10312 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10313 
10314 	/*
10315 	 * If the requests need security, set enforce_policy.
10316 	 * If the requests are IPSEC_PREF_NEVER, one should
10317 	 * still set conn_out_enforce_policy so that an ipsec_out
10318 	 * gets attached in ip_wput. This is needed so that
10319 	 * for connections that we don't cache policy in ip_bind,
10320 	 * if global policy matches in ip_wput_attach_policy, we
10321 	 * don't wrongly inherit global policy. Similarly, we need
10322 	 * to set conn_in_enforce_policy also so that we don't verify
10323 	 * policy wrongly.
10324 	 */
10325 	if ((ah_req & REQ_MASK) != 0 ||
10326 	    (esp_req & REQ_MASK) != 0 ||
10327 	    (se_req & REQ_MASK) != 0) {
10328 		connp->conn_in_enforce_policy = B_TRUE;
10329 		connp->conn_out_enforce_policy = B_TRUE;
10330 		connp->conn_flags |= IPCL_CHECK_POLICY;
10331 	}
10332 
10333 	mutex_exit(&connp->conn_lock);
10334 	return (error);
10335 #undef REQ_MASK
10336 
10337 	/*
10338 	 * Common memory-allocation-failure exit path.
10339 	 */
10340 enomem:
10341 	mutex_exit(&connp->conn_lock);
10342 	if (actp != NULL)
10343 		ipsec_actvec_free(actp, nact);
10344 	if (pin4 != NULL)
10345 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10346 	if (pout4 != NULL)
10347 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10348 	if (pin6 != NULL)
10349 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10350 	if (pout6 != NULL)
10351 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10352 	return (ENOMEM);
10353 }
10354 
10355 /*
10356  * Only for options that pass in an IP addr. Currently only V4 options
10357  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10358  * So this function assumes level is IPPROTO_IP
10359  */
10360 int
10361 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10362     mblk_t *first_mp)
10363 {
10364 	ipif_t *ipif = NULL;
10365 	int error;
10366 	ill_t *ill;
10367 	int zoneid;
10368 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10369 
10370 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10371 
10372 	if (addr != INADDR_ANY || checkonly) {
10373 		ASSERT(connp != NULL);
10374 		zoneid = IPCL_ZONEID(connp);
10375 		if (option == IP_NEXTHOP) {
10376 			ipif = ipif_lookup_onlink_addr(addr,
10377 			    connp->conn_zoneid, ipst);
10378 		} else {
10379 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10380 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10381 			    &error, ipst);
10382 		}
10383 		if (ipif == NULL) {
10384 			if (error == EINPROGRESS)
10385 				return (error);
10386 			if ((option == IP_MULTICAST_IF) ||
10387 			    (option == IP_NEXTHOP))
10388 				return (EHOSTUNREACH);
10389 			else
10390 				return (EINVAL);
10391 		} else if (checkonly) {
10392 			if (option == IP_MULTICAST_IF) {
10393 				ill = ipif->ipif_ill;
10394 				/* not supported by the virtual network iface */
10395 				if (IS_VNI(ill)) {
10396 					ipif_refrele(ipif);
10397 					return (EINVAL);
10398 				}
10399 			}
10400 			ipif_refrele(ipif);
10401 			return (0);
10402 		}
10403 		ill = ipif->ipif_ill;
10404 		mutex_enter(&connp->conn_lock);
10405 		mutex_enter(&ill->ill_lock);
10406 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10407 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10408 			mutex_exit(&ill->ill_lock);
10409 			mutex_exit(&connp->conn_lock);
10410 			ipif_refrele(ipif);
10411 			return (option == IP_MULTICAST_IF ?
10412 			    EHOSTUNREACH : EINVAL);
10413 		}
10414 	} else {
10415 		mutex_enter(&connp->conn_lock);
10416 	}
10417 
10418 	/* None of the options below are supported on the VNI */
10419 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10420 		mutex_exit(&ill->ill_lock);
10421 		mutex_exit(&connp->conn_lock);
10422 		ipif_refrele(ipif);
10423 		return (EINVAL);
10424 	}
10425 
10426 	switch (option) {
10427 	case IP_MULTICAST_IF:
10428 		connp->conn_multicast_ipif = ipif;
10429 		break;
10430 	case IP_NEXTHOP:
10431 		connp->conn_nexthop_v4 = addr;
10432 		connp->conn_nexthop_set = B_TRUE;
10433 		break;
10434 	}
10435 
10436 	if (ipif != NULL) {
10437 		mutex_exit(&ill->ill_lock);
10438 		mutex_exit(&connp->conn_lock);
10439 		ipif_refrele(ipif);
10440 		return (0);
10441 	}
10442 	mutex_exit(&connp->conn_lock);
10443 	/* We succeded in cleared the option */
10444 	return (0);
10445 }
10446 
10447 /*
10448  * For options that pass in an ifindex specifying the ill. V6 options always
10449  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10450  */
10451 int
10452 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10453     int level, int option, mblk_t *first_mp)
10454 {
10455 	ill_t *ill = NULL;
10456 	int error = 0;
10457 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10458 
10459 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10460 	if (ifindex != 0) {
10461 		ASSERT(connp != NULL);
10462 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10463 		    first_mp, ip_restart_optmgmt, &error, ipst);
10464 		if (ill != NULL) {
10465 			if (checkonly) {
10466 				/* not supported by the virtual network iface */
10467 				if (IS_VNI(ill)) {
10468 					ill_refrele(ill);
10469 					return (EINVAL);
10470 				}
10471 				ill_refrele(ill);
10472 				return (0);
10473 			}
10474 			if (!ipif_lookup_zoneid(ill, connp->conn_zoneid,
10475 			    0, NULL)) {
10476 				ill_refrele(ill);
10477 				ill = NULL;
10478 				mutex_enter(&connp->conn_lock);
10479 				goto setit;
10480 			}
10481 			mutex_enter(&connp->conn_lock);
10482 			mutex_enter(&ill->ill_lock);
10483 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10484 				mutex_exit(&ill->ill_lock);
10485 				mutex_exit(&connp->conn_lock);
10486 				ill_refrele(ill);
10487 				ill = NULL;
10488 				mutex_enter(&connp->conn_lock);
10489 			}
10490 			goto setit;
10491 		} else if (error == EINPROGRESS) {
10492 			return (error);
10493 		} else {
10494 			error = 0;
10495 		}
10496 	}
10497 	mutex_enter(&connp->conn_lock);
10498 setit:
10499 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10500 
10501 	/*
10502 	 * The options below assume that the ILL (if any) transmits and/or
10503 	 * receives traffic. Neither of which is true for the virtual network
10504 	 * interface, so fail setting these on a VNI.
10505 	 */
10506 	if (IS_VNI(ill)) {
10507 		ASSERT(ill != NULL);
10508 		mutex_exit(&ill->ill_lock);
10509 		mutex_exit(&connp->conn_lock);
10510 		ill_refrele(ill);
10511 		return (EINVAL);
10512 	}
10513 
10514 	if (level == IPPROTO_IP) {
10515 		switch (option) {
10516 		case IP_BOUND_IF:
10517 			connp->conn_incoming_ill = ill;
10518 			connp->conn_outgoing_ill = ill;
10519 			break;
10520 
10521 		case IP_MULTICAST_IF:
10522 			/*
10523 			 * This option is an internal special. The socket
10524 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10525 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10526 			 * specifies an ifindex and we try first on V6 ill's.
10527 			 * If we don't find one, we they try using on v4 ill's
10528 			 * intenally and we come here.
10529 			 */
10530 			if (!checkonly && ill != NULL) {
10531 				ipif_t	*ipif;
10532 				ipif = ill->ill_ipif;
10533 
10534 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10535 					mutex_exit(&ill->ill_lock);
10536 					mutex_exit(&connp->conn_lock);
10537 					ill_refrele(ill);
10538 					ill = NULL;
10539 					mutex_enter(&connp->conn_lock);
10540 				} else {
10541 					connp->conn_multicast_ipif = ipif;
10542 				}
10543 			}
10544 			break;
10545 
10546 		case IP_DHCPINIT_IF:
10547 			if (connp->conn_dhcpinit_ill != NULL) {
10548 				/*
10549 				 * We've locked the conn so conn_cleanup_ill()
10550 				 * cannot clear conn_dhcpinit_ill -- so it's
10551 				 * safe to access the ill.
10552 				 */
10553 				ill_t *oill = connp->conn_dhcpinit_ill;
10554 
10555 				ASSERT(oill->ill_dhcpinit != 0);
10556 				atomic_dec_32(&oill->ill_dhcpinit);
10557 				connp->conn_dhcpinit_ill = NULL;
10558 			}
10559 
10560 			if (ill != NULL) {
10561 				connp->conn_dhcpinit_ill = ill;
10562 				atomic_inc_32(&ill->ill_dhcpinit);
10563 			}
10564 			break;
10565 		}
10566 	} else {
10567 		switch (option) {
10568 		case IPV6_BOUND_IF:
10569 			connp->conn_incoming_ill = ill;
10570 			connp->conn_outgoing_ill = ill;
10571 			break;
10572 
10573 		case IPV6_MULTICAST_IF:
10574 			/*
10575 			 * Set conn_multicast_ill to be the IPv6 ill.
10576 			 * Set conn_multicast_ipif to be an IPv4 ipif
10577 			 * for ifindex to make IPv4 mapped addresses
10578 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10579 			 * Even if no IPv6 ill exists for the ifindex
10580 			 * we need to check for an IPv4 ifindex in order
10581 			 * for this to work with mapped addresses. In that
10582 			 * case only set conn_multicast_ipif.
10583 			 */
10584 			if (!checkonly) {
10585 				if (ifindex == 0) {
10586 					connp->conn_multicast_ill = NULL;
10587 					connp->conn_multicast_ipif = NULL;
10588 				} else if (ill != NULL) {
10589 					connp->conn_multicast_ill = ill;
10590 				}
10591 			}
10592 			break;
10593 		}
10594 	}
10595 
10596 	if (ill != NULL) {
10597 		mutex_exit(&ill->ill_lock);
10598 		mutex_exit(&connp->conn_lock);
10599 		ill_refrele(ill);
10600 		return (0);
10601 	}
10602 	mutex_exit(&connp->conn_lock);
10603 	/*
10604 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10605 	 * locate the ill and could not set the option (ifindex != 0)
10606 	 */
10607 	return (ifindex == 0 ? 0 : EINVAL);
10608 }
10609 
10610 /* This routine sets socket options. */
10611 /* ARGSUSED */
10612 int
10613 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10614     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10615     void *dummy, cred_t *cr, mblk_t *first_mp)
10616 {
10617 	int		*i1 = (int *)invalp;
10618 	conn_t		*connp = Q_TO_CONN(q);
10619 	int		error = 0;
10620 	boolean_t	checkonly;
10621 	ire_t		*ire;
10622 	boolean_t	found;
10623 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10624 
10625 	switch (optset_context) {
10626 
10627 	case SETFN_OPTCOM_CHECKONLY:
10628 		checkonly = B_TRUE;
10629 		/*
10630 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10631 		 * inlen != 0 implies value supplied and
10632 		 * 	we have to "pretend" to set it.
10633 		 * inlen == 0 implies that there is no
10634 		 * 	value part in T_CHECK request and just validation
10635 		 * done elsewhere should be enough, we just return here.
10636 		 */
10637 		if (inlen == 0) {
10638 			*outlenp = 0;
10639 			return (0);
10640 		}
10641 		break;
10642 	case SETFN_OPTCOM_NEGOTIATE:
10643 	case SETFN_UD_NEGOTIATE:
10644 	case SETFN_CONN_NEGOTIATE:
10645 		checkonly = B_FALSE;
10646 		break;
10647 	default:
10648 		/*
10649 		 * We should never get here
10650 		 */
10651 		*outlenp = 0;
10652 		return (EINVAL);
10653 	}
10654 
10655 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10656 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10657 
10658 	/*
10659 	 * For fixed length options, no sanity check
10660 	 * of passed in length is done. It is assumed *_optcom_req()
10661 	 * routines do the right thing.
10662 	 */
10663 
10664 	switch (level) {
10665 	case SOL_SOCKET:
10666 		/*
10667 		 * conn_lock protects the bitfields, and is used to
10668 		 * set the fields atomically.
10669 		 */
10670 		switch (name) {
10671 		case SO_BROADCAST:
10672 			if (!checkonly) {
10673 				/* TODO: use value someplace? */
10674 				mutex_enter(&connp->conn_lock);
10675 				connp->conn_broadcast = *i1 ? 1 : 0;
10676 				mutex_exit(&connp->conn_lock);
10677 			}
10678 			break;	/* goto sizeof (int) option return */
10679 		case SO_USELOOPBACK:
10680 			if (!checkonly) {
10681 				/* TODO: use value someplace? */
10682 				mutex_enter(&connp->conn_lock);
10683 				connp->conn_loopback = *i1 ? 1 : 0;
10684 				mutex_exit(&connp->conn_lock);
10685 			}
10686 			break;	/* goto sizeof (int) option return */
10687 		case SO_DONTROUTE:
10688 			if (!checkonly) {
10689 				mutex_enter(&connp->conn_lock);
10690 				connp->conn_dontroute = *i1 ? 1 : 0;
10691 				mutex_exit(&connp->conn_lock);
10692 			}
10693 			break;	/* goto sizeof (int) option return */
10694 		case SO_REUSEADDR:
10695 			if (!checkonly) {
10696 				mutex_enter(&connp->conn_lock);
10697 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10698 				mutex_exit(&connp->conn_lock);
10699 			}
10700 			break;	/* goto sizeof (int) option return */
10701 		case SO_PROTOTYPE:
10702 			if (!checkonly) {
10703 				mutex_enter(&connp->conn_lock);
10704 				connp->conn_proto = *i1;
10705 				mutex_exit(&connp->conn_lock);
10706 			}
10707 			break;	/* goto sizeof (int) option return */
10708 		case SO_ALLZONES:
10709 			if (!checkonly) {
10710 				mutex_enter(&connp->conn_lock);
10711 				if (IPCL_IS_BOUND(connp)) {
10712 					mutex_exit(&connp->conn_lock);
10713 					return (EINVAL);
10714 				}
10715 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10716 				mutex_exit(&connp->conn_lock);
10717 			}
10718 			break;	/* goto sizeof (int) option return */
10719 		case SO_ANON_MLP:
10720 			if (!checkonly) {
10721 				mutex_enter(&connp->conn_lock);
10722 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10723 				mutex_exit(&connp->conn_lock);
10724 			}
10725 			break;	/* goto sizeof (int) option return */
10726 		case SO_MAC_EXEMPT:
10727 			if (secpolicy_net_mac_aware(cr) != 0 ||
10728 			    IPCL_IS_BOUND(connp))
10729 				return (EACCES);
10730 			if (!checkonly) {
10731 				mutex_enter(&connp->conn_lock);
10732 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10733 				mutex_exit(&connp->conn_lock);
10734 			}
10735 			break;	/* goto sizeof (int) option return */
10736 		default:
10737 			/*
10738 			 * "soft" error (negative)
10739 			 * option not handled at this level
10740 			 * Note: Do not modify *outlenp
10741 			 */
10742 			return (-EINVAL);
10743 		}
10744 		break;
10745 	case IPPROTO_IP:
10746 		switch (name) {
10747 		case IP_NEXTHOP:
10748 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10749 				return (EPERM);
10750 			/* FALLTHRU */
10751 		case IP_MULTICAST_IF: {
10752 			ipaddr_t addr = *i1;
10753 
10754 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10755 			    first_mp);
10756 			if (error != 0)
10757 				return (error);
10758 			break;	/* goto sizeof (int) option return */
10759 		}
10760 
10761 		case IP_MULTICAST_TTL:
10762 			/* Recorded in transport above IP */
10763 			*outvalp = *invalp;
10764 			*outlenp = sizeof (uchar_t);
10765 			return (0);
10766 		case IP_MULTICAST_LOOP:
10767 			if (!checkonly) {
10768 				mutex_enter(&connp->conn_lock);
10769 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10770 				mutex_exit(&connp->conn_lock);
10771 			}
10772 			*outvalp = *invalp;
10773 			*outlenp = sizeof (uchar_t);
10774 			return (0);
10775 		case IP_ADD_MEMBERSHIP:
10776 		case MCAST_JOIN_GROUP:
10777 		case IP_DROP_MEMBERSHIP:
10778 		case MCAST_LEAVE_GROUP: {
10779 			struct ip_mreq *mreqp;
10780 			struct group_req *greqp;
10781 			ire_t *ire;
10782 			boolean_t done = B_FALSE;
10783 			ipaddr_t group, ifaddr;
10784 			struct sockaddr_in *sin;
10785 			uint32_t *ifindexp;
10786 			boolean_t mcast_opt = B_TRUE;
10787 			mcast_record_t fmode;
10788 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10789 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10790 
10791 			switch (name) {
10792 			case IP_ADD_MEMBERSHIP:
10793 				mcast_opt = B_FALSE;
10794 				/* FALLTHRU */
10795 			case MCAST_JOIN_GROUP:
10796 				fmode = MODE_IS_EXCLUDE;
10797 				optfn = ip_opt_add_group;
10798 				break;
10799 
10800 			case IP_DROP_MEMBERSHIP:
10801 				mcast_opt = B_FALSE;
10802 				/* FALLTHRU */
10803 			case MCAST_LEAVE_GROUP:
10804 				fmode = MODE_IS_INCLUDE;
10805 				optfn = ip_opt_delete_group;
10806 				break;
10807 			}
10808 
10809 			if (mcast_opt) {
10810 				greqp = (struct group_req *)i1;
10811 				sin = (struct sockaddr_in *)&greqp->gr_group;
10812 				if (sin->sin_family != AF_INET) {
10813 					*outlenp = 0;
10814 					return (ENOPROTOOPT);
10815 				}
10816 				group = (ipaddr_t)sin->sin_addr.s_addr;
10817 				ifaddr = INADDR_ANY;
10818 				ifindexp = &greqp->gr_interface;
10819 			} else {
10820 				mreqp = (struct ip_mreq *)i1;
10821 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10822 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10823 				ifindexp = NULL;
10824 			}
10825 
10826 			/*
10827 			 * In the multirouting case, we need to replicate
10828 			 * the request on all interfaces that will take part
10829 			 * in replication.  We do so because multirouting is
10830 			 * reflective, thus we will probably receive multi-
10831 			 * casts on those interfaces.
10832 			 * The ip_multirt_apply_membership() succeeds if the
10833 			 * operation succeeds on at least one interface.
10834 			 */
10835 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10836 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10837 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10838 			if (ire != NULL) {
10839 				if (ire->ire_flags & RTF_MULTIRT) {
10840 					error = ip_multirt_apply_membership(
10841 					    optfn, ire, connp, checkonly, group,
10842 					    fmode, INADDR_ANY, first_mp);
10843 					done = B_TRUE;
10844 				}
10845 				ire_refrele(ire);
10846 			}
10847 			if (!done) {
10848 				error = optfn(connp, checkonly, group, ifaddr,
10849 				    ifindexp, fmode, INADDR_ANY, first_mp);
10850 			}
10851 			if (error) {
10852 				/*
10853 				 * EINPROGRESS is a soft error, needs retry
10854 				 * so don't make *outlenp zero.
10855 				 */
10856 				if (error != EINPROGRESS)
10857 					*outlenp = 0;
10858 				return (error);
10859 			}
10860 			/* OK return - copy input buffer into output buffer */
10861 			if (invalp != outvalp) {
10862 				/* don't trust bcopy for identical src/dst */
10863 				bcopy(invalp, outvalp, inlen);
10864 			}
10865 			*outlenp = inlen;
10866 			return (0);
10867 		}
10868 		case IP_BLOCK_SOURCE:
10869 		case IP_UNBLOCK_SOURCE:
10870 		case IP_ADD_SOURCE_MEMBERSHIP:
10871 		case IP_DROP_SOURCE_MEMBERSHIP:
10872 		case MCAST_BLOCK_SOURCE:
10873 		case MCAST_UNBLOCK_SOURCE:
10874 		case MCAST_JOIN_SOURCE_GROUP:
10875 		case MCAST_LEAVE_SOURCE_GROUP: {
10876 			struct ip_mreq_source *imreqp;
10877 			struct group_source_req *gsreqp;
10878 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10879 			uint32_t ifindex = 0;
10880 			mcast_record_t fmode;
10881 			struct sockaddr_in *sin;
10882 			ire_t *ire;
10883 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10884 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10885 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10886 
10887 			switch (name) {
10888 			case IP_BLOCK_SOURCE:
10889 				mcast_opt = B_FALSE;
10890 				/* FALLTHRU */
10891 			case MCAST_BLOCK_SOURCE:
10892 				fmode = MODE_IS_EXCLUDE;
10893 				optfn = ip_opt_add_group;
10894 				break;
10895 
10896 			case IP_UNBLOCK_SOURCE:
10897 				mcast_opt = B_FALSE;
10898 				/* FALLTHRU */
10899 			case MCAST_UNBLOCK_SOURCE:
10900 				fmode = MODE_IS_EXCLUDE;
10901 				optfn = ip_opt_delete_group;
10902 				break;
10903 
10904 			case IP_ADD_SOURCE_MEMBERSHIP:
10905 				mcast_opt = B_FALSE;
10906 				/* FALLTHRU */
10907 			case MCAST_JOIN_SOURCE_GROUP:
10908 				fmode = MODE_IS_INCLUDE;
10909 				optfn = ip_opt_add_group;
10910 				break;
10911 
10912 			case IP_DROP_SOURCE_MEMBERSHIP:
10913 				mcast_opt = B_FALSE;
10914 				/* FALLTHRU */
10915 			case MCAST_LEAVE_SOURCE_GROUP:
10916 				fmode = MODE_IS_INCLUDE;
10917 				optfn = ip_opt_delete_group;
10918 				break;
10919 			}
10920 
10921 			if (mcast_opt) {
10922 				gsreqp = (struct group_source_req *)i1;
10923 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10924 					*outlenp = 0;
10925 					return (ENOPROTOOPT);
10926 				}
10927 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10928 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10929 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10930 				src = (ipaddr_t)sin->sin_addr.s_addr;
10931 				ifindex = gsreqp->gsr_interface;
10932 			} else {
10933 				imreqp = (struct ip_mreq_source *)i1;
10934 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10935 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10936 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10937 			}
10938 
10939 			/*
10940 			 * In the multirouting case, we need to replicate
10941 			 * the request as noted in the mcast cases above.
10942 			 */
10943 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10944 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10945 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10946 			if (ire != NULL) {
10947 				if (ire->ire_flags & RTF_MULTIRT) {
10948 					error = ip_multirt_apply_membership(
10949 					    optfn, ire, connp, checkonly, grp,
10950 					    fmode, src, first_mp);
10951 					done = B_TRUE;
10952 				}
10953 				ire_refrele(ire);
10954 			}
10955 			if (!done) {
10956 				error = optfn(connp, checkonly, grp, ifaddr,
10957 				    &ifindex, fmode, src, first_mp);
10958 			}
10959 			if (error != 0) {
10960 				/*
10961 				 * EINPROGRESS is a soft error, needs retry
10962 				 * so don't make *outlenp zero.
10963 				 */
10964 				if (error != EINPROGRESS)
10965 					*outlenp = 0;
10966 				return (error);
10967 			}
10968 			/* OK return - copy input buffer into output buffer */
10969 			if (invalp != outvalp) {
10970 				bcopy(invalp, outvalp, inlen);
10971 			}
10972 			*outlenp = inlen;
10973 			return (0);
10974 		}
10975 		case IP_SEC_OPT:
10976 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10977 			if (error != 0) {
10978 				*outlenp = 0;
10979 				return (error);
10980 			}
10981 			break;
10982 		case IP_HDRINCL:
10983 		case IP_OPTIONS:
10984 		case T_IP_OPTIONS:
10985 		case IP_TOS:
10986 		case T_IP_TOS:
10987 		case IP_TTL:
10988 		case IP_RECVDSTADDR:
10989 		case IP_RECVOPTS:
10990 			/* OK return - copy input buffer into output buffer */
10991 			if (invalp != outvalp) {
10992 				/* don't trust bcopy for identical src/dst */
10993 				bcopy(invalp, outvalp, inlen);
10994 			}
10995 			*outlenp = inlen;
10996 			return (0);
10997 		case IP_RECVIF:
10998 			/* Retrieve the inbound interface index */
10999 			if (!checkonly) {
11000 				mutex_enter(&connp->conn_lock);
11001 				connp->conn_recvif = *i1 ? 1 : 0;
11002 				mutex_exit(&connp->conn_lock);
11003 			}
11004 			break;	/* goto sizeof (int) option return */
11005 		case IP_RECVPKTINFO:
11006 			if (!checkonly) {
11007 				mutex_enter(&connp->conn_lock);
11008 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11009 				mutex_exit(&connp->conn_lock);
11010 			}
11011 			break;	/* goto sizeof (int) option return */
11012 		case IP_RECVSLLA:
11013 			/* Retrieve the source link layer address */
11014 			if (!checkonly) {
11015 				mutex_enter(&connp->conn_lock);
11016 				connp->conn_recvslla = *i1 ? 1 : 0;
11017 				mutex_exit(&connp->conn_lock);
11018 			}
11019 			break;	/* goto sizeof (int) option return */
11020 		case MRT_INIT:
11021 		case MRT_DONE:
11022 		case MRT_ADD_VIF:
11023 		case MRT_DEL_VIF:
11024 		case MRT_ADD_MFC:
11025 		case MRT_DEL_MFC:
11026 		case MRT_ASSERT:
11027 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11028 				*outlenp = 0;
11029 				return (error);
11030 			}
11031 			error = ip_mrouter_set((int)name, q, checkonly,
11032 			    (uchar_t *)invalp, inlen, first_mp);
11033 			if (error) {
11034 				*outlenp = 0;
11035 				return (error);
11036 			}
11037 			/* OK return - copy input buffer into output buffer */
11038 			if (invalp != outvalp) {
11039 				/* don't trust bcopy for identical src/dst */
11040 				bcopy(invalp, outvalp, inlen);
11041 			}
11042 			*outlenp = inlen;
11043 			return (0);
11044 		case IP_BOUND_IF:
11045 		case IP_DHCPINIT_IF:
11046 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11047 			    level, name, first_mp);
11048 			if (error != 0)
11049 				return (error);
11050 			break; 		/* goto sizeof (int) option return */
11051 
11052 		case IP_UNSPEC_SRC:
11053 			/* Allow sending with a zero source address */
11054 			if (!checkonly) {
11055 				mutex_enter(&connp->conn_lock);
11056 				connp->conn_unspec_src = *i1 ? 1 : 0;
11057 				mutex_exit(&connp->conn_lock);
11058 			}
11059 			break;	/* goto sizeof (int) option return */
11060 		default:
11061 			/*
11062 			 * "soft" error (negative)
11063 			 * option not handled at this level
11064 			 * Note: Do not modify *outlenp
11065 			 */
11066 			return (-EINVAL);
11067 		}
11068 		break;
11069 	case IPPROTO_IPV6:
11070 		switch (name) {
11071 		case IPV6_BOUND_IF:
11072 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11073 			    level, name, first_mp);
11074 			if (error != 0)
11075 				return (error);
11076 			break; 		/* goto sizeof (int) option return */
11077 
11078 		case IPV6_MULTICAST_IF:
11079 			/*
11080 			 * The only possible errors are EINPROGRESS and
11081 			 * EINVAL. EINPROGRESS will be restarted and is not
11082 			 * a hard error. We call this option on both V4 and V6
11083 			 * If both return EINVAL, then this call returns
11084 			 * EINVAL. If at least one of them succeeds we
11085 			 * return success.
11086 			 */
11087 			found = B_FALSE;
11088 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11089 			    level, name, first_mp);
11090 			if (error == EINPROGRESS)
11091 				return (error);
11092 			if (error == 0)
11093 				found = B_TRUE;
11094 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11095 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11096 			if (error == 0)
11097 				found = B_TRUE;
11098 			if (!found)
11099 				return (error);
11100 			break; 		/* goto sizeof (int) option return */
11101 
11102 		case IPV6_MULTICAST_HOPS:
11103 			/* Recorded in transport above IP */
11104 			break;	/* goto sizeof (int) option return */
11105 		case IPV6_MULTICAST_LOOP:
11106 			if (!checkonly) {
11107 				mutex_enter(&connp->conn_lock);
11108 				connp->conn_multicast_loop = *i1;
11109 				mutex_exit(&connp->conn_lock);
11110 			}
11111 			break;	/* goto sizeof (int) option return */
11112 		case IPV6_JOIN_GROUP:
11113 		case MCAST_JOIN_GROUP:
11114 		case IPV6_LEAVE_GROUP:
11115 		case MCAST_LEAVE_GROUP: {
11116 			struct ipv6_mreq *ip_mreqp;
11117 			struct group_req *greqp;
11118 			ire_t *ire;
11119 			boolean_t done = B_FALSE;
11120 			in6_addr_t groupv6;
11121 			uint32_t ifindex;
11122 			boolean_t mcast_opt = B_TRUE;
11123 			mcast_record_t fmode;
11124 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11125 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11126 
11127 			switch (name) {
11128 			case IPV6_JOIN_GROUP:
11129 				mcast_opt = B_FALSE;
11130 				/* FALLTHRU */
11131 			case MCAST_JOIN_GROUP:
11132 				fmode = MODE_IS_EXCLUDE;
11133 				optfn = ip_opt_add_group_v6;
11134 				break;
11135 
11136 			case IPV6_LEAVE_GROUP:
11137 				mcast_opt = B_FALSE;
11138 				/* FALLTHRU */
11139 			case MCAST_LEAVE_GROUP:
11140 				fmode = MODE_IS_INCLUDE;
11141 				optfn = ip_opt_delete_group_v6;
11142 				break;
11143 			}
11144 
11145 			if (mcast_opt) {
11146 				struct sockaddr_in *sin;
11147 				struct sockaddr_in6 *sin6;
11148 				greqp = (struct group_req *)i1;
11149 				if (greqp->gr_group.ss_family == AF_INET) {
11150 					sin = (struct sockaddr_in *)
11151 					    &(greqp->gr_group);
11152 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11153 					    &groupv6);
11154 				} else {
11155 					sin6 = (struct sockaddr_in6 *)
11156 					    &(greqp->gr_group);
11157 					groupv6 = sin6->sin6_addr;
11158 				}
11159 				ifindex = greqp->gr_interface;
11160 			} else {
11161 				ip_mreqp = (struct ipv6_mreq *)i1;
11162 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11163 				ifindex = ip_mreqp->ipv6mr_interface;
11164 			}
11165 			/*
11166 			 * In the multirouting case, we need to replicate
11167 			 * the request on all interfaces that will take part
11168 			 * in replication.  We do so because multirouting is
11169 			 * reflective, thus we will probably receive multi-
11170 			 * casts on those interfaces.
11171 			 * The ip_multirt_apply_membership_v6() succeeds if
11172 			 * the operation succeeds on at least one interface.
11173 			 */
11174 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11175 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11176 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11177 			if (ire != NULL) {
11178 				if (ire->ire_flags & RTF_MULTIRT) {
11179 					error = ip_multirt_apply_membership_v6(
11180 					    optfn, ire, connp, checkonly,
11181 					    &groupv6, fmode, &ipv6_all_zeros,
11182 					    first_mp);
11183 					done = B_TRUE;
11184 				}
11185 				ire_refrele(ire);
11186 			}
11187 			if (!done) {
11188 				error = optfn(connp, checkonly, &groupv6,
11189 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11190 			}
11191 			if (error) {
11192 				/*
11193 				 * EINPROGRESS is a soft error, needs retry
11194 				 * so don't make *outlenp zero.
11195 				 */
11196 				if (error != EINPROGRESS)
11197 					*outlenp = 0;
11198 				return (error);
11199 			}
11200 			/* OK return - copy input buffer into output buffer */
11201 			if (invalp != outvalp) {
11202 				/* don't trust bcopy for identical src/dst */
11203 				bcopy(invalp, outvalp, inlen);
11204 			}
11205 			*outlenp = inlen;
11206 			return (0);
11207 		}
11208 		case MCAST_BLOCK_SOURCE:
11209 		case MCAST_UNBLOCK_SOURCE:
11210 		case MCAST_JOIN_SOURCE_GROUP:
11211 		case MCAST_LEAVE_SOURCE_GROUP: {
11212 			struct group_source_req *gsreqp;
11213 			in6_addr_t v6grp, v6src;
11214 			uint32_t ifindex;
11215 			mcast_record_t fmode;
11216 			ire_t *ire;
11217 			boolean_t done = B_FALSE;
11218 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11219 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11220 
11221 			switch (name) {
11222 			case MCAST_BLOCK_SOURCE:
11223 				fmode = MODE_IS_EXCLUDE;
11224 				optfn = ip_opt_add_group_v6;
11225 				break;
11226 			case MCAST_UNBLOCK_SOURCE:
11227 				fmode = MODE_IS_EXCLUDE;
11228 				optfn = ip_opt_delete_group_v6;
11229 				break;
11230 			case MCAST_JOIN_SOURCE_GROUP:
11231 				fmode = MODE_IS_INCLUDE;
11232 				optfn = ip_opt_add_group_v6;
11233 				break;
11234 			case MCAST_LEAVE_SOURCE_GROUP:
11235 				fmode = MODE_IS_INCLUDE;
11236 				optfn = ip_opt_delete_group_v6;
11237 				break;
11238 			}
11239 
11240 			gsreqp = (struct group_source_req *)i1;
11241 			ifindex = gsreqp->gsr_interface;
11242 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11243 				struct sockaddr_in *s;
11244 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11245 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11246 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11247 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11248 			} else {
11249 				struct sockaddr_in6 *s6;
11250 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11251 				v6grp = s6->sin6_addr;
11252 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11253 				v6src = s6->sin6_addr;
11254 			}
11255 
11256 			/*
11257 			 * In the multirouting case, we need to replicate
11258 			 * the request as noted in the mcast cases above.
11259 			 */
11260 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11261 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11262 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11263 			if (ire != NULL) {
11264 				if (ire->ire_flags & RTF_MULTIRT) {
11265 					error = ip_multirt_apply_membership_v6(
11266 					    optfn, ire, connp, checkonly,
11267 					    &v6grp, fmode, &v6src, first_mp);
11268 					done = B_TRUE;
11269 				}
11270 				ire_refrele(ire);
11271 			}
11272 			if (!done) {
11273 				error = optfn(connp, checkonly, &v6grp,
11274 				    ifindex, fmode, &v6src, first_mp);
11275 			}
11276 			if (error != 0) {
11277 				/*
11278 				 * EINPROGRESS is a soft error, needs retry
11279 				 * so don't make *outlenp zero.
11280 				 */
11281 				if (error != EINPROGRESS)
11282 					*outlenp = 0;
11283 				return (error);
11284 			}
11285 			/* OK return - copy input buffer into output buffer */
11286 			if (invalp != outvalp) {
11287 				bcopy(invalp, outvalp, inlen);
11288 			}
11289 			*outlenp = inlen;
11290 			return (0);
11291 		}
11292 		case IPV6_UNICAST_HOPS:
11293 			/* Recorded in transport above IP */
11294 			break;	/* goto sizeof (int) option return */
11295 		case IPV6_UNSPEC_SRC:
11296 			/* Allow sending with a zero source address */
11297 			if (!checkonly) {
11298 				mutex_enter(&connp->conn_lock);
11299 				connp->conn_unspec_src = *i1 ? 1 : 0;
11300 				mutex_exit(&connp->conn_lock);
11301 			}
11302 			break;	/* goto sizeof (int) option return */
11303 		case IPV6_RECVPKTINFO:
11304 			if (!checkonly) {
11305 				mutex_enter(&connp->conn_lock);
11306 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11307 				mutex_exit(&connp->conn_lock);
11308 			}
11309 			break;	/* goto sizeof (int) option return */
11310 		case IPV6_RECVTCLASS:
11311 			if (!checkonly) {
11312 				if (*i1 < 0 || *i1 > 1) {
11313 					return (EINVAL);
11314 				}
11315 				mutex_enter(&connp->conn_lock);
11316 				connp->conn_ipv6_recvtclass = *i1;
11317 				mutex_exit(&connp->conn_lock);
11318 			}
11319 			break;
11320 		case IPV6_RECVPATHMTU:
11321 			if (!checkonly) {
11322 				if (*i1 < 0 || *i1 > 1) {
11323 					return (EINVAL);
11324 				}
11325 				mutex_enter(&connp->conn_lock);
11326 				connp->conn_ipv6_recvpathmtu = *i1;
11327 				mutex_exit(&connp->conn_lock);
11328 			}
11329 			break;
11330 		case IPV6_RECVHOPLIMIT:
11331 			if (!checkonly) {
11332 				mutex_enter(&connp->conn_lock);
11333 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11334 				mutex_exit(&connp->conn_lock);
11335 			}
11336 			break;	/* goto sizeof (int) option return */
11337 		case IPV6_RECVHOPOPTS:
11338 			if (!checkonly) {
11339 				mutex_enter(&connp->conn_lock);
11340 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11341 				mutex_exit(&connp->conn_lock);
11342 			}
11343 			break;	/* goto sizeof (int) option return */
11344 		case IPV6_RECVDSTOPTS:
11345 			if (!checkonly) {
11346 				mutex_enter(&connp->conn_lock);
11347 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11348 				mutex_exit(&connp->conn_lock);
11349 			}
11350 			break;	/* goto sizeof (int) option return */
11351 		case IPV6_RECVRTHDR:
11352 			if (!checkonly) {
11353 				mutex_enter(&connp->conn_lock);
11354 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11355 				mutex_exit(&connp->conn_lock);
11356 			}
11357 			break;	/* goto sizeof (int) option return */
11358 		case IPV6_RECVRTHDRDSTOPTS:
11359 			if (!checkonly) {
11360 				mutex_enter(&connp->conn_lock);
11361 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11362 				mutex_exit(&connp->conn_lock);
11363 			}
11364 			break;	/* goto sizeof (int) option return */
11365 		case IPV6_PKTINFO:
11366 			if (inlen == 0)
11367 				return (-EINVAL);	/* clearing option */
11368 			error = ip6_set_pktinfo(cr, connp,
11369 			    (struct in6_pktinfo *)invalp);
11370 			if (error != 0)
11371 				*outlenp = 0;
11372 			else
11373 				*outlenp = inlen;
11374 			return (error);
11375 		case IPV6_NEXTHOP: {
11376 			struct sockaddr_in6 *sin6;
11377 
11378 			/* Verify that the nexthop is reachable */
11379 			if (inlen == 0)
11380 				return (-EINVAL);	/* clearing option */
11381 
11382 			sin6 = (struct sockaddr_in6 *)invalp;
11383 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11384 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11385 			    NULL, MATCH_IRE_DEFAULT, ipst);
11386 
11387 			if (ire == NULL) {
11388 				*outlenp = 0;
11389 				return (EHOSTUNREACH);
11390 			}
11391 			ire_refrele(ire);
11392 			return (-EINVAL);
11393 		}
11394 		case IPV6_SEC_OPT:
11395 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11396 			if (error != 0) {
11397 				*outlenp = 0;
11398 				return (error);
11399 			}
11400 			break;
11401 		case IPV6_SRC_PREFERENCES: {
11402 			/*
11403 			 * This is implemented strictly in the ip module
11404 			 * (here and in tcp_opt_*() to accomodate tcp
11405 			 * sockets).  Modules above ip pass this option
11406 			 * down here since ip is the only one that needs to
11407 			 * be aware of source address preferences.
11408 			 *
11409 			 * This socket option only affects connected
11410 			 * sockets that haven't already bound to a specific
11411 			 * IPv6 address.  In other words, sockets that
11412 			 * don't call bind() with an address other than the
11413 			 * unspecified address and that call connect().
11414 			 * ip_bind_connected_v6() passes these preferences
11415 			 * to the ipif_select_source_v6() function.
11416 			 */
11417 			if (inlen != sizeof (uint32_t))
11418 				return (EINVAL);
11419 			error = ip6_set_src_preferences(connp,
11420 			    *(uint32_t *)invalp);
11421 			if (error != 0) {
11422 				*outlenp = 0;
11423 				return (error);
11424 			} else {
11425 				*outlenp = sizeof (uint32_t);
11426 			}
11427 			break;
11428 		}
11429 		case IPV6_V6ONLY:
11430 			if (*i1 < 0 || *i1 > 1) {
11431 				return (EINVAL);
11432 			}
11433 			mutex_enter(&connp->conn_lock);
11434 			connp->conn_ipv6_v6only = *i1;
11435 			mutex_exit(&connp->conn_lock);
11436 			break;
11437 		default:
11438 			return (-EINVAL);
11439 		}
11440 		break;
11441 	default:
11442 		/*
11443 		 * "soft" error (negative)
11444 		 * option not handled at this level
11445 		 * Note: Do not modify *outlenp
11446 		 */
11447 		return (-EINVAL);
11448 	}
11449 	/*
11450 	 * Common case of return from an option that is sizeof (int)
11451 	 */
11452 	*(int *)outvalp = *i1;
11453 	*outlenp = sizeof (int);
11454 	return (0);
11455 }
11456 
11457 /*
11458  * This routine gets default values of certain options whose default
11459  * values are maintained by protocol specific code
11460  */
11461 /* ARGSUSED */
11462 int
11463 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11464 {
11465 	int *i1 = (int *)ptr;
11466 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11467 
11468 	switch (level) {
11469 	case IPPROTO_IP:
11470 		switch (name) {
11471 		case IP_MULTICAST_TTL:
11472 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11473 			return (sizeof (uchar_t));
11474 		case IP_MULTICAST_LOOP:
11475 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11476 			return (sizeof (uchar_t));
11477 		default:
11478 			return (-1);
11479 		}
11480 	case IPPROTO_IPV6:
11481 		switch (name) {
11482 		case IPV6_UNICAST_HOPS:
11483 			*i1 = ipst->ips_ipv6_def_hops;
11484 			return (sizeof (int));
11485 		case IPV6_MULTICAST_HOPS:
11486 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11487 			return (sizeof (int));
11488 		case IPV6_MULTICAST_LOOP:
11489 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11490 			return (sizeof (int));
11491 		case IPV6_V6ONLY:
11492 			*i1 = 1;
11493 			return (sizeof (int));
11494 		default:
11495 			return (-1);
11496 		}
11497 	default:
11498 		return (-1);
11499 	}
11500 	/* NOTREACHED */
11501 }
11502 
11503 /*
11504  * Given a destination address and a pointer to where to put the information
11505  * this routine fills in the mtuinfo.
11506  */
11507 int
11508 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11509     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11510 {
11511 	ire_t *ire;
11512 	ip_stack_t	*ipst = ns->netstack_ip;
11513 
11514 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11515 		return (-1);
11516 
11517 	bzero(mtuinfo, sizeof (*mtuinfo));
11518 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11519 	mtuinfo->ip6m_addr.sin6_port = port;
11520 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11521 
11522 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11523 	if (ire != NULL) {
11524 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11525 		ire_refrele(ire);
11526 	} else {
11527 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11528 	}
11529 	return (sizeof (struct ip6_mtuinfo));
11530 }
11531 
11532 /*
11533  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11534  * checking of cred and that ip_g_mrouter is set should be done and
11535  * isn't.  This doesn't matter as the error checking is done properly for the
11536  * other MRT options coming in through ip_opt_set.
11537  */
11538 int
11539 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11540 {
11541 	conn_t		*connp = Q_TO_CONN(q);
11542 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11543 
11544 	switch (level) {
11545 	case IPPROTO_IP:
11546 		switch (name) {
11547 		case MRT_VERSION:
11548 		case MRT_ASSERT:
11549 			(void) ip_mrouter_get(name, q, ptr);
11550 			return (sizeof (int));
11551 		case IP_SEC_OPT:
11552 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11553 		case IP_NEXTHOP:
11554 			if (connp->conn_nexthop_set) {
11555 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11556 				return (sizeof (ipaddr_t));
11557 			} else
11558 				return (0);
11559 		case IP_RECVPKTINFO:
11560 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11561 			return (sizeof (int));
11562 		default:
11563 			break;
11564 		}
11565 		break;
11566 	case IPPROTO_IPV6:
11567 		switch (name) {
11568 		case IPV6_SEC_OPT:
11569 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11570 		case IPV6_SRC_PREFERENCES: {
11571 			return (ip6_get_src_preferences(connp,
11572 			    (uint32_t *)ptr));
11573 		}
11574 		case IPV6_V6ONLY:
11575 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11576 			return (sizeof (int));
11577 		case IPV6_PATHMTU:
11578 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11579 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11580 		default:
11581 			break;
11582 		}
11583 		break;
11584 	default:
11585 		break;
11586 	}
11587 	return (-1);
11588 }
11589 /* Named Dispatch routine to get a current value out of our parameter table. */
11590 /* ARGSUSED */
11591 static int
11592 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11593 {
11594 	ipparam_t *ippa = (ipparam_t *)cp;
11595 
11596 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11597 	return (0);
11598 }
11599 
11600 /* ARGSUSED */
11601 static int
11602 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11603 {
11604 
11605 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11606 	return (0);
11607 }
11608 
11609 /*
11610  * Set ip{,6}_forwarding values.  This means walking through all of the
11611  * ill's and toggling their forwarding values.
11612  */
11613 /* ARGSUSED */
11614 static int
11615 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11616 {
11617 	long new_value;
11618 	int *forwarding_value = (int *)cp;
11619 	ill_t *ill;
11620 	boolean_t isv6;
11621 	ill_walk_context_t ctx;
11622 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11623 
11624 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11625 
11626 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11627 	    new_value < 0 || new_value > 1) {
11628 		return (EINVAL);
11629 	}
11630 
11631 	*forwarding_value = new_value;
11632 
11633 	/*
11634 	 * Regardless of the current value of ip_forwarding, set all per-ill
11635 	 * values of ip_forwarding to the value being set.
11636 	 *
11637 	 * Bring all the ill's up to date with the new global value.
11638 	 */
11639 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11640 
11641 	if (isv6)
11642 		ill = ILL_START_WALK_V6(&ctx, ipst);
11643 	else
11644 		ill = ILL_START_WALK_V4(&ctx, ipst);
11645 
11646 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11647 		(void) ill_forward_set(ill, new_value != 0);
11648 
11649 	rw_exit(&ipst->ips_ill_g_lock);
11650 	return (0);
11651 }
11652 
11653 /*
11654  * Walk through the param array specified registering each element with the
11655  * Named Dispatch handler. This is called only during init. So it is ok
11656  * not to acquire any locks
11657  */
11658 static boolean_t
11659 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11660     ipndp_t *ipnd, size_t ipnd_cnt)
11661 {
11662 	for (; ippa_cnt-- > 0; ippa++) {
11663 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11664 			if (!nd_load(ndp, ippa->ip_param_name,
11665 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11666 				nd_free(ndp);
11667 				return (B_FALSE);
11668 			}
11669 		}
11670 	}
11671 
11672 	for (; ipnd_cnt-- > 0; ipnd++) {
11673 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11674 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11675 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11676 			    ipnd->ip_ndp_data)) {
11677 				nd_free(ndp);
11678 				return (B_FALSE);
11679 			}
11680 		}
11681 	}
11682 
11683 	return (B_TRUE);
11684 }
11685 
11686 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11687 /* ARGSUSED */
11688 static int
11689 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11690 {
11691 	long		new_value;
11692 	ipparam_t	*ippa = (ipparam_t *)cp;
11693 
11694 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11695 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11696 		return (EINVAL);
11697 	}
11698 	ippa->ip_param_value = new_value;
11699 	return (0);
11700 }
11701 
11702 /*
11703  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11704  * When an ipf is passed here for the first time, if
11705  * we already have in-order fragments on the queue, we convert from the fast-
11706  * path reassembly scheme to the hard-case scheme.  From then on, additional
11707  * fragments are reassembled here.  We keep track of the start and end offsets
11708  * of each piece, and the number of holes in the chain.  When the hole count
11709  * goes to zero, we are done!
11710  *
11711  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11712  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11713  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11714  * after the call to ip_reassemble().
11715  */
11716 int
11717 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11718     size_t msg_len)
11719 {
11720 	uint_t	end;
11721 	mblk_t	*next_mp;
11722 	mblk_t	*mp1;
11723 	uint_t	offset;
11724 	boolean_t incr_dups = B_TRUE;
11725 	boolean_t offset_zero_seen = B_FALSE;
11726 	boolean_t pkt_boundary_checked = B_FALSE;
11727 
11728 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11729 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11730 
11731 	/* Add in byte count */
11732 	ipf->ipf_count += msg_len;
11733 	if (ipf->ipf_end) {
11734 		/*
11735 		 * We were part way through in-order reassembly, but now there
11736 		 * is a hole.  We walk through messages already queued, and
11737 		 * mark them for hard case reassembly.  We know that up till
11738 		 * now they were in order starting from offset zero.
11739 		 */
11740 		offset = 0;
11741 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11742 			IP_REASS_SET_START(mp1, offset);
11743 			if (offset == 0) {
11744 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11745 				offset = -ipf->ipf_nf_hdr_len;
11746 			}
11747 			offset += mp1->b_wptr - mp1->b_rptr;
11748 			IP_REASS_SET_END(mp1, offset);
11749 		}
11750 		/* One hole at the end. */
11751 		ipf->ipf_hole_cnt = 1;
11752 		/* Brand it as a hard case, forever. */
11753 		ipf->ipf_end = 0;
11754 	}
11755 	/* Walk through all the new pieces. */
11756 	do {
11757 		end = start + (mp->b_wptr - mp->b_rptr);
11758 		/*
11759 		 * If start is 0, decrease 'end' only for the first mblk of
11760 		 * the fragment. Otherwise 'end' can get wrong value in the
11761 		 * second pass of the loop if first mblk is exactly the
11762 		 * size of ipf_nf_hdr_len.
11763 		 */
11764 		if (start == 0 && !offset_zero_seen) {
11765 			/* First segment */
11766 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11767 			end -= ipf->ipf_nf_hdr_len;
11768 			offset_zero_seen = B_TRUE;
11769 		}
11770 		next_mp = mp->b_cont;
11771 		/*
11772 		 * We are checking to see if there is any interesing data
11773 		 * to process.  If there isn't and the mblk isn't the
11774 		 * one which carries the unfragmentable header then we
11775 		 * drop it.  It's possible to have just the unfragmentable
11776 		 * header come through without any data.  That needs to be
11777 		 * saved.
11778 		 *
11779 		 * If the assert at the top of this function holds then the
11780 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11781 		 * is infrequently traveled enough that the test is left in
11782 		 * to protect against future code changes which break that
11783 		 * invariant.
11784 		 */
11785 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11786 			/* Empty.  Blast it. */
11787 			IP_REASS_SET_START(mp, 0);
11788 			IP_REASS_SET_END(mp, 0);
11789 			/*
11790 			 * If the ipf points to the mblk we are about to free,
11791 			 * update ipf to point to the next mblk (or NULL
11792 			 * if none).
11793 			 */
11794 			if (ipf->ipf_mp->b_cont == mp)
11795 				ipf->ipf_mp->b_cont = next_mp;
11796 			freeb(mp);
11797 			continue;
11798 		}
11799 		mp->b_cont = NULL;
11800 		IP_REASS_SET_START(mp, start);
11801 		IP_REASS_SET_END(mp, end);
11802 		if (!ipf->ipf_tail_mp) {
11803 			ipf->ipf_tail_mp = mp;
11804 			ipf->ipf_mp->b_cont = mp;
11805 			if (start == 0 || !more) {
11806 				ipf->ipf_hole_cnt = 1;
11807 				/*
11808 				 * if the first fragment comes in more than one
11809 				 * mblk, this loop will be executed for each
11810 				 * mblk. Need to adjust hole count so exiting
11811 				 * this routine will leave hole count at 1.
11812 				 */
11813 				if (next_mp)
11814 					ipf->ipf_hole_cnt++;
11815 			} else
11816 				ipf->ipf_hole_cnt = 2;
11817 			continue;
11818 		} else if (ipf->ipf_last_frag_seen && !more &&
11819 		    !pkt_boundary_checked) {
11820 			/*
11821 			 * We check datagram boundary only if this fragment
11822 			 * claims to be the last fragment and we have seen a
11823 			 * last fragment in the past too. We do this only
11824 			 * once for a given fragment.
11825 			 *
11826 			 * start cannot be 0 here as fragments with start=0
11827 			 * and MF=0 gets handled as a complete packet. These
11828 			 * fragments should not reach here.
11829 			 */
11830 
11831 			if (start + msgdsize(mp) !=
11832 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11833 				/*
11834 				 * We have two fragments both of which claim
11835 				 * to be the last fragment but gives conflicting
11836 				 * information about the whole datagram size.
11837 				 * Something fishy is going on. Drop the
11838 				 * fragment and free up the reassembly list.
11839 				 */
11840 				return (IP_REASS_FAILED);
11841 			}
11842 
11843 			/*
11844 			 * We shouldn't come to this code block again for this
11845 			 * particular fragment.
11846 			 */
11847 			pkt_boundary_checked = B_TRUE;
11848 		}
11849 
11850 		/* New stuff at or beyond tail? */
11851 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11852 		if (start >= offset) {
11853 			if (ipf->ipf_last_frag_seen) {
11854 				/* current fragment is beyond last fragment */
11855 				return (IP_REASS_FAILED);
11856 			}
11857 			/* Link it on end. */
11858 			ipf->ipf_tail_mp->b_cont = mp;
11859 			ipf->ipf_tail_mp = mp;
11860 			if (more) {
11861 				if (start != offset)
11862 					ipf->ipf_hole_cnt++;
11863 			} else if (start == offset && next_mp == NULL)
11864 					ipf->ipf_hole_cnt--;
11865 			continue;
11866 		}
11867 		mp1 = ipf->ipf_mp->b_cont;
11868 		offset = IP_REASS_START(mp1);
11869 		/* New stuff at the front? */
11870 		if (start < offset) {
11871 			if (start == 0) {
11872 				if (end >= offset) {
11873 					/* Nailed the hole at the begining. */
11874 					ipf->ipf_hole_cnt--;
11875 				}
11876 			} else if (end < offset) {
11877 				/*
11878 				 * A hole, stuff, and a hole where there used
11879 				 * to be just a hole.
11880 				 */
11881 				ipf->ipf_hole_cnt++;
11882 			}
11883 			mp->b_cont = mp1;
11884 			/* Check for overlap. */
11885 			while (end > offset) {
11886 				if (end < IP_REASS_END(mp1)) {
11887 					mp->b_wptr -= end - offset;
11888 					IP_REASS_SET_END(mp, offset);
11889 					BUMP_MIB(ill->ill_ip_mib,
11890 					    ipIfStatsReasmPartDups);
11891 					break;
11892 				}
11893 				/* Did we cover another hole? */
11894 				if ((mp1->b_cont &&
11895 				    IP_REASS_END(mp1) !=
11896 				    IP_REASS_START(mp1->b_cont) &&
11897 				    end >= IP_REASS_START(mp1->b_cont)) ||
11898 				    (!ipf->ipf_last_frag_seen && !more)) {
11899 					ipf->ipf_hole_cnt--;
11900 				}
11901 				/* Clip out mp1. */
11902 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11903 					/*
11904 					 * After clipping out mp1, this guy
11905 					 * is now hanging off the end.
11906 					 */
11907 					ipf->ipf_tail_mp = mp;
11908 				}
11909 				IP_REASS_SET_START(mp1, 0);
11910 				IP_REASS_SET_END(mp1, 0);
11911 				/* Subtract byte count */
11912 				ipf->ipf_count -= mp1->b_datap->db_lim -
11913 				    mp1->b_datap->db_base;
11914 				freeb(mp1);
11915 				BUMP_MIB(ill->ill_ip_mib,
11916 				    ipIfStatsReasmPartDups);
11917 				mp1 = mp->b_cont;
11918 				if (!mp1)
11919 					break;
11920 				offset = IP_REASS_START(mp1);
11921 			}
11922 			ipf->ipf_mp->b_cont = mp;
11923 			continue;
11924 		}
11925 		/*
11926 		 * The new piece starts somewhere between the start of the head
11927 		 * and before the end of the tail.
11928 		 */
11929 		for (; mp1; mp1 = mp1->b_cont) {
11930 			offset = IP_REASS_END(mp1);
11931 			if (start < offset) {
11932 				if (end <= offset) {
11933 					/* Nothing new. */
11934 					IP_REASS_SET_START(mp, 0);
11935 					IP_REASS_SET_END(mp, 0);
11936 					/* Subtract byte count */
11937 					ipf->ipf_count -= mp->b_datap->db_lim -
11938 					    mp->b_datap->db_base;
11939 					if (incr_dups) {
11940 						ipf->ipf_num_dups++;
11941 						incr_dups = B_FALSE;
11942 					}
11943 					freeb(mp);
11944 					BUMP_MIB(ill->ill_ip_mib,
11945 					    ipIfStatsReasmDuplicates);
11946 					break;
11947 				}
11948 				/*
11949 				 * Trim redundant stuff off beginning of new
11950 				 * piece.
11951 				 */
11952 				IP_REASS_SET_START(mp, offset);
11953 				mp->b_rptr += offset - start;
11954 				BUMP_MIB(ill->ill_ip_mib,
11955 				    ipIfStatsReasmPartDups);
11956 				start = offset;
11957 				if (!mp1->b_cont) {
11958 					/*
11959 					 * After trimming, this guy is now
11960 					 * hanging off the end.
11961 					 */
11962 					mp1->b_cont = mp;
11963 					ipf->ipf_tail_mp = mp;
11964 					if (!more) {
11965 						ipf->ipf_hole_cnt--;
11966 					}
11967 					break;
11968 				}
11969 			}
11970 			if (start >= IP_REASS_START(mp1->b_cont))
11971 				continue;
11972 			/* Fill a hole */
11973 			if (start > offset)
11974 				ipf->ipf_hole_cnt++;
11975 			mp->b_cont = mp1->b_cont;
11976 			mp1->b_cont = mp;
11977 			mp1 = mp->b_cont;
11978 			offset = IP_REASS_START(mp1);
11979 			if (end >= offset) {
11980 				ipf->ipf_hole_cnt--;
11981 				/* Check for overlap. */
11982 				while (end > offset) {
11983 					if (end < IP_REASS_END(mp1)) {
11984 						mp->b_wptr -= end - offset;
11985 						IP_REASS_SET_END(mp, offset);
11986 						/*
11987 						 * TODO we might bump
11988 						 * this up twice if there is
11989 						 * overlap at both ends.
11990 						 */
11991 						BUMP_MIB(ill->ill_ip_mib,
11992 						    ipIfStatsReasmPartDups);
11993 						break;
11994 					}
11995 					/* Did we cover another hole? */
11996 					if ((mp1->b_cont &&
11997 					    IP_REASS_END(mp1)
11998 					    != IP_REASS_START(mp1->b_cont) &&
11999 					    end >=
12000 					    IP_REASS_START(mp1->b_cont)) ||
12001 					    (!ipf->ipf_last_frag_seen &&
12002 					    !more)) {
12003 						ipf->ipf_hole_cnt--;
12004 					}
12005 					/* Clip out mp1. */
12006 					if ((mp->b_cont = mp1->b_cont) ==
12007 					    NULL) {
12008 						/*
12009 						 * After clipping out mp1,
12010 						 * this guy is now hanging
12011 						 * off the end.
12012 						 */
12013 						ipf->ipf_tail_mp = mp;
12014 					}
12015 					IP_REASS_SET_START(mp1, 0);
12016 					IP_REASS_SET_END(mp1, 0);
12017 					/* Subtract byte count */
12018 					ipf->ipf_count -=
12019 					    mp1->b_datap->db_lim -
12020 					    mp1->b_datap->db_base;
12021 					freeb(mp1);
12022 					BUMP_MIB(ill->ill_ip_mib,
12023 					    ipIfStatsReasmPartDups);
12024 					mp1 = mp->b_cont;
12025 					if (!mp1)
12026 						break;
12027 					offset = IP_REASS_START(mp1);
12028 				}
12029 			}
12030 			break;
12031 		}
12032 	} while (start = end, mp = next_mp);
12033 
12034 	/* Fragment just processed could be the last one. Remember this fact */
12035 	if (!more)
12036 		ipf->ipf_last_frag_seen = B_TRUE;
12037 
12038 	/* Still got holes? */
12039 	if (ipf->ipf_hole_cnt)
12040 		return (IP_REASS_PARTIAL);
12041 	/* Clean up overloaded fields to avoid upstream disasters. */
12042 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12043 		IP_REASS_SET_START(mp1, 0);
12044 		IP_REASS_SET_END(mp1, 0);
12045 	}
12046 	return (IP_REASS_COMPLETE);
12047 }
12048 
12049 /*
12050  * ipsec processing for the fast path, used for input UDP Packets
12051  * Returns true if ready for passup to UDP.
12052  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12053  * was an ESP-in-UDP packet, etc.).
12054  */
12055 static boolean_t
12056 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12057     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12058 {
12059 	uint32_t	ill_index;
12060 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12061 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12062 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12063 	udp_t		*udp = connp->conn_udp;
12064 
12065 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12066 	/* The ill_index of the incoming ILL */
12067 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12068 
12069 	/* pass packet up to the transport */
12070 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12071 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12072 		    NULL, mctl_present);
12073 		if (*first_mpp == NULL) {
12074 			return (B_FALSE);
12075 		}
12076 	}
12077 
12078 	/* Initiate IPPF processing for fastpath UDP */
12079 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12080 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12081 		if (*mpp == NULL) {
12082 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12083 			    "deferred/dropped during IPPF processing\n"));
12084 			return (B_FALSE);
12085 		}
12086 	}
12087 	/*
12088 	 * Remove 0-spi if it's 0, or move everything behind
12089 	 * the UDP header over it and forward to ESP via
12090 	 * ip_proto_input().
12091 	 */
12092 	if (udp->udp_nat_t_endpoint) {
12093 		if (mctl_present) {
12094 			/* mctl_present *shouldn't* happen. */
12095 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12096 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12097 			    &ipss->ipsec_dropper);
12098 			*first_mpp = NULL;
12099 			return (B_FALSE);
12100 		}
12101 
12102 		/* "ill" is "recv_ill" in actuality. */
12103 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12104 			return (B_FALSE);
12105 
12106 		/* Else continue like a normal UDP packet. */
12107 	}
12108 
12109 	/*
12110 	 * We make the checks as below since we are in the fast path
12111 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12112 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12113 	 */
12114 	if (connp->conn_recvif || connp->conn_recvslla ||
12115 	    connp->conn_ip_recvpktinfo) {
12116 		if (connp->conn_recvif) {
12117 			in_flags = IPF_RECVIF;
12118 		}
12119 		/*
12120 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12121 		 * so the flag passed to ip_add_info is based on IP version
12122 		 * of connp.
12123 		 */
12124 		if (connp->conn_ip_recvpktinfo) {
12125 			if (connp->conn_af_isv6) {
12126 				/*
12127 				 * V6 only needs index
12128 				 */
12129 				in_flags |= IPF_RECVIF;
12130 			} else {
12131 				/*
12132 				 * V4 needs index + matching address.
12133 				 */
12134 				in_flags |= IPF_RECVADDR;
12135 			}
12136 		}
12137 		if (connp->conn_recvslla) {
12138 			in_flags |= IPF_RECVSLLA;
12139 		}
12140 		/*
12141 		 * since in_flags are being set ill will be
12142 		 * referenced in ip_add_info, so it better not
12143 		 * be NULL.
12144 		 */
12145 		/*
12146 		 * the actual data will be contained in b_cont
12147 		 * upon successful return of the following call.
12148 		 * If the call fails then the original mblk is
12149 		 * returned.
12150 		 */
12151 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12152 		    ipst);
12153 	}
12154 
12155 	return (B_TRUE);
12156 }
12157 
12158 /*
12159  * Fragmentation reassembly.  Each ILL has a hash table for
12160  * queuing packets undergoing reassembly for all IPIFs
12161  * associated with the ILL.  The hash is based on the packet
12162  * IP ident field.  The ILL frag hash table was allocated
12163  * as a timer block at the time the ILL was created.  Whenever
12164  * there is anything on the reassembly queue, the timer will
12165  * be running.  Returns B_TRUE if successful else B_FALSE;
12166  * frees mp on failure.
12167  */
12168 static boolean_t
12169 ip_rput_fragment(ill_t *ill, ill_t *recv_ill, mblk_t **mpp, ipha_t *ipha,
12170     uint32_t *cksum_val, uint16_t *cksum_flags)
12171 {
12172 	uint32_t	frag_offset_flags;
12173 	mblk_t		*mp = *mpp;
12174 	mblk_t		*t_mp;
12175 	ipaddr_t	dst;
12176 	uint8_t		proto = ipha->ipha_protocol;
12177 	uint32_t	sum_val;
12178 	uint16_t	sum_flags;
12179 	ipf_t		*ipf;
12180 	ipf_t		**ipfp;
12181 	ipfb_t		*ipfb;
12182 	uint16_t	ident;
12183 	uint32_t	offset;
12184 	ipaddr_t	src;
12185 	uint_t		hdr_length;
12186 	uint32_t	end;
12187 	mblk_t		*mp1;
12188 	mblk_t		*tail_mp;
12189 	size_t		count;
12190 	size_t		msg_len;
12191 	uint8_t		ecn_info = 0;
12192 	uint32_t	packet_size;
12193 	boolean_t	pruned = B_FALSE;
12194 	ip_stack_t *ipst = ill->ill_ipst;
12195 
12196 	if (cksum_val != NULL)
12197 		*cksum_val = 0;
12198 	if (cksum_flags != NULL)
12199 		*cksum_flags = 0;
12200 
12201 	/*
12202 	 * Drop the fragmented as early as possible, if
12203 	 * we don't have resource(s) to re-assemble.
12204 	 */
12205 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12206 		freemsg(mp);
12207 		return (B_FALSE);
12208 	}
12209 
12210 	/* Check for fragmentation offset; return if there's none */
12211 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12212 	    (IPH_MF | IPH_OFFSET)) == 0)
12213 		return (B_TRUE);
12214 
12215 	/*
12216 	 * We utilize hardware computed checksum info only for UDP since
12217 	 * IP fragmentation is a normal occurrence for the protocol.  In
12218 	 * addition, checksum offload support for IP fragments carrying
12219 	 * UDP payload is commonly implemented across network adapters.
12220 	 */
12221 	ASSERT(recv_ill != NULL);
12222 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(recv_ill) &&
12223 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12224 		mblk_t *mp1 = mp->b_cont;
12225 		int32_t len;
12226 
12227 		/* Record checksum information from the packet */
12228 		sum_val = (uint32_t)DB_CKSUM16(mp);
12229 		sum_flags = DB_CKSUMFLAGS(mp);
12230 
12231 		/* IP payload offset from beginning of mblk */
12232 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12233 
12234 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12235 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12236 		    offset >= DB_CKSUMSTART(mp) &&
12237 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12238 			uint32_t adj;
12239 			/*
12240 			 * Partial checksum has been calculated by hardware
12241 			 * and attached to the packet; in addition, any
12242 			 * prepended extraneous data is even byte aligned.
12243 			 * If any such data exists, we adjust the checksum;
12244 			 * this would also handle any postpended data.
12245 			 */
12246 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12247 			    mp, mp1, len, adj);
12248 
12249 			/* One's complement subtract extraneous checksum */
12250 			if (adj >= sum_val)
12251 				sum_val = ~(adj - sum_val) & 0xFFFF;
12252 			else
12253 				sum_val -= adj;
12254 		}
12255 	} else {
12256 		sum_val = 0;
12257 		sum_flags = 0;
12258 	}
12259 
12260 	/* Clear hardware checksumming flag */
12261 	DB_CKSUMFLAGS(mp) = 0;
12262 
12263 	ident = ipha->ipha_ident;
12264 	offset = (frag_offset_flags << 3) & 0xFFFF;
12265 	src = ipha->ipha_src;
12266 	dst = ipha->ipha_dst;
12267 	hdr_length = IPH_HDR_LENGTH(ipha);
12268 	end = ntohs(ipha->ipha_length) - hdr_length;
12269 
12270 	/* If end == 0 then we have a packet with no data, so just free it */
12271 	if (end == 0) {
12272 		freemsg(mp);
12273 		return (B_FALSE);
12274 	}
12275 
12276 	/* Record the ECN field info. */
12277 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12278 	if (offset != 0) {
12279 		/*
12280 		 * If this isn't the first piece, strip the header, and
12281 		 * add the offset to the end value.
12282 		 */
12283 		mp->b_rptr += hdr_length;
12284 		end += offset;
12285 	}
12286 
12287 	msg_len = MBLKSIZE(mp);
12288 	tail_mp = mp;
12289 	while (tail_mp->b_cont != NULL) {
12290 		tail_mp = tail_mp->b_cont;
12291 		msg_len += MBLKSIZE(tail_mp);
12292 	}
12293 
12294 	/* If the reassembly list for this ILL will get too big, prune it */
12295 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12296 	    ipst->ips_ip_reass_queue_bytes) {
12297 		ill_frag_prune(ill,
12298 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12299 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12300 		pruned = B_TRUE;
12301 	}
12302 
12303 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12304 	mutex_enter(&ipfb->ipfb_lock);
12305 
12306 	ipfp = &ipfb->ipfb_ipf;
12307 	/* Try to find an existing fragment queue for this packet. */
12308 	for (;;) {
12309 		ipf = ipfp[0];
12310 		if (ipf != NULL) {
12311 			/*
12312 			 * It has to match on ident and src/dst address.
12313 			 */
12314 			if (ipf->ipf_ident == ident &&
12315 			    ipf->ipf_src == src &&
12316 			    ipf->ipf_dst == dst &&
12317 			    ipf->ipf_protocol == proto) {
12318 				/*
12319 				 * If we have received too many
12320 				 * duplicate fragments for this packet
12321 				 * free it.
12322 				 */
12323 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12324 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12325 					freemsg(mp);
12326 					mutex_exit(&ipfb->ipfb_lock);
12327 					return (B_FALSE);
12328 				}
12329 				/* Found it. */
12330 				break;
12331 			}
12332 			ipfp = &ipf->ipf_hash_next;
12333 			continue;
12334 		}
12335 
12336 		/*
12337 		 * If we pruned the list, do we want to store this new
12338 		 * fragment?. We apply an optimization here based on the
12339 		 * fact that most fragments will be received in order.
12340 		 * So if the offset of this incoming fragment is zero,
12341 		 * it is the first fragment of a new packet. We will
12342 		 * keep it.  Otherwise drop the fragment, as we have
12343 		 * probably pruned the packet already (since the
12344 		 * packet cannot be found).
12345 		 */
12346 		if (pruned && offset != 0) {
12347 			mutex_exit(&ipfb->ipfb_lock);
12348 			freemsg(mp);
12349 			return (B_FALSE);
12350 		}
12351 
12352 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12353 			/*
12354 			 * Too many fragmented packets in this hash
12355 			 * bucket. Free the oldest.
12356 			 */
12357 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12358 		}
12359 
12360 		/* New guy.  Allocate a frag message. */
12361 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12362 		if (mp1 == NULL) {
12363 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12364 			freemsg(mp);
12365 reass_done:
12366 			mutex_exit(&ipfb->ipfb_lock);
12367 			return (B_FALSE);
12368 		}
12369 
12370 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12371 		mp1->b_cont = mp;
12372 
12373 		/* Initialize the fragment header. */
12374 		ipf = (ipf_t *)mp1->b_rptr;
12375 		ipf->ipf_mp = mp1;
12376 		ipf->ipf_ptphn = ipfp;
12377 		ipfp[0] = ipf;
12378 		ipf->ipf_hash_next = NULL;
12379 		ipf->ipf_ident = ident;
12380 		ipf->ipf_protocol = proto;
12381 		ipf->ipf_src = src;
12382 		ipf->ipf_dst = dst;
12383 		ipf->ipf_nf_hdr_len = 0;
12384 		/* Record reassembly start time. */
12385 		ipf->ipf_timestamp = gethrestime_sec();
12386 		/* Record ipf generation and account for frag header */
12387 		ipf->ipf_gen = ill->ill_ipf_gen++;
12388 		ipf->ipf_count = MBLKSIZE(mp1);
12389 		ipf->ipf_last_frag_seen = B_FALSE;
12390 		ipf->ipf_ecn = ecn_info;
12391 		ipf->ipf_num_dups = 0;
12392 		ipfb->ipfb_frag_pkts++;
12393 		ipf->ipf_checksum = 0;
12394 		ipf->ipf_checksum_flags = 0;
12395 
12396 		/* Store checksum value in fragment header */
12397 		if (sum_flags != 0) {
12398 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12399 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12400 			ipf->ipf_checksum = sum_val;
12401 			ipf->ipf_checksum_flags = sum_flags;
12402 		}
12403 
12404 		/*
12405 		 * We handle reassembly two ways.  In the easy case,
12406 		 * where all the fragments show up in order, we do
12407 		 * minimal bookkeeping, and just clip new pieces on
12408 		 * the end.  If we ever see a hole, then we go off
12409 		 * to ip_reassemble which has to mark the pieces and
12410 		 * keep track of the number of holes, etc.  Obviously,
12411 		 * the point of having both mechanisms is so we can
12412 		 * handle the easy case as efficiently as possible.
12413 		 */
12414 		if (offset == 0) {
12415 			/* Easy case, in-order reassembly so far. */
12416 			ipf->ipf_count += msg_len;
12417 			ipf->ipf_tail_mp = tail_mp;
12418 			/*
12419 			 * Keep track of next expected offset in
12420 			 * ipf_end.
12421 			 */
12422 			ipf->ipf_end = end;
12423 			ipf->ipf_nf_hdr_len = hdr_length;
12424 		} else {
12425 			/* Hard case, hole at the beginning. */
12426 			ipf->ipf_tail_mp = NULL;
12427 			/*
12428 			 * ipf_end == 0 means that we have given up
12429 			 * on easy reassembly.
12430 			 */
12431 			ipf->ipf_end = 0;
12432 
12433 			/* Forget checksum offload from now on */
12434 			ipf->ipf_checksum_flags = 0;
12435 
12436 			/*
12437 			 * ipf_hole_cnt is set by ip_reassemble.
12438 			 * ipf_count is updated by ip_reassemble.
12439 			 * No need to check for return value here
12440 			 * as we don't expect reassembly to complete
12441 			 * or fail for the first fragment itself.
12442 			 */
12443 			(void) ip_reassemble(mp, ipf,
12444 			    (frag_offset_flags & IPH_OFFSET) << 3,
12445 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12446 		}
12447 		/* Update per ipfb and ill byte counts */
12448 		ipfb->ipfb_count += ipf->ipf_count;
12449 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12450 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12451 		/* If the frag timer wasn't already going, start it. */
12452 		mutex_enter(&ill->ill_lock);
12453 		ill_frag_timer_start(ill);
12454 		mutex_exit(&ill->ill_lock);
12455 		goto reass_done;
12456 	}
12457 
12458 	/*
12459 	 * If the packet's flag has changed (it could be coming up
12460 	 * from an interface different than the previous, therefore
12461 	 * possibly different checksum capability), then forget about
12462 	 * any stored checksum states.  Otherwise add the value to
12463 	 * the existing one stored in the fragment header.
12464 	 */
12465 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12466 		sum_val += ipf->ipf_checksum;
12467 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12468 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12469 		ipf->ipf_checksum = sum_val;
12470 	} else if (ipf->ipf_checksum_flags != 0) {
12471 		/* Forget checksum offload from now on */
12472 		ipf->ipf_checksum_flags = 0;
12473 	}
12474 
12475 	/*
12476 	 * We have a new piece of a datagram which is already being
12477 	 * reassembled.  Update the ECN info if all IP fragments
12478 	 * are ECN capable.  If there is one which is not, clear
12479 	 * all the info.  If there is at least one which has CE
12480 	 * code point, IP needs to report that up to transport.
12481 	 */
12482 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12483 		if (ecn_info == IPH_ECN_CE)
12484 			ipf->ipf_ecn = IPH_ECN_CE;
12485 	} else {
12486 		ipf->ipf_ecn = IPH_ECN_NECT;
12487 	}
12488 	if (offset && ipf->ipf_end == offset) {
12489 		/* The new fragment fits at the end */
12490 		ipf->ipf_tail_mp->b_cont = mp;
12491 		/* Update the byte count */
12492 		ipf->ipf_count += msg_len;
12493 		/* Update per ipfb and ill byte counts */
12494 		ipfb->ipfb_count += msg_len;
12495 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12496 		atomic_add_32(&ill->ill_frag_count, msg_len);
12497 		if (frag_offset_flags & IPH_MF) {
12498 			/* More to come. */
12499 			ipf->ipf_end = end;
12500 			ipf->ipf_tail_mp = tail_mp;
12501 			goto reass_done;
12502 		}
12503 	} else {
12504 		/* Go do the hard cases. */
12505 		int ret;
12506 
12507 		if (offset == 0)
12508 			ipf->ipf_nf_hdr_len = hdr_length;
12509 
12510 		/* Save current byte count */
12511 		count = ipf->ipf_count;
12512 		ret = ip_reassemble(mp, ipf,
12513 		    (frag_offset_flags & IPH_OFFSET) << 3,
12514 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12515 		/* Count of bytes added and subtracted (freeb()ed) */
12516 		count = ipf->ipf_count - count;
12517 		if (count) {
12518 			/* Update per ipfb and ill byte counts */
12519 			ipfb->ipfb_count += count;
12520 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12521 			atomic_add_32(&ill->ill_frag_count, count);
12522 		}
12523 		if (ret == IP_REASS_PARTIAL) {
12524 			goto reass_done;
12525 		} else if (ret == IP_REASS_FAILED) {
12526 			/* Reassembly failed. Free up all resources */
12527 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12528 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12529 				IP_REASS_SET_START(t_mp, 0);
12530 				IP_REASS_SET_END(t_mp, 0);
12531 			}
12532 			freemsg(mp);
12533 			goto reass_done;
12534 		}
12535 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12536 	}
12537 	/*
12538 	 * We have completed reassembly.  Unhook the frag header from
12539 	 * the reassembly list.
12540 	 *
12541 	 * Before we free the frag header, record the ECN info
12542 	 * to report back to the transport.
12543 	 */
12544 	ecn_info = ipf->ipf_ecn;
12545 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12546 	ipfp = ipf->ipf_ptphn;
12547 
12548 	/* We need to supply these to caller */
12549 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12550 		sum_val = ipf->ipf_checksum;
12551 	else
12552 		sum_val = 0;
12553 
12554 	mp1 = ipf->ipf_mp;
12555 	count = ipf->ipf_count;
12556 	ipf = ipf->ipf_hash_next;
12557 	if (ipf != NULL)
12558 		ipf->ipf_ptphn = ipfp;
12559 	ipfp[0] = ipf;
12560 	atomic_add_32(&ill->ill_frag_count, -count);
12561 	ASSERT(ipfb->ipfb_count >= count);
12562 	ipfb->ipfb_count -= count;
12563 	ipfb->ipfb_frag_pkts--;
12564 	mutex_exit(&ipfb->ipfb_lock);
12565 	/* Ditch the frag header. */
12566 	mp = mp1->b_cont;
12567 
12568 	freeb(mp1);
12569 
12570 	/* Restore original IP length in header. */
12571 	packet_size = (uint32_t)msgdsize(mp);
12572 	if (packet_size > IP_MAXPACKET) {
12573 		freemsg(mp);
12574 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12575 		return (B_FALSE);
12576 	}
12577 
12578 	if (DB_REF(mp) > 1) {
12579 		mblk_t *mp2 = copymsg(mp);
12580 
12581 		freemsg(mp);
12582 		if (mp2 == NULL) {
12583 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12584 			return (B_FALSE);
12585 		}
12586 		mp = mp2;
12587 	}
12588 	ipha = (ipha_t *)mp->b_rptr;
12589 
12590 	ipha->ipha_length = htons((uint16_t)packet_size);
12591 	/* We're now complete, zip the frag state */
12592 	ipha->ipha_fragment_offset_and_flags = 0;
12593 	/* Record the ECN info. */
12594 	ipha->ipha_type_of_service &= 0xFC;
12595 	ipha->ipha_type_of_service |= ecn_info;
12596 	*mpp = mp;
12597 
12598 	/* Reassembly is successful; return checksum information if needed */
12599 	if (cksum_val != NULL)
12600 		*cksum_val = sum_val;
12601 	if (cksum_flags != NULL)
12602 		*cksum_flags = sum_flags;
12603 
12604 	return (B_TRUE);
12605 }
12606 
12607 /*
12608  * Perform ip header check sum update local options.
12609  * return B_TRUE if all is well, else return B_FALSE and release
12610  * the mp. caller is responsible for decrementing ire ref cnt.
12611  */
12612 static boolean_t
12613 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12614     ip_stack_t *ipst)
12615 {
12616 	mblk_t		*first_mp;
12617 	boolean_t	mctl_present;
12618 	uint16_t	sum;
12619 
12620 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12621 	/*
12622 	 * Don't do the checksum if it has gone through AH/ESP
12623 	 * processing.
12624 	 */
12625 	if (!mctl_present) {
12626 		sum = ip_csum_hdr(ipha);
12627 		if (sum != 0) {
12628 			if (ill != NULL) {
12629 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12630 			} else {
12631 				BUMP_MIB(&ipst->ips_ip_mib,
12632 				    ipIfStatsInCksumErrs);
12633 			}
12634 			freemsg(first_mp);
12635 			return (B_FALSE);
12636 		}
12637 	}
12638 
12639 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12640 		if (mctl_present)
12641 			freeb(first_mp);
12642 		return (B_FALSE);
12643 	}
12644 
12645 	return (B_TRUE);
12646 }
12647 
12648 /*
12649  * All udp packet are delivered to the local host via this routine.
12650  */
12651 void
12652 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12653     ill_t *recv_ill)
12654 {
12655 	uint32_t	sum;
12656 	uint32_t	u1;
12657 	boolean_t	mctl_present;
12658 	conn_t		*connp;
12659 	mblk_t		*first_mp;
12660 	uint16_t	*up;
12661 	ill_t		*ill = (ill_t *)q->q_ptr;
12662 	uint16_t	reass_hck_flags = 0;
12663 	ip_stack_t	*ipst;
12664 
12665 	ASSERT(recv_ill != NULL);
12666 	ipst = recv_ill->ill_ipst;
12667 
12668 #define	rptr    ((uchar_t *)ipha)
12669 
12670 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12671 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12672 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12673 	ASSERT(ill != NULL);
12674 
12675 	/*
12676 	 * FAST PATH for udp packets
12677 	 */
12678 
12679 	/* u1 is # words of IP options */
12680 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12681 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12682 
12683 	/* IP options present */
12684 	if (u1 != 0)
12685 		goto ipoptions;
12686 
12687 	/* Check the IP header checksum.  */
12688 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12689 		/* Clear the IP header h/w cksum flag */
12690 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12691 	} else if (!mctl_present) {
12692 		/*
12693 		 * Don't verify header checksum if this packet is coming
12694 		 * back from AH/ESP as we already did it.
12695 		 */
12696 #define	uph	((uint16_t *)ipha)
12697 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12698 		    uph[6] + uph[7] + uph[8] + uph[9];
12699 #undef	uph
12700 		/* finish doing IP checksum */
12701 		sum = (sum & 0xFFFF) + (sum >> 16);
12702 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12703 		if (sum != 0 && sum != 0xFFFF) {
12704 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12705 			freemsg(first_mp);
12706 			return;
12707 		}
12708 	}
12709 
12710 	/*
12711 	 * Count for SNMP of inbound packets for ire.
12712 	 * if mctl is present this might be a secure packet and
12713 	 * has already been counted for in ip_proto_input().
12714 	 */
12715 	if (!mctl_present) {
12716 		UPDATE_IB_PKT_COUNT(ire);
12717 		ire->ire_last_used_time = lbolt;
12718 	}
12719 
12720 	/* packet part of fragmented IP packet? */
12721 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12722 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12723 		goto fragmented;
12724 	}
12725 
12726 	/* u1 = IP header length (20 bytes) */
12727 	u1 = IP_SIMPLE_HDR_LENGTH;
12728 
12729 	/* packet does not contain complete IP & UDP headers */
12730 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12731 		goto udppullup;
12732 
12733 	/* up points to UDP header */
12734 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12735 #define	iphs    ((uint16_t *)ipha)
12736 
12737 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12738 	if (up[3] != 0) {
12739 		mblk_t *mp1 = mp->b_cont;
12740 		boolean_t cksum_err;
12741 		uint16_t hck_flags = 0;
12742 
12743 		/* Pseudo-header checksum */
12744 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12745 		    iphs[9] + up[2];
12746 
12747 		/*
12748 		 * Revert to software checksum calculation if the interface
12749 		 * isn't capable of checksum offload or if IPsec is present.
12750 		 */
12751 		if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
12752 			hck_flags = DB_CKSUMFLAGS(mp);
12753 
12754 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12755 			IP_STAT(ipst, ip_in_sw_cksum);
12756 
12757 		IP_CKSUM_RECV(hck_flags, u1,
12758 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12759 		    (int32_t)((uchar_t *)up - rptr),
12760 		    mp, mp1, cksum_err);
12761 
12762 		if (cksum_err) {
12763 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12764 			if (hck_flags & HCK_FULLCKSUM)
12765 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12766 			else if (hck_flags & HCK_PARTIALCKSUM)
12767 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12768 			else
12769 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12770 
12771 			freemsg(first_mp);
12772 			return;
12773 		}
12774 	}
12775 
12776 	/* Non-fragmented broadcast or multicast packet? */
12777 	if (ire->ire_type == IRE_BROADCAST)
12778 		goto udpslowpath;
12779 
12780 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12781 	    ire->ire_zoneid, ipst)) != NULL) {
12782 		ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_upq != NULL);
12783 		IP_STAT(ipst, ip_udp_fast_path);
12784 
12785 		if ((IPCL_IS_NONSTR(connp) && PROTO_FLOW_CNTRLD(connp)) ||
12786 		    (!IPCL_IS_NONSTR(connp) && CONN_UDP_FLOWCTLD(connp))) {
12787 			freemsg(mp);
12788 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12789 		} else {
12790 			if (!mctl_present) {
12791 				BUMP_MIB(ill->ill_ip_mib,
12792 				    ipIfStatsHCInDelivers);
12793 			}
12794 			/*
12795 			 * mp and first_mp can change.
12796 			 */
12797 			if (ip_udp_check(q, connp, recv_ill,
12798 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12799 				/* Send it upstream */
12800 				(connp->conn_recv)(connp, mp, NULL);
12801 			}
12802 		}
12803 		/*
12804 		 * freeb() cannot deal with null mblk being passed
12805 		 * in and first_mp can be set to null in the call
12806 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12807 		 */
12808 		if (mctl_present && first_mp != NULL) {
12809 			freeb(first_mp);
12810 		}
12811 		CONN_DEC_REF(connp);
12812 		return;
12813 	}
12814 
12815 	/*
12816 	 * if we got here we know the packet is not fragmented and
12817 	 * has no options. The classifier could not find a conn_t and
12818 	 * most likely its an icmp packet so send it through slow path.
12819 	 */
12820 
12821 	goto udpslowpath;
12822 
12823 ipoptions:
12824 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12825 		goto slow_done;
12826 	}
12827 
12828 	UPDATE_IB_PKT_COUNT(ire);
12829 	ire->ire_last_used_time = lbolt;
12830 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12831 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12832 fragmented:
12833 		/*
12834 		 * "sum" and "reass_hck_flags" are non-zero if the
12835 		 * reassembled packet has a valid hardware computed
12836 		 * checksum information associated with it.
12837 		 */
12838 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, &sum,
12839 		    &reass_hck_flags)) {
12840 			goto slow_done;
12841 		}
12842 
12843 		/*
12844 		 * Make sure that first_mp points back to mp as
12845 		 * the mp we came in with could have changed in
12846 		 * ip_rput_fragment().
12847 		 */
12848 		ASSERT(!mctl_present);
12849 		ipha = (ipha_t *)mp->b_rptr;
12850 		first_mp = mp;
12851 	}
12852 
12853 	/* Now we have a complete datagram, destined for this machine. */
12854 	u1 = IPH_HDR_LENGTH(ipha);
12855 	/* Pull up the UDP header, if necessary. */
12856 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12857 udppullup:
12858 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12859 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12860 			freemsg(first_mp);
12861 			goto slow_done;
12862 		}
12863 		ipha = (ipha_t *)mp->b_rptr;
12864 	}
12865 
12866 	/*
12867 	 * Validate the checksum for the reassembled packet; for the
12868 	 * pullup case we calculate the payload checksum in software.
12869 	 */
12870 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12871 	if (up[3] != 0) {
12872 		boolean_t cksum_err;
12873 
12874 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12875 			IP_STAT(ipst, ip_in_sw_cksum);
12876 
12877 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12878 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12879 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12880 		    iphs[9] + up[2], sum, cksum_err);
12881 
12882 		if (cksum_err) {
12883 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12884 
12885 			if (reass_hck_flags & HCK_FULLCKSUM)
12886 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12887 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12888 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12889 			else
12890 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12891 
12892 			freemsg(first_mp);
12893 			goto slow_done;
12894 		}
12895 	}
12896 udpslowpath:
12897 
12898 	/* Clear hardware checksum flag to be safe */
12899 	DB_CKSUMFLAGS(mp) = 0;
12900 
12901 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12902 	    (ire->ire_type == IRE_BROADCAST),
12903 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12904 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12905 
12906 slow_done:
12907 	IP_STAT(ipst, ip_udp_slow_path);
12908 	return;
12909 
12910 #undef  iphs
12911 #undef  rptr
12912 }
12913 
12914 /* ARGSUSED */
12915 static mblk_t *
12916 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12917     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12918     ill_rx_ring_t *ill_ring)
12919 {
12920 	conn_t		*connp;
12921 	uint32_t	sum;
12922 	uint32_t	u1;
12923 	uint16_t	*up;
12924 	int		offset;
12925 	ssize_t		len;
12926 	mblk_t		*mp1;
12927 	boolean_t	syn_present = B_FALSE;
12928 	tcph_t		*tcph;
12929 	uint_t		tcph_flags;
12930 	uint_t		ip_hdr_len;
12931 	ill_t		*ill = (ill_t *)q->q_ptr;
12932 	zoneid_t	zoneid = ire->ire_zoneid;
12933 	boolean_t	cksum_err;
12934 	uint16_t	hck_flags = 0;
12935 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12936 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12937 
12938 #define	rptr	((uchar_t *)ipha)
12939 
12940 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12941 	ASSERT(ill != NULL);
12942 
12943 	/*
12944 	 * FAST PATH for tcp packets
12945 	 */
12946 
12947 	/* u1 is # words of IP options */
12948 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12949 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12950 
12951 	/* IP options present */
12952 	if (u1) {
12953 		goto ipoptions;
12954 	} else if (!mctl_present) {
12955 		/* Check the IP header checksum.  */
12956 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill)) {
12957 			/* Clear the IP header h/w cksum flag */
12958 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12959 		} else if (!mctl_present) {
12960 			/*
12961 			 * Don't verify header checksum if this packet
12962 			 * is coming back from AH/ESP as we already did it.
12963 			 */
12964 #define	uph	((uint16_t *)ipha)
12965 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12966 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12967 #undef	uph
12968 			/* finish doing IP checksum */
12969 			sum = (sum & 0xFFFF) + (sum >> 16);
12970 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12971 			if (sum != 0 && sum != 0xFFFF) {
12972 				BUMP_MIB(ill->ill_ip_mib,
12973 				    ipIfStatsInCksumErrs);
12974 				goto error;
12975 			}
12976 		}
12977 	}
12978 
12979 	if (!mctl_present) {
12980 		UPDATE_IB_PKT_COUNT(ire);
12981 		ire->ire_last_used_time = lbolt;
12982 	}
12983 
12984 	/* packet part of fragmented IP packet? */
12985 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12986 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12987 		goto fragmented;
12988 	}
12989 
12990 	/* u1 = IP header length (20 bytes) */
12991 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12992 
12993 	/* does packet contain IP+TCP headers? */
12994 	len = mp->b_wptr - rptr;
12995 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12996 		IP_STAT(ipst, ip_tcppullup);
12997 		goto tcppullup;
12998 	}
12999 
13000 	/* TCP options present? */
13001 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13002 
13003 	/*
13004 	 * If options need to be pulled up, then goto tcpoptions.
13005 	 * otherwise we are still in the fast path
13006 	 */
13007 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13008 		IP_STAT(ipst, ip_tcpoptions);
13009 		goto tcpoptions;
13010 	}
13011 
13012 	/* multiple mblks of tcp data? */
13013 	if ((mp1 = mp->b_cont) != NULL) {
13014 		IP_STAT(ipst, ip_multipkttcp);
13015 		len += msgdsize(mp1);
13016 	}
13017 
13018 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13019 
13020 	/* part of pseudo checksum */
13021 
13022 	/* TCP datagram length */
13023 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13024 
13025 #define	iphs    ((uint16_t *)ipha)
13026 
13027 #ifdef	_BIG_ENDIAN
13028 	u1 += IPPROTO_TCP;
13029 #else
13030 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13031 #endif
13032 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13033 
13034 	/*
13035 	 * Revert to software checksum calculation if the interface
13036 	 * isn't capable of checksum offload or if IPsec is present.
13037 	 */
13038 	if (ILL_HCKSUM_CAPABLE(recv_ill) && !mctl_present && dohwcksum)
13039 		hck_flags = DB_CKSUMFLAGS(mp);
13040 
13041 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13042 		IP_STAT(ipst, ip_in_sw_cksum);
13043 
13044 	IP_CKSUM_RECV(hck_flags, u1,
13045 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13046 	    (int32_t)((uchar_t *)up - rptr),
13047 	    mp, mp1, cksum_err);
13048 
13049 	if (cksum_err) {
13050 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13051 
13052 		if (hck_flags & HCK_FULLCKSUM)
13053 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13054 		else if (hck_flags & HCK_PARTIALCKSUM)
13055 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13056 		else
13057 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13058 
13059 		goto error;
13060 	}
13061 
13062 try_again:
13063 
13064 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13065 	    zoneid, ipst)) == NULL) {
13066 		/* Send the TH_RST */
13067 		goto no_conn;
13068 	}
13069 
13070 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13071 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13072 
13073 	/*
13074 	 * TCP FAST PATH for AF_INET socket.
13075 	 *
13076 	 * TCP fast path to avoid extra work. An AF_INET socket type
13077 	 * does not have facility to receive extra information via
13078 	 * ip_process or ip_add_info. Also, when the connection was
13079 	 * established, we made a check if this connection is impacted
13080 	 * by any global IPsec policy or per connection policy (a
13081 	 * policy that comes in effect later will not apply to this
13082 	 * connection). Since all this can be determined at the
13083 	 * connection establishment time, a quick check of flags
13084 	 * can avoid extra work.
13085 	 */
13086 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13087 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13088 		ASSERT(first_mp == mp);
13089 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13090 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13091 			SET_SQUEUE(mp, tcp_rput_data, connp);
13092 			return (mp);
13093 		}
13094 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13095 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13096 		SET_SQUEUE(mp, tcp_input, connp);
13097 		return (mp);
13098 	}
13099 
13100 	if (tcph_flags == TH_SYN) {
13101 		if (IPCL_IS_TCP(connp)) {
13102 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13103 			DB_CKSUMSTART(mp) =
13104 			    (intptr_t)ip_squeue_get(ill_ring);
13105 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13106 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13107 				BUMP_MIB(ill->ill_ip_mib,
13108 				    ipIfStatsHCInDelivers);
13109 				SET_SQUEUE(mp, connp->conn_recv, connp);
13110 				return (mp);
13111 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13112 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13113 				BUMP_MIB(ill->ill_ip_mib,
13114 				    ipIfStatsHCInDelivers);
13115 				ip_squeue_enter_unbound++;
13116 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13117 				    connp);
13118 				return (mp);
13119 			}
13120 			syn_present = B_TRUE;
13121 		}
13122 	}
13123 
13124 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13125 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13126 
13127 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13128 		/* No need to send this packet to TCP */
13129 		if ((flags & TH_RST) || (flags & TH_URG)) {
13130 			CONN_DEC_REF(connp);
13131 			freemsg(first_mp);
13132 			return (NULL);
13133 		}
13134 		if (flags & TH_ACK) {
13135 			ip_xmit_reset_serialize(first_mp, ip_hdr_len, zoneid,
13136 			    ipst->ips_netstack->netstack_tcp, connp);
13137 			CONN_DEC_REF(connp);
13138 			return (NULL);
13139 		}
13140 
13141 		CONN_DEC_REF(connp);
13142 		freemsg(first_mp);
13143 		return (NULL);
13144 	}
13145 
13146 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13147 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13148 		    ipha, NULL, mctl_present);
13149 		if (first_mp == NULL) {
13150 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13151 			CONN_DEC_REF(connp);
13152 			return (NULL);
13153 		}
13154 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13155 			ASSERT(syn_present);
13156 			if (mctl_present) {
13157 				ASSERT(first_mp != mp);
13158 				first_mp->b_datap->db_struioflag |=
13159 				    STRUIO_POLICY;
13160 			} else {
13161 				ASSERT(first_mp == mp);
13162 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13163 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13164 			}
13165 		} else {
13166 			/*
13167 			 * Discard first_mp early since we're dealing with a
13168 			 * fully-connected conn_t and tcp doesn't do policy in
13169 			 * this case.
13170 			 */
13171 			if (mctl_present) {
13172 				freeb(first_mp);
13173 				mctl_present = B_FALSE;
13174 			}
13175 			first_mp = mp;
13176 		}
13177 	}
13178 
13179 	/* Initiate IPPF processing for fastpath */
13180 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13181 		uint32_t	ill_index;
13182 
13183 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13184 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13185 		if (mp == NULL) {
13186 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13187 			    "deferred/dropped during IPPF processing\n"));
13188 			CONN_DEC_REF(connp);
13189 			if (mctl_present)
13190 				freeb(first_mp);
13191 			return (NULL);
13192 		} else if (mctl_present) {
13193 			/*
13194 			 * ip_process might return a new mp.
13195 			 */
13196 			ASSERT(first_mp != mp);
13197 			first_mp->b_cont = mp;
13198 		} else {
13199 			first_mp = mp;
13200 		}
13201 
13202 	}
13203 
13204 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13205 		/*
13206 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13207 		 * make sure IPF_RECVIF is passed to ip_add_info.
13208 		 */
13209 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13210 		    IPCL_ZONEID(connp), ipst);
13211 		if (mp == NULL) {
13212 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13213 			CONN_DEC_REF(connp);
13214 			if (mctl_present)
13215 				freeb(first_mp);
13216 			return (NULL);
13217 		} else if (mctl_present) {
13218 			/*
13219 			 * ip_add_info might return a new mp.
13220 			 */
13221 			ASSERT(first_mp != mp);
13222 			first_mp->b_cont = mp;
13223 		} else {
13224 			first_mp = mp;
13225 		}
13226 	}
13227 
13228 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13229 	if (IPCL_IS_TCP(connp)) {
13230 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13231 		return (first_mp);
13232 	} else {
13233 		/* SOCK_RAW, IPPROTO_TCP case */
13234 		(connp->conn_recv)(connp, first_mp, NULL);
13235 		CONN_DEC_REF(connp);
13236 		return (NULL);
13237 	}
13238 
13239 no_conn:
13240 	/* Initiate IPPf processing, if needed. */
13241 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13242 		uint32_t ill_index;
13243 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13244 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13245 		if (first_mp == NULL) {
13246 			return (NULL);
13247 		}
13248 	}
13249 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13250 
13251 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13252 	    ipst->ips_netstack->netstack_tcp, NULL);
13253 	return (NULL);
13254 ipoptions:
13255 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13256 		goto slow_done;
13257 	}
13258 
13259 	UPDATE_IB_PKT_COUNT(ire);
13260 	ire->ire_last_used_time = lbolt;
13261 
13262 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13263 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13264 fragmented:
13265 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL)) {
13266 			if (mctl_present)
13267 				freeb(first_mp);
13268 			goto slow_done;
13269 		}
13270 		/*
13271 		 * Make sure that first_mp points back to mp as
13272 		 * the mp we came in with could have changed in
13273 		 * ip_rput_fragment().
13274 		 */
13275 		ASSERT(!mctl_present);
13276 		ipha = (ipha_t *)mp->b_rptr;
13277 		first_mp = mp;
13278 	}
13279 
13280 	/* Now we have a complete datagram, destined for this machine. */
13281 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13282 
13283 	len = mp->b_wptr - mp->b_rptr;
13284 	/* Pull up a minimal TCP header, if necessary. */
13285 	if (len < (u1 + 20)) {
13286 tcppullup:
13287 		if (!pullupmsg(mp, u1 + 20)) {
13288 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13289 			goto error;
13290 		}
13291 		ipha = (ipha_t *)mp->b_rptr;
13292 		len = mp->b_wptr - mp->b_rptr;
13293 	}
13294 
13295 	/*
13296 	 * Extract the offset field from the TCP header.  As usual, we
13297 	 * try to help the compiler more than the reader.
13298 	 */
13299 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13300 	if (offset != 5) {
13301 tcpoptions:
13302 		if (offset < 5) {
13303 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13304 			goto error;
13305 		}
13306 		/*
13307 		 * There must be TCP options.
13308 		 * Make sure we can grab them.
13309 		 */
13310 		offset <<= 2;
13311 		offset += u1;
13312 		if (len < offset) {
13313 			if (!pullupmsg(mp, offset)) {
13314 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13315 				goto error;
13316 			}
13317 			ipha = (ipha_t *)mp->b_rptr;
13318 			len = mp->b_wptr - rptr;
13319 		}
13320 	}
13321 
13322 	/* Get the total packet length in len, including headers. */
13323 	if (mp->b_cont)
13324 		len = msgdsize(mp);
13325 
13326 	/*
13327 	 * Check the TCP checksum by pulling together the pseudo-
13328 	 * header checksum, and passing it to ip_csum to be added in
13329 	 * with the TCP datagram.
13330 	 *
13331 	 * Since we are not using the hwcksum if available we must
13332 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13333 	 * If either of these fails along the way the mblk is freed.
13334 	 * If this logic ever changes and mblk is reused to say send
13335 	 * ICMP's back, then this flag may need to be cleared in
13336 	 * other places as well.
13337 	 */
13338 	DB_CKSUMFLAGS(mp) = 0;
13339 
13340 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13341 
13342 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13343 #ifdef	_BIG_ENDIAN
13344 	u1 += IPPROTO_TCP;
13345 #else
13346 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13347 #endif
13348 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13349 	/*
13350 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13351 	 */
13352 	IP_STAT(ipst, ip_in_sw_cksum);
13353 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13354 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13355 		goto error;
13356 	}
13357 
13358 	IP_STAT(ipst, ip_tcp_slow_path);
13359 	goto try_again;
13360 #undef  iphs
13361 #undef  rptr
13362 
13363 error:
13364 	freemsg(first_mp);
13365 slow_done:
13366 	return (NULL);
13367 }
13368 
13369 /* ARGSUSED */
13370 static void
13371 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13372     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13373 {
13374 	conn_t		*connp;
13375 	uint32_t	sum;
13376 	uint32_t	u1;
13377 	ssize_t		len;
13378 	sctp_hdr_t	*sctph;
13379 	zoneid_t	zoneid = ire->ire_zoneid;
13380 	uint32_t	pktsum;
13381 	uint32_t	calcsum;
13382 	uint32_t	ports;
13383 	in6_addr_t	map_src, map_dst;
13384 	ill_t		*ill = (ill_t *)q->q_ptr;
13385 	ip_stack_t	*ipst;
13386 	sctp_stack_t	*sctps;
13387 	boolean_t	sctp_csum_err = B_FALSE;
13388 
13389 	ASSERT(recv_ill != NULL);
13390 	ipst = recv_ill->ill_ipst;
13391 	sctps = ipst->ips_netstack->netstack_sctp;
13392 
13393 #define	rptr	((uchar_t *)ipha)
13394 
13395 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13396 	ASSERT(ill != NULL);
13397 
13398 	/* u1 is # words of IP options */
13399 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13400 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13401 
13402 	/* IP options present */
13403 	if (u1 > 0) {
13404 		goto ipoptions;
13405 	} else {
13406 		/* Check the IP header checksum.  */
13407 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, recv_ill) &&
13408 		    !mctl_present) {
13409 #define	uph	((uint16_t *)ipha)
13410 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13411 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13412 #undef	uph
13413 			/* finish doing IP checksum */
13414 			sum = (sum & 0xFFFF) + (sum >> 16);
13415 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13416 			/*
13417 			 * Don't verify header checksum if this packet
13418 			 * is coming back from AH/ESP as we already did it.
13419 			 */
13420 			if (sum != 0 && sum != 0xFFFF) {
13421 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13422 				goto error;
13423 			}
13424 		}
13425 		/*
13426 		 * Since there is no SCTP h/w cksum support yet, just
13427 		 * clear the flag.
13428 		 */
13429 		DB_CKSUMFLAGS(mp) = 0;
13430 	}
13431 
13432 	/*
13433 	 * Don't verify header checksum if this packet is coming
13434 	 * back from AH/ESP as we already did it.
13435 	 */
13436 	if (!mctl_present) {
13437 		UPDATE_IB_PKT_COUNT(ire);
13438 		ire->ire_last_used_time = lbolt;
13439 	}
13440 
13441 	/* packet part of fragmented IP packet? */
13442 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13443 	if (u1 & (IPH_MF | IPH_OFFSET))
13444 		goto fragmented;
13445 
13446 	/* u1 = IP header length (20 bytes) */
13447 	u1 = IP_SIMPLE_HDR_LENGTH;
13448 
13449 find_sctp_client:
13450 	/* Pullup if we don't have the sctp common header. */
13451 	len = MBLKL(mp);
13452 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13453 		if (mp->b_cont == NULL ||
13454 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13455 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13456 			goto error;
13457 		}
13458 		ipha = (ipha_t *)mp->b_rptr;
13459 		len = MBLKL(mp);
13460 	}
13461 
13462 	sctph = (sctp_hdr_t *)(rptr + u1);
13463 #ifdef	DEBUG
13464 	if (!skip_sctp_cksum) {
13465 #endif
13466 		pktsum = sctph->sh_chksum;
13467 		sctph->sh_chksum = 0;
13468 		calcsum = sctp_cksum(mp, u1);
13469 		sctph->sh_chksum = pktsum;
13470 		if (calcsum != pktsum)
13471 			sctp_csum_err = B_TRUE;
13472 #ifdef	DEBUG	/* skip_sctp_cksum */
13473 	}
13474 #endif
13475 	/* get the ports */
13476 	ports = *(uint32_t *)&sctph->sh_sport;
13477 
13478 	IRE_REFRELE(ire);
13479 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13480 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13481 	if (sctp_csum_err) {
13482 		/*
13483 		 * No potential sctp checksum errors go to the Sun
13484 		 * sctp stack however they might be Adler-32 summed
13485 		 * packets a userland stack bound to a raw IP socket
13486 		 * could reasonably use. Note though that Adler-32 is
13487 		 * a long deprecated algorithm and customer sctp
13488 		 * networks should eventually migrate to CRC-32 at
13489 		 * which time this facility should be removed.
13490 		 */
13491 		flags |= IP_FF_SCTP_CSUM_ERR;
13492 		goto no_conn;
13493 	}
13494 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13495 	    sctps)) == NULL) {
13496 		/* Check for raw socket or OOTB handling */
13497 		goto no_conn;
13498 	}
13499 
13500 	/* Found a client; up it goes */
13501 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13502 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13503 	return;
13504 
13505 no_conn:
13506 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13507 	    ports, mctl_present, flags, B_TRUE, zoneid);
13508 	return;
13509 
13510 ipoptions:
13511 	DB_CKSUMFLAGS(mp) = 0;
13512 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13513 		goto slow_done;
13514 
13515 	UPDATE_IB_PKT_COUNT(ire);
13516 	ire->ire_last_used_time = lbolt;
13517 
13518 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13519 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13520 fragmented:
13521 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
13522 			goto slow_done;
13523 		/*
13524 		 * Make sure that first_mp points back to mp as
13525 		 * the mp we came in with could have changed in
13526 		 * ip_rput_fragment().
13527 		 */
13528 		ASSERT(!mctl_present);
13529 		ipha = (ipha_t *)mp->b_rptr;
13530 		first_mp = mp;
13531 	}
13532 
13533 	/* Now we have a complete datagram, destined for this machine. */
13534 	u1 = IPH_HDR_LENGTH(ipha);
13535 	goto find_sctp_client;
13536 #undef  iphs
13537 #undef  rptr
13538 
13539 error:
13540 	freemsg(first_mp);
13541 slow_done:
13542 	IRE_REFRELE(ire);
13543 }
13544 
13545 #define	VER_BITS	0xF0
13546 #define	VERSION_6	0x60
13547 
13548 static boolean_t
13549 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13550     ipaddr_t *dstp, ip_stack_t *ipst)
13551 {
13552 	uint_t	opt_len;
13553 	ipha_t *ipha;
13554 	ssize_t len;
13555 	uint_t	pkt_len;
13556 
13557 	ASSERT(ill != NULL);
13558 	IP_STAT(ipst, ip_ipoptions);
13559 	ipha = *iphapp;
13560 
13561 #define	rptr    ((uchar_t *)ipha)
13562 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13563 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13564 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13565 		freemsg(mp);
13566 		return (B_FALSE);
13567 	}
13568 
13569 	/* multiple mblk or too short */
13570 	pkt_len = ntohs(ipha->ipha_length);
13571 
13572 	/* Get the number of words of IP options in the IP header. */
13573 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13574 	if (opt_len) {
13575 		/* IP Options present!  Validate and process. */
13576 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13577 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13578 			goto done;
13579 		}
13580 		/*
13581 		 * Recompute complete header length and make sure we
13582 		 * have access to all of it.
13583 		 */
13584 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13585 		if (len > (mp->b_wptr - rptr)) {
13586 			if (len > pkt_len) {
13587 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13588 				goto done;
13589 			}
13590 			if (!pullupmsg(mp, len)) {
13591 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13592 				goto done;
13593 			}
13594 			ipha = (ipha_t *)mp->b_rptr;
13595 		}
13596 		/*
13597 		 * Go off to ip_rput_options which returns the next hop
13598 		 * destination address, which may have been affected
13599 		 * by source routing.
13600 		 */
13601 		IP_STAT(ipst, ip_opt);
13602 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13603 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13604 			return (B_FALSE);
13605 		}
13606 	}
13607 	*iphapp = ipha;
13608 	return (B_TRUE);
13609 done:
13610 	/* clear b_prev - used by ip_mroute_decap */
13611 	mp->b_prev = NULL;
13612 	freemsg(mp);
13613 	return (B_FALSE);
13614 #undef  rptr
13615 }
13616 
13617 /*
13618  * Deal with the fact that there is no ire for the destination.
13619  */
13620 static ire_t *
13621 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13622 {
13623 	ipha_t	*ipha;
13624 	ill_t	*ill;
13625 	ire_t	*ire;
13626 	ip_stack_t *ipst;
13627 	enum	ire_forward_action ret_action;
13628 
13629 	ipha = (ipha_t *)mp->b_rptr;
13630 	ill = (ill_t *)q->q_ptr;
13631 
13632 	ASSERT(ill != NULL);
13633 	ipst = ill->ill_ipst;
13634 
13635 	/*
13636 	 * No IRE for this destination, so it can't be for us.
13637 	 * Unless we are forwarding, drop the packet.
13638 	 * We have to let source routed packets through
13639 	 * since we don't yet know if they are 'ping -l'
13640 	 * packets i.e. if they will go out over the
13641 	 * same interface as they came in on.
13642 	 */
13643 	if (ll_multicast) {
13644 		freemsg(mp);
13645 		return (NULL);
13646 	}
13647 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13648 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13649 		freemsg(mp);
13650 		return (NULL);
13651 	}
13652 
13653 	/*
13654 	 * Mark this packet as having originated externally.
13655 	 *
13656 	 * For non-forwarding code path, ire_send later double
13657 	 * checks this interface to see if it is still exists
13658 	 * post-ARP resolution.
13659 	 *
13660 	 * Also, IPQOS uses this to differentiate between
13661 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13662 	 * QOS packet processing in ip_wput_attach_llhdr().
13663 	 * The QoS module can mark the b_band for a fastpath message
13664 	 * or the dl_priority field in a unitdata_req header for
13665 	 * CoS marking. This info can only be found in
13666 	 * ip_wput_attach_llhdr().
13667 	 */
13668 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13669 	/*
13670 	 * Clear the indication that this may have a hardware checksum
13671 	 * as we are not using it
13672 	 */
13673 	DB_CKSUMFLAGS(mp) = 0;
13674 
13675 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13676 	    msg_getlabel(mp), ipst);
13677 
13678 	if (ire == NULL && ret_action == Forward_check_multirt) {
13679 		/* Let ip_newroute handle CGTP  */
13680 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13681 		return (NULL);
13682 	}
13683 
13684 	if (ire != NULL)
13685 		return (ire);
13686 
13687 	mp->b_prev = mp->b_next = 0;
13688 
13689 	if (ret_action == Forward_blackhole) {
13690 		freemsg(mp);
13691 		return (NULL);
13692 	}
13693 	/* send icmp unreachable */
13694 	q = WR(q);
13695 	/* Sent by forwarding path, and router is global zone */
13696 	if (ip_source_routed(ipha, ipst)) {
13697 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13698 		    GLOBAL_ZONEID, ipst);
13699 	} else {
13700 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13701 		    ipst);
13702 	}
13703 
13704 	return (NULL);
13705 
13706 }
13707 
13708 /*
13709  * check ip header length and align it.
13710  */
13711 static boolean_t
13712 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13713 {
13714 	ssize_t len;
13715 	ill_t *ill;
13716 	ipha_t	*ipha;
13717 
13718 	len = MBLKL(mp);
13719 
13720 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13721 		ill = (ill_t *)q->q_ptr;
13722 
13723 		if (!OK_32PTR(mp->b_rptr))
13724 			IP_STAT(ipst, ip_notaligned1);
13725 		else
13726 			IP_STAT(ipst, ip_notaligned2);
13727 		/* Guard against bogus device drivers */
13728 		if (len < 0) {
13729 			/* clear b_prev - used by ip_mroute_decap */
13730 			mp->b_prev = NULL;
13731 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13732 			freemsg(mp);
13733 			return (B_FALSE);
13734 		}
13735 
13736 		if (ip_rput_pullups++ == 0) {
13737 			ipha = (ipha_t *)mp->b_rptr;
13738 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13739 			    "ip_check_and_align_header: %s forced us to "
13740 			    " pullup pkt, hdr len %ld, hdr addr %p",
13741 			    ill->ill_name, len, (void *)ipha);
13742 		}
13743 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13744 			/* clear b_prev - used by ip_mroute_decap */
13745 			mp->b_prev = NULL;
13746 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13747 			freemsg(mp);
13748 			return (B_FALSE);
13749 		}
13750 	}
13751 	return (B_TRUE);
13752 }
13753 
13754 /*
13755  * Handle the situation where a packet came in on `ill' but matched an IRE
13756  * whose ire_rfq doesn't match `ill'.  We return the IRE that should be used
13757  * for interface statistics.
13758  */
13759 ire_t *
13760 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13761 {
13762 	ire_t		*new_ire;
13763 	ill_t		*ire_ill;
13764 	uint_t		ifindex;
13765 	ip_stack_t	*ipst = ill->ill_ipst;
13766 	boolean_t	strict_check = B_FALSE;
13767 
13768 	/*
13769 	 * IPMP common case: if IRE and ILL are in the same group, there's no
13770 	 * issue (e.g. packet received on an underlying interface matched an
13771 	 * IRE_LOCAL on its associated group interface).
13772 	 */
13773 	if (ire->ire_rfq != NULL &&
13774 	    IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr)) {
13775 		return (ire);
13776 	}
13777 
13778 	/*
13779 	 * Do another ire lookup here, using the ingress ill, to see if the
13780 	 * interface is in a usesrc group.
13781 	 * As long as the ills belong to the same group, we don't consider
13782 	 * them to be arriving on the wrong interface. Thus, if the switch
13783 	 * is doing inbound load spreading, we won't drop packets when the
13784 	 * ip*_strict_dst_multihoming switch is on.
13785 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13786 	 * where the local address may not be unique. In this case we were
13787 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13788 	 * actually returned. The new lookup, which is more specific, should
13789 	 * only find the IRE_LOCAL associated with the ingress ill if one
13790 	 * exists.
13791 	 */
13792 
13793 	if (ire->ire_ipversion == IPV4_VERSION) {
13794 		if (ipst->ips_ip_strict_dst_multihoming)
13795 			strict_check = B_TRUE;
13796 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13797 		    ill->ill_ipif, ALL_ZONES, NULL,
13798 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13799 	} else {
13800 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13801 		if (ipst->ips_ipv6_strict_dst_multihoming)
13802 			strict_check = B_TRUE;
13803 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13804 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13805 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), ipst);
13806 	}
13807 	/*
13808 	 * If the same ire that was returned in ip_input() is found then this
13809 	 * is an indication that usesrc groups are in use. The packet
13810 	 * arrived on a different ill in the group than the one associated with
13811 	 * the destination address.  If a different ire was found then the same
13812 	 * IP address must be hosted on multiple ills. This is possible with
13813 	 * unnumbered point2point interfaces. We switch to use this new ire in
13814 	 * order to have accurate interface statistics.
13815 	 */
13816 	if (new_ire != NULL) {
13817 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13818 			ire_refrele(ire);
13819 			ire = new_ire;
13820 		} else {
13821 			ire_refrele(new_ire);
13822 		}
13823 		return (ire);
13824 	} else if ((ire->ire_rfq == NULL) &&
13825 	    (ire->ire_ipversion == IPV4_VERSION)) {
13826 		/*
13827 		 * The best match could have been the original ire which
13828 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13829 		 * the strict multihoming checks are irrelevant as we consider
13830 		 * local addresses hosted on lo0 to be interface agnostic. We
13831 		 * only expect a null ire_rfq on IREs which are associated with
13832 		 * lo0 hence we can return now.
13833 		 */
13834 		return (ire);
13835 	}
13836 
13837 	/*
13838 	 * Chase pointers once and store locally.
13839 	 */
13840 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13841 	    (ill_t *)(ire->ire_rfq->q_ptr);
13842 	ifindex = ill->ill_usesrc_ifindex;
13843 
13844 	/*
13845 	 * Check if it's a legal address on the 'usesrc' interface.
13846 	 */
13847 	if ((ifindex != 0) && (ire_ill != NULL) &&
13848 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13849 		return (ire);
13850 	}
13851 
13852 	/*
13853 	 * If the ip*_strict_dst_multihoming switch is on then we can
13854 	 * only accept this packet if the interface is marked as routing.
13855 	 */
13856 	if (!(strict_check))
13857 		return (ire);
13858 
13859 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13860 	    ILLF_ROUTER) != 0) {
13861 		return (ire);
13862 	}
13863 
13864 	ire_refrele(ire);
13865 	return (NULL);
13866 }
13867 
13868 /*
13869  *
13870  * This is the fast forward path. If we are here, we dont need to
13871  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13872  * needed to find the nexthop in this case is much simpler
13873  */
13874 ire_t *
13875 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13876 {
13877 	ipha_t	*ipha;
13878 	ire_t	*src_ire;
13879 	ill_t	*stq_ill;
13880 	uint_t	hlen;
13881 	uint_t	pkt_len;
13882 	uint32_t sum;
13883 	queue_t	*dev_q;
13884 	ip_stack_t *ipst = ill->ill_ipst;
13885 	mblk_t *fpmp;
13886 	enum	ire_forward_action ret_action;
13887 
13888 	ipha = (ipha_t *)mp->b_rptr;
13889 
13890 	if (ire != NULL &&
13891 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13892 	    ire->ire_zoneid != ALL_ZONES) {
13893 		/*
13894 		 * Should only use IREs that are visible to the global
13895 		 * zone for forwarding.
13896 		 */
13897 		ire_refrele(ire);
13898 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13899 		/*
13900 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13901 		 * transient cases. In such case, just drop the packet
13902 		 */
13903 		if (ire->ire_type != IRE_CACHE)
13904 			goto drop;
13905 	}
13906 
13907 	/*
13908 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13909 	 * The loopback address check for both src and dst has already
13910 	 * been checked in ip_input
13911 	 */
13912 
13913 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13914 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13915 		goto drop;
13916 	}
13917 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13918 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13919 
13920 	if (src_ire != NULL) {
13921 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13922 		ire_refrele(src_ire);
13923 		goto drop;
13924 	}
13925 
13926 	/* No ire cache of nexthop. So first create one  */
13927 	if (ire == NULL) {
13928 
13929 		ire = ire_forward_simple(dst, &ret_action, ipst);
13930 
13931 		/*
13932 		 * We only come to ip_fast_forward if ip_cgtp_filter
13933 		 * is not set. So ire_forward() should not return with
13934 		 * Forward_check_multirt as the next action.
13935 		 */
13936 		ASSERT(ret_action != Forward_check_multirt);
13937 		if (ire == NULL) {
13938 			/* An attempt was made to forward the packet */
13939 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13940 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13941 			mp->b_prev = mp->b_next = 0;
13942 			/* send icmp unreachable */
13943 			/* Sent by forwarding path, and router is global zone */
13944 			if (ret_action == Forward_ret_icmp_err) {
13945 				if (ip_source_routed(ipha, ipst)) {
13946 					icmp_unreachable(ill->ill_wq, mp,
13947 					    ICMP_SOURCE_ROUTE_FAILED,
13948 					    GLOBAL_ZONEID, ipst);
13949 				} else {
13950 					icmp_unreachable(ill->ill_wq, mp,
13951 					    ICMP_HOST_UNREACHABLE,
13952 					    GLOBAL_ZONEID, ipst);
13953 				}
13954 			} else {
13955 				freemsg(mp);
13956 			}
13957 			return (NULL);
13958 		}
13959 	}
13960 
13961 	/*
13962 	 * Forwarding fastpath exception case:
13963 	 * If any of the following are true, we take the slowpath:
13964 	 *	o forwarding is not enabled
13965 	 *	o incoming and outgoing interface are the same, or in the same
13966 	 *	  IPMP group.
13967 	 *	o corresponding ire is in incomplete state
13968 	 *	o packet needs fragmentation
13969 	 *	o ARP cache is not resolved
13970 	 *
13971 	 * The codeflow from here on is thus:
13972 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13973 	 */
13974 	pkt_len = ntohs(ipha->ipha_length);
13975 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13976 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13977 	    (ill == stq_ill) || IS_IN_SAME_ILLGRP(ill, stq_ill) ||
13978 	    (ire->ire_nce == NULL) ||
13979 	    (pkt_len > ire->ire_max_frag) ||
13980 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13981 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13982 	    ipha->ipha_ttl <= 1) {
13983 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13984 		    ipha, ill, B_FALSE, B_TRUE);
13985 		return (ire);
13986 	}
13987 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13988 
13989 	DTRACE_PROBE4(ip4__forwarding__start,
13990 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13991 
13992 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13993 	    ipst->ips_ipv4firewall_forwarding,
13994 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13995 
13996 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13997 
13998 	if (mp == NULL)
13999 		goto drop;
14000 
14001 	mp->b_datap->db_struioun.cksum.flags = 0;
14002 	/* Adjust the checksum to reflect the ttl decrement. */
14003 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14004 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14005 	ipha->ipha_ttl--;
14006 
14007 	/*
14008 	 * Write the link layer header.  We can do this safely here,
14009 	 * because we have already tested to make sure that the IP
14010 	 * policy is not set, and that we have a fast path destination
14011 	 * header.
14012 	 */
14013 	mp->b_rptr -= hlen;
14014 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14015 
14016 	UPDATE_IB_PKT_COUNT(ire);
14017 	ire->ire_last_used_time = lbolt;
14018 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14019 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14020 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14021 
14022 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14023 		dev_q = ire->ire_stq->q_next;
14024 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14025 			goto indiscard;
14026 	}
14027 
14028 	DTRACE_PROBE4(ip4__physical__out__start,
14029 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14030 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14031 	    ipst->ips_ipv4firewall_physical_out,
14032 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14033 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14034 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14035 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14036 	    ip6_t *, NULL, int, 0);
14037 
14038 	if (mp != NULL) {
14039 		if (ipst->ips_ipobs_enabled) {
14040 			zoneid_t szone;
14041 
14042 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14043 			    ipst, ALL_ZONES);
14044 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14045 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14046 		}
14047 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC, NULL);
14048 	}
14049 	return (ire);
14050 
14051 indiscard:
14052 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14053 drop:
14054 	if (mp != NULL)
14055 		freemsg(mp);
14056 	return (ire);
14057 
14058 }
14059 
14060 /*
14061  * This function is called in the forwarding slowpath, when
14062  * either the ire lacks the link-layer address, or the packet needs
14063  * further processing(eg. fragmentation), before transmission.
14064  */
14065 
14066 static void
14067 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14068     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14069 {
14070 	queue_t		*dev_q;
14071 	ire_t		*src_ire;
14072 	ip_stack_t	*ipst = ill->ill_ipst;
14073 	boolean_t	same_illgrp = B_FALSE;
14074 
14075 	ASSERT(ire->ire_stq != NULL);
14076 
14077 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14078 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14079 
14080 	/*
14081 	 * If the caller of this function is ip_fast_forward() skip the
14082 	 * next three checks as it does not apply.
14083 	 */
14084 	if (from_ip_fast_forward)
14085 		goto skip;
14086 
14087 	if (ll_multicast != 0) {
14088 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14089 		goto drop_pkt;
14090 	}
14091 
14092 	/*
14093 	 * check if ipha_src is a broadcast address. Note that this
14094 	 * check is redundant when we get here from ip_fast_forward()
14095 	 * which has already done this check. However, since we can
14096 	 * also get here from ip_rput_process_broadcast() or, for
14097 	 * for the slow path through ip_fast_forward(), we perform
14098 	 * the check again for code-reusability
14099 	 */
14100 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14101 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14102 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14103 		if (src_ire != NULL)
14104 			ire_refrele(src_ire);
14105 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14106 		ip2dbg(("ip_rput_process_forward: Received packet with"
14107 		    " bad src/dst address on %s\n", ill->ill_name));
14108 		goto drop_pkt;
14109 	}
14110 
14111 	/*
14112 	 * Check if we want to forward this one at this time.
14113 	 * We allow source routed packets on a host provided that
14114 	 * they go out the same ill or illgrp as they came in on.
14115 	 *
14116 	 * XXX To be quicker, we may wish to not chase pointers to
14117 	 * get the ILLF_ROUTER flag and instead store the
14118 	 * forwarding policy in the ire.  An unfortunate
14119 	 * side-effect of that would be requiring an ire flush
14120 	 * whenever the ILLF_ROUTER flag changes.
14121 	 */
14122 skip:
14123 	same_illgrp = IS_IN_SAME_ILLGRP(ill, (ill_t *)ire->ire_rfq->q_ptr);
14124 
14125 	if (((ill->ill_flags &
14126 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags & ILLF_ROUTER) == 0) &&
14127 	    !(ip_source_routed(ipha, ipst) &&
14128 	    (ire->ire_rfq == q || same_illgrp))) {
14129 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14130 		if (ip_source_routed(ipha, ipst)) {
14131 			q = WR(q);
14132 			/*
14133 			 * Clear the indication that this may have
14134 			 * hardware checksum as we are not using it.
14135 			 */
14136 			DB_CKSUMFLAGS(mp) = 0;
14137 			/* Sent by forwarding path, and router is global zone */
14138 			icmp_unreachable(q, mp,
14139 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14140 			return;
14141 		}
14142 		goto drop_pkt;
14143 	}
14144 
14145 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14146 
14147 	/* Packet is being forwarded. Turning off hwcksum flag. */
14148 	DB_CKSUMFLAGS(mp) = 0;
14149 	if (ipst->ips_ip_g_send_redirects) {
14150 		/*
14151 		 * Check whether the incoming interface and outgoing
14152 		 * interface is part of the same group. If so,
14153 		 * send redirects.
14154 		 *
14155 		 * Check the source address to see if it originated
14156 		 * on the same logical subnet it is going back out on.
14157 		 * If so, we should be able to send it a redirect.
14158 		 * Avoid sending a redirect if the destination
14159 		 * is directly connected (i.e., ipha_dst is the same
14160 		 * as ire_gateway_addr or the ire_addr of the
14161 		 * nexthop IRE_CACHE ), or if the packet was source
14162 		 * routed out this interface.
14163 		 */
14164 		ipaddr_t src, nhop;
14165 		mblk_t	*mp1;
14166 		ire_t	*nhop_ire = NULL;
14167 
14168 		/*
14169 		 * Check whether ire_rfq and q are from the same ill or illgrp.
14170 		 * If so, send redirects.
14171 		 */
14172 		if ((ire->ire_rfq == q || same_illgrp) &&
14173 		    !ip_source_routed(ipha, ipst)) {
14174 
14175 			nhop = (ire->ire_gateway_addr != 0 ?
14176 			    ire->ire_gateway_addr : ire->ire_addr);
14177 
14178 			if (ipha->ipha_dst == nhop) {
14179 				/*
14180 				 * We avoid sending a redirect if the
14181 				 * destination is directly connected
14182 				 * because it is possible that multiple
14183 				 * IP subnets may have been configured on
14184 				 * the link, and the source may not
14185 				 * be on the same subnet as ip destination,
14186 				 * even though they are on the same
14187 				 * physical link.
14188 				 */
14189 				goto sendit;
14190 			}
14191 
14192 			src = ipha->ipha_src;
14193 
14194 			/*
14195 			 * We look up the interface ire for the nexthop,
14196 			 * to see if ipha_src is in the same subnet
14197 			 * as the nexthop.
14198 			 *
14199 			 * Note that, if, in the future, IRE_CACHE entries
14200 			 * are obsoleted,  this lookup will not be needed,
14201 			 * as the ire passed to this function will be the
14202 			 * same as the nhop_ire computed below.
14203 			 */
14204 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14205 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14206 			    0, NULL, MATCH_IRE_TYPE, ipst);
14207 
14208 			if (nhop_ire != NULL) {
14209 				if ((src & nhop_ire->ire_mask) ==
14210 				    (nhop & nhop_ire->ire_mask)) {
14211 					/*
14212 					 * The source is directly connected.
14213 					 * Just copy the ip header (which is
14214 					 * in the first mblk)
14215 					 */
14216 					mp1 = copyb(mp);
14217 					if (mp1 != NULL) {
14218 						icmp_send_redirect(WR(q), mp1,
14219 						    nhop, ipst);
14220 					}
14221 				}
14222 				ire_refrele(nhop_ire);
14223 			}
14224 		}
14225 	}
14226 sendit:
14227 	dev_q = ire->ire_stq->q_next;
14228 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14229 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14230 		freemsg(mp);
14231 		return;
14232 	}
14233 
14234 	ip_rput_forward(ire, ipha, mp, ill);
14235 	return;
14236 
14237 drop_pkt:
14238 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14239 	freemsg(mp);
14240 }
14241 
14242 ire_t *
14243 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14244     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14245 {
14246 	queue_t		*q;
14247 	uint16_t	hcksumflags;
14248 	ip_stack_t	*ipst = ill->ill_ipst;
14249 
14250 	q = *qp;
14251 
14252 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14253 
14254 	/*
14255 	 * Clear the indication that this may have hardware
14256 	 * checksum as we are not using it for forwarding.
14257 	 */
14258 	hcksumflags = DB_CKSUMFLAGS(mp);
14259 	DB_CKSUMFLAGS(mp) = 0;
14260 
14261 	/*
14262 	 * Directed broadcast forwarding: if the packet came in over a
14263 	 * different interface then it is routed out over we can forward it.
14264 	 */
14265 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14266 		ire_refrele(ire);
14267 		freemsg(mp);
14268 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14269 		return (NULL);
14270 	}
14271 	/*
14272 	 * For multicast we have set dst to be INADDR_BROADCAST
14273 	 * for delivering to all STREAMS.
14274 	 */
14275 	if (!CLASSD(ipha->ipha_dst)) {
14276 		ire_t *new_ire;
14277 		ipif_t *ipif;
14278 
14279 		ipif = ipif_get_next_ipif(NULL, ill);
14280 		if (ipif == NULL) {
14281 discard:		ire_refrele(ire);
14282 			freemsg(mp);
14283 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14284 			return (NULL);
14285 		}
14286 		new_ire = ire_ctable_lookup(dst, 0, 0,
14287 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14288 		ipif_refrele(ipif);
14289 
14290 		if (new_ire != NULL) {
14291 			/*
14292 			 * If the matching IRE_BROADCAST is part of an IPMP
14293 			 * group, then drop the packet unless our ill has been
14294 			 * nominated to receive for the group.
14295 			 */
14296 			if (IS_IPMP(new_ire->ire_ipif->ipif_ill) &&
14297 			    new_ire->ire_rfq != q) {
14298 				ire_refrele(new_ire);
14299 				goto discard;
14300 			}
14301 
14302 			/*
14303 			 * In the special case of multirouted broadcast
14304 			 * packets, we unconditionally need to "gateway"
14305 			 * them to the appropriate interface here.
14306 			 * In the normal case, this cannot happen, because
14307 			 * there is no broadcast IRE tagged with the
14308 			 * RTF_MULTIRT flag.
14309 			 */
14310 			if (new_ire->ire_flags & RTF_MULTIRT) {
14311 				ire_refrele(new_ire);
14312 				if (ire->ire_rfq != NULL) {
14313 					q = ire->ire_rfq;
14314 					*qp = q;
14315 				}
14316 			} else {
14317 				ire_refrele(ire);
14318 				ire = new_ire;
14319 			}
14320 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14321 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14322 				/*
14323 				 * Free the message if
14324 				 * ip_g_forward_directed_bcast is turned
14325 				 * off for non-local broadcast.
14326 				 */
14327 				ire_refrele(ire);
14328 				freemsg(mp);
14329 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14330 				return (NULL);
14331 			}
14332 		} else {
14333 			/*
14334 			 * This CGTP packet successfully passed the
14335 			 * CGTP filter, but the related CGTP
14336 			 * broadcast IRE has not been found,
14337 			 * meaning that the redundant ipif is
14338 			 * probably down. However, if we discarded
14339 			 * this packet, its duplicate would be
14340 			 * filtered out by the CGTP filter so none
14341 			 * of them would get through. So we keep
14342 			 * going with this one.
14343 			 */
14344 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14345 			if (ire->ire_rfq != NULL) {
14346 				q = ire->ire_rfq;
14347 				*qp = q;
14348 			}
14349 		}
14350 	}
14351 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14352 		/*
14353 		 * Verify that there are not more then one
14354 		 * IRE_BROADCAST with this broadcast address which
14355 		 * has ire_stq set.
14356 		 * TODO: simplify, loop over all IRE's
14357 		 */
14358 		ire_t	*ire1;
14359 		int	num_stq = 0;
14360 		mblk_t	*mp1;
14361 
14362 		/* Find the first one with ire_stq set */
14363 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14364 		for (ire1 = ire; ire1 &&
14365 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14366 		    ire1 = ire1->ire_next)
14367 			;
14368 		if (ire1) {
14369 			ire_refrele(ire);
14370 			ire = ire1;
14371 			IRE_REFHOLD(ire);
14372 		}
14373 
14374 		/* Check if there are additional ones with stq set */
14375 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14376 			if (ire->ire_addr != ire1->ire_addr)
14377 				break;
14378 			if (ire1->ire_stq) {
14379 				num_stq++;
14380 				break;
14381 			}
14382 		}
14383 		rw_exit(&ire->ire_bucket->irb_lock);
14384 		if (num_stq == 1 && ire->ire_stq != NULL) {
14385 			ip1dbg(("ip_rput_process_broadcast: directed "
14386 			    "broadcast to 0x%x\n",
14387 			    ntohl(ire->ire_addr)));
14388 			mp1 = copymsg(mp);
14389 			if (mp1) {
14390 				switch (ipha->ipha_protocol) {
14391 				case IPPROTO_UDP:
14392 					ip_udp_input(q, mp1, ipha, ire, ill);
14393 					break;
14394 				default:
14395 					ip_proto_input(q, mp1, ipha, ire, ill,
14396 					    0);
14397 					break;
14398 				}
14399 			}
14400 			/*
14401 			 * Adjust ttl to 2 (1+1 - the forward engine
14402 			 * will decrement it by one.
14403 			 */
14404 			if (ip_csum_hdr(ipha)) {
14405 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14406 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14407 				freemsg(mp);
14408 				ire_refrele(ire);
14409 				return (NULL);
14410 			}
14411 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14412 			ipha->ipha_hdr_checksum = 0;
14413 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14414 			ip_rput_process_forward(q, mp, ire, ipha,
14415 			    ill, ll_multicast, B_FALSE);
14416 			ire_refrele(ire);
14417 			return (NULL);
14418 		}
14419 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14420 		    ntohl(ire->ire_addr)));
14421 	}
14422 
14423 	/* Restore any hardware checksum flags */
14424 	DB_CKSUMFLAGS(mp) = hcksumflags;
14425 	return (ire);
14426 }
14427 
14428 /* ARGSUSED */
14429 static boolean_t
14430 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14431     int *ll_multicast, ipaddr_t *dstp)
14432 {
14433 	ip_stack_t	*ipst = ill->ill_ipst;
14434 
14435 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14436 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14437 	    ntohs(ipha->ipha_length));
14438 
14439 	/*
14440 	 * So that we don't end up with dups, only one ill in an IPMP group is
14441 	 * nominated to receive multicast traffic.
14442 	 */
14443 	if (IS_UNDER_IPMP(ill) && !ill->ill_nom_cast)
14444 		goto drop_pkt;
14445 
14446 	/*
14447 	 * Forward packets only if we have joined the allmulti
14448 	 * group on this interface.
14449 	 */
14450 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14451 		int retval;
14452 
14453 		/*
14454 		 * Clear the indication that this may have hardware
14455 		 * checksum as we are not using it.
14456 		 */
14457 		DB_CKSUMFLAGS(mp) = 0;
14458 		retval = ip_mforward(ill, ipha, mp);
14459 		/* ip_mforward updates mib variables if needed */
14460 		/* clear b_prev - used by ip_mroute_decap */
14461 		mp->b_prev = NULL;
14462 
14463 		switch (retval) {
14464 		case 0:
14465 			/*
14466 			 * pkt is okay and arrived on phyint.
14467 			 *
14468 			 * If we are running as a multicast router
14469 			 * we need to see all IGMP and/or PIM packets.
14470 			 */
14471 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14472 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14473 				goto done;
14474 			}
14475 			break;
14476 		case -1:
14477 			/* pkt is mal-formed, toss it */
14478 			goto drop_pkt;
14479 		case 1:
14480 			/* pkt is okay and arrived on a tunnel */
14481 			/*
14482 			 * If we are running a multicast router
14483 			 *  we need to see all igmp packets.
14484 			 */
14485 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14486 				*dstp = INADDR_BROADCAST;
14487 				*ll_multicast = 1;
14488 				return (B_FALSE);
14489 			}
14490 
14491 			goto drop_pkt;
14492 		}
14493 	}
14494 
14495 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14496 		/*
14497 		 * This might just be caused by the fact that
14498 		 * multiple IP Multicast addresses map to the same
14499 		 * link layer multicast - no need to increment counter!
14500 		 */
14501 		freemsg(mp);
14502 		return (B_TRUE);
14503 	}
14504 done:
14505 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14506 	/*
14507 	 * This assumes the we deliver to all streams for multicast
14508 	 * and broadcast packets.
14509 	 */
14510 	*dstp = INADDR_BROADCAST;
14511 	*ll_multicast = 1;
14512 	return (B_FALSE);
14513 drop_pkt:
14514 	ip2dbg(("ip_rput: drop pkt\n"));
14515 	freemsg(mp);
14516 	return (B_TRUE);
14517 }
14518 
14519 /*
14520  * This function is used to both return an indication of whether or not
14521  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14522  * and in doing so, determine whether or not it is broadcast vs multicast.
14523  * For it to be a broadcast packet, we must have the appropriate mblk_t
14524  * hanging off the ill_t.  If this is either not present or doesn't match
14525  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14526  * to be multicast.  Thus NICs that have no broadcast address (or no
14527  * capability for one, such as point to point links) cannot return as
14528  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14529  * the return values simplifies the current use of the return value of this
14530  * function, which is to pass through the multicast/broadcast characteristic
14531  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14532  * changing the return value to some other symbol demands the appropriate
14533  * "translation" when hpe_flags is set prior to calling hook_run() for
14534  * packet events.
14535  */
14536 int
14537 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14538 {
14539 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14540 	mblk_t *bmp;
14541 
14542 	if (ind->dl_group_address) {
14543 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14544 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14545 		    MBLKL(mb) &&
14546 		    (bmp = ill->ill_bcast_mp) != NULL) {
14547 			dl_unitdata_req_t *dlur;
14548 			uint8_t *bphys_addr;
14549 
14550 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14551 			if (ill->ill_sap_length < 0)
14552 				bphys_addr = (uchar_t *)dlur +
14553 				    dlur->dl_dest_addr_offset;
14554 			else
14555 				bphys_addr = (uchar_t *)dlur +
14556 				    dlur->dl_dest_addr_offset +
14557 				    ill->ill_sap_length;
14558 
14559 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14560 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14561 				return (HPE_BROADCAST);
14562 			}
14563 			return (HPE_MULTICAST);
14564 		}
14565 		return (HPE_MULTICAST);
14566 	}
14567 	return (0);
14568 }
14569 
14570 static boolean_t
14571 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14572     int *ll_multicast, mblk_t **mpp)
14573 {
14574 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14575 	boolean_t must_copy = B_FALSE;
14576 	struct iocblk   *iocp;
14577 	ipha_t		*ipha;
14578 	ip_stack_t	*ipst = ill->ill_ipst;
14579 
14580 #define	rptr    ((uchar_t *)ipha)
14581 
14582 	first_mp = *first_mpp;
14583 	mp = *mpp;
14584 
14585 	ASSERT(first_mp == mp);
14586 
14587 	/*
14588 	 * if db_ref > 1 then copymsg and free original. Packet may be
14589 	 * changed and do not want other entity who has a reference to this
14590 	 * message to trip over the changes. This is a blind change because
14591 	 * trying to catch all places that might change packet is too
14592 	 * difficult (since it may be a module above this one)
14593 	 *
14594 	 * This corresponds to the non-fast path case. We walk down the full
14595 	 * chain in this case, and check the db_ref count of all the dblks,
14596 	 * and do a copymsg if required. It is possible that the db_ref counts
14597 	 * of the data blocks in the mblk chain can be different.
14598 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14599 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14600 	 * 'snoop' is running.
14601 	 */
14602 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14603 		if (mp1->b_datap->db_ref > 1) {
14604 			must_copy = B_TRUE;
14605 			break;
14606 		}
14607 	}
14608 
14609 	if (must_copy) {
14610 		mp1 = copymsg(mp);
14611 		if (mp1 == NULL) {
14612 			for (mp1 = mp; mp1 != NULL;
14613 			    mp1 = mp1->b_cont) {
14614 				mp1->b_next = NULL;
14615 				mp1->b_prev = NULL;
14616 			}
14617 			freemsg(mp);
14618 			if (ill != NULL) {
14619 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14620 			} else {
14621 				BUMP_MIB(&ipst->ips_ip_mib,
14622 				    ipIfStatsInDiscards);
14623 			}
14624 			return (B_TRUE);
14625 		}
14626 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14627 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14628 			/* Copy b_prev - used by ip_mroute_decap */
14629 			to_mp->b_prev = from_mp->b_prev;
14630 			from_mp->b_prev = NULL;
14631 		}
14632 		*first_mpp = first_mp = mp1;
14633 		freemsg(mp);
14634 		mp = mp1;
14635 		*mpp = mp1;
14636 	}
14637 
14638 	ipha = (ipha_t *)mp->b_rptr;
14639 
14640 	/*
14641 	 * previous code has a case for M_DATA.
14642 	 * We want to check how that happens.
14643 	 */
14644 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14645 	switch (first_mp->b_datap->db_type) {
14646 	case M_PROTO:
14647 	case M_PCPROTO:
14648 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14649 		    DL_UNITDATA_IND) {
14650 			/* Go handle anything other than data elsewhere. */
14651 			ip_rput_dlpi(q, mp);
14652 			return (B_TRUE);
14653 		}
14654 
14655 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14656 		/* Ditch the DLPI header. */
14657 		mp1 = mp->b_cont;
14658 		ASSERT(first_mp == mp);
14659 		*first_mpp = mp1;
14660 		freeb(mp);
14661 		*mpp = mp1;
14662 		return (B_FALSE);
14663 	case M_IOCACK:
14664 		ip1dbg(("got iocack "));
14665 		iocp = (struct iocblk *)mp->b_rptr;
14666 		switch (iocp->ioc_cmd) {
14667 		case DL_IOC_HDR_INFO:
14668 			ill = (ill_t *)q->q_ptr;
14669 			ill_fastpath_ack(ill, mp);
14670 			return (B_TRUE);
14671 		case SIOCSTUNPARAM:
14672 		case OSIOCSTUNPARAM:
14673 			/* Go through qwriter_ip */
14674 			break;
14675 		case SIOCGTUNPARAM:
14676 		case OSIOCGTUNPARAM:
14677 			ip_rput_other(NULL, q, mp, NULL);
14678 			return (B_TRUE);
14679 		default:
14680 			putnext(q, mp);
14681 			return (B_TRUE);
14682 		}
14683 		/* FALLTHRU */
14684 	case M_ERROR:
14685 	case M_HANGUP:
14686 		/*
14687 		 * Since this is on the ill stream we unconditionally
14688 		 * bump up the refcount
14689 		 */
14690 		ill_refhold(ill);
14691 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14692 		return (B_TRUE);
14693 	case M_CTL:
14694 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14695 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14696 		    IPHADA_M_CTL)) {
14697 			/*
14698 			 * It's an IPsec accelerated packet.
14699 			 * Make sure that the ill from which we received the
14700 			 * packet has enabled IPsec hardware acceleration.
14701 			 */
14702 			if (!(ill->ill_capabilities &
14703 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14704 				/* IPsec kstats: bean counter */
14705 				freemsg(mp);
14706 				return (B_TRUE);
14707 			}
14708 
14709 			/*
14710 			 * Make mp point to the mblk following the M_CTL,
14711 			 * then process according to type of mp.
14712 			 * After this processing, first_mp will point to
14713 			 * the data-attributes and mp to the pkt following
14714 			 * the M_CTL.
14715 			 */
14716 			mp = first_mp->b_cont;
14717 			if (mp == NULL) {
14718 				freemsg(first_mp);
14719 				return (B_TRUE);
14720 			}
14721 			/*
14722 			 * A Hardware Accelerated packet can only be M_DATA
14723 			 * ESP or AH packet.
14724 			 */
14725 			if (mp->b_datap->db_type != M_DATA) {
14726 				/* non-M_DATA IPsec accelerated packet */
14727 				IPSECHW_DEBUG(IPSECHW_PKT,
14728 				    ("non-M_DATA IPsec accelerated pkt\n"));
14729 				freemsg(first_mp);
14730 				return (B_TRUE);
14731 			}
14732 			ipha = (ipha_t *)mp->b_rptr;
14733 			if (ipha->ipha_protocol != IPPROTO_AH &&
14734 			    ipha->ipha_protocol != IPPROTO_ESP) {
14735 				IPSECHW_DEBUG(IPSECHW_PKT,
14736 				    ("non-M_DATA IPsec accelerated pkt\n"));
14737 				freemsg(first_mp);
14738 				return (B_TRUE);
14739 			}
14740 			*mpp = mp;
14741 			return (B_FALSE);
14742 		}
14743 		putnext(q, mp);
14744 		return (B_TRUE);
14745 	case M_IOCNAK:
14746 		ip1dbg(("got iocnak "));
14747 		iocp = (struct iocblk *)mp->b_rptr;
14748 		switch (iocp->ioc_cmd) {
14749 		case SIOCSTUNPARAM:
14750 		case OSIOCSTUNPARAM:
14751 			/*
14752 			 * Since this is on the ill stream we unconditionally
14753 			 * bump up the refcount
14754 			 */
14755 			ill_refhold(ill);
14756 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14757 			return (B_TRUE);
14758 		case DL_IOC_HDR_INFO:
14759 		case SIOCGTUNPARAM:
14760 		case OSIOCGTUNPARAM:
14761 			ip_rput_other(NULL, q, mp, NULL);
14762 			return (B_TRUE);
14763 		default:
14764 			break;
14765 		}
14766 		/* FALLTHRU */
14767 	default:
14768 		putnext(q, mp);
14769 		return (B_TRUE);
14770 	}
14771 }
14772 
14773 /* Read side put procedure.  Packets coming from the wire arrive here. */
14774 void
14775 ip_rput(queue_t *q, mblk_t *mp)
14776 {
14777 	ill_t	*ill;
14778 	union DL_primitives *dl;
14779 
14780 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14781 
14782 	ill = (ill_t *)q->q_ptr;
14783 
14784 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14785 		/*
14786 		 * If things are opening or closing, only accept high-priority
14787 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14788 		 * created; on close, things hanging off the ill may have been
14789 		 * freed already.)
14790 		 */
14791 		dl = (union DL_primitives *)mp->b_rptr;
14792 		if (DB_TYPE(mp) != M_PCPROTO ||
14793 		    dl->dl_primitive == DL_UNITDATA_IND) {
14794 			/*
14795 			 * SIOC[GS]TUNPARAM ioctls can come here.
14796 			 */
14797 			inet_freemsg(mp);
14798 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14799 			    "ip_rput_end: q %p (%S)", q, "uninit");
14800 			return;
14801 		}
14802 	}
14803 
14804 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14805 	    "ip_rput_end: q %p (%S)", q, "end");
14806 
14807 	ip_input(ill, NULL, mp, NULL);
14808 }
14809 
14810 static mblk_t *
14811 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14812 {
14813 	mblk_t *mp1;
14814 	boolean_t adjusted = B_FALSE;
14815 	ip_stack_t *ipst = ill->ill_ipst;
14816 
14817 	IP_STAT(ipst, ip_db_ref);
14818 	/*
14819 	 * The IP_RECVSLLA option depends on having the
14820 	 * link layer header. First check that:
14821 	 * a> the underlying device is of type ether,
14822 	 * since this option is currently supported only
14823 	 * over ethernet.
14824 	 * b> there is enough room to copy over the link
14825 	 * layer header.
14826 	 *
14827 	 * Once the checks are done, adjust rptr so that
14828 	 * the link layer header will be copied via
14829 	 * copymsg. Note that, IFT_ETHER may be returned
14830 	 * by some non-ethernet drivers but in this case
14831 	 * the second check will fail.
14832 	 */
14833 	if (ill->ill_type == IFT_ETHER &&
14834 	    (mp->b_rptr - mp->b_datap->db_base) >=
14835 	    sizeof (struct ether_header)) {
14836 		mp->b_rptr -= sizeof (struct ether_header);
14837 		adjusted = B_TRUE;
14838 	}
14839 	mp1 = copymsg(mp);
14840 
14841 	if (mp1 == NULL) {
14842 		mp->b_next = NULL;
14843 		/* clear b_prev - used by ip_mroute_decap */
14844 		mp->b_prev = NULL;
14845 		freemsg(mp);
14846 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14847 		return (NULL);
14848 	}
14849 
14850 	if (adjusted) {
14851 		/*
14852 		 * Copy is done. Restore the pointer in
14853 		 * the _new_ mblk
14854 		 */
14855 		mp1->b_rptr += sizeof (struct ether_header);
14856 	}
14857 
14858 	/* Copy b_prev - used by ip_mroute_decap */
14859 	mp1->b_prev = mp->b_prev;
14860 	mp->b_prev = NULL;
14861 
14862 	/* preserve the hardware checksum flags and data, if present */
14863 	if (DB_CKSUMFLAGS(mp) != 0) {
14864 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14865 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14866 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14867 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14868 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14869 	}
14870 
14871 	freemsg(mp);
14872 	return (mp1);
14873 }
14874 
14875 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14876 	if (tail != NULL)					\
14877 		tail->b_next = mp;				\
14878 	else							\
14879 		head = mp;					\
14880 	tail = mp;						\
14881 	cnt++;							\
14882 }
14883 
14884 /*
14885  * Direct read side procedure capable of dealing with chains. GLDv3 based
14886  * drivers call this function directly with mblk chains while STREAMS
14887  * read side procedure ip_rput() calls this for single packet with ip_ring
14888  * set to NULL to process one packet at a time.
14889  *
14890  * The ill will always be valid if this function is called directly from
14891  * the driver.
14892  *
14893  * If ip_input() is called from GLDv3:
14894  *
14895  *   - This must be a non-VLAN IP stream.
14896  *   - 'mp' is either an untagged or a special priority-tagged packet.
14897  *   - Any VLAN tag that was in the MAC header has been stripped.
14898  *
14899  * If the IP header in packet is not 32-bit aligned, every message in the
14900  * chain will be aligned before further operations. This is required on SPARC
14901  * platform.
14902  */
14903 /* ARGSUSED */
14904 void
14905 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14906     struct mac_header_info_s *mhip)
14907 {
14908 	ipaddr_t		dst = NULL;
14909 	ipaddr_t		prev_dst;
14910 	ire_t			*ire = NULL;
14911 	ipha_t			*ipha;
14912 	uint_t			pkt_len;
14913 	ssize_t			len;
14914 	uint_t			opt_len;
14915 	int			ll_multicast;
14916 	int			cgtp_flt_pkt;
14917 	queue_t			*q = ill->ill_rq;
14918 	squeue_t		*curr_sqp = NULL;
14919 	mblk_t 			*head = NULL;
14920 	mblk_t			*tail = NULL;
14921 	mblk_t			*first_mp;
14922 	int			cnt = 0;
14923 	ip_stack_t		*ipst = ill->ill_ipst;
14924 	mblk_t			*mp;
14925 	mblk_t			*dmp;
14926 	uint8_t			tag;
14927 
14928 	ASSERT(mp_chain != NULL);
14929 	ASSERT(ill != NULL);
14930 
14931 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14932 
14933 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14934 
14935 #define	rptr	((uchar_t *)ipha)
14936 
14937 	while (mp_chain != NULL) {
14938 		mp = mp_chain;
14939 		mp_chain = mp_chain->b_next;
14940 		mp->b_next = NULL;
14941 		ll_multicast = 0;
14942 
14943 		/*
14944 		 * We do ire caching from one iteration to
14945 		 * another. In the event the packet chain contains
14946 		 * all packets from the same dst, this caching saves
14947 		 * an ire_cache_lookup for each of the succeeding
14948 		 * packets in a packet chain.
14949 		 */
14950 		prev_dst = dst;
14951 
14952 		/*
14953 		 * if db_ref > 1 then copymsg and free original. Packet
14954 		 * may be changed and we do not want the other entity
14955 		 * who has a reference to this message to trip over the
14956 		 * changes. This is a blind change because trying to
14957 		 * catch all places that might change the packet is too
14958 		 * difficult.
14959 		 *
14960 		 * This corresponds to the fast path case, where we have
14961 		 * a chain of M_DATA mblks.  We check the db_ref count
14962 		 * of only the 1st data block in the mblk chain. There
14963 		 * doesn't seem to be a reason why a device driver would
14964 		 * send up data with varying db_ref counts in the mblk
14965 		 * chain. In any case the Fast path is a private
14966 		 * interface, and our drivers don't do such a thing.
14967 		 * Given the above assumption, there is no need to walk
14968 		 * down the entire mblk chain (which could have a
14969 		 * potential performance problem)
14970 		 *
14971 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
14972 		 * to here because of exclusive ip stacks and vnics.
14973 		 * Packets transmitted from exclusive stack over vnic
14974 		 * can have db_ref > 1 and when it gets looped back to
14975 		 * another vnic in a different zone, you have ip_input()
14976 		 * getting dblks with db_ref > 1. So if someone
14977 		 * complains of TCP performance under this scenario,
14978 		 * take a serious look here on the impact of copymsg().
14979 		 */
14980 
14981 		if (DB_REF(mp) > 1) {
14982 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14983 				continue;
14984 		}
14985 
14986 		/*
14987 		 * Check and align the IP header.
14988 		 */
14989 		first_mp = mp;
14990 		if (DB_TYPE(mp) == M_DATA) {
14991 			dmp = mp;
14992 		} else if (DB_TYPE(mp) == M_PROTO &&
14993 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14994 			dmp = mp->b_cont;
14995 		} else {
14996 			dmp = NULL;
14997 		}
14998 		if (dmp != NULL) {
14999 			/*
15000 			 * IP header ptr not aligned?
15001 			 * OR IP header not complete in first mblk
15002 			 */
15003 			if (!OK_32PTR(dmp->b_rptr) ||
15004 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15005 				if (!ip_check_and_align_header(q, dmp, ipst))
15006 					continue;
15007 			}
15008 		}
15009 
15010 		/*
15011 		 * ip_input fast path
15012 		 */
15013 
15014 		/* mblk type is not M_DATA */
15015 		if (DB_TYPE(mp) != M_DATA) {
15016 			if (ip_rput_process_notdata(q, &first_mp, ill,
15017 			    &ll_multicast, &mp))
15018 				continue;
15019 
15020 			/*
15021 			 * The only way we can get here is if we had a
15022 			 * packet that was either a DL_UNITDATA_IND or
15023 			 * an M_CTL for an IPsec accelerated packet.
15024 			 *
15025 			 * In either case, the first_mp will point to
15026 			 * the leading M_PROTO or M_CTL.
15027 			 */
15028 			ASSERT(first_mp != NULL);
15029 		} else if (mhip != NULL) {
15030 			/*
15031 			 * ll_multicast is set here so that it is ready
15032 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15033 			 * manipulates ll_multicast in the same fashion when
15034 			 * called from ip_rput_process_notdata.
15035 			 */
15036 			switch (mhip->mhi_dsttype) {
15037 			case MAC_ADDRTYPE_MULTICAST :
15038 				ll_multicast = HPE_MULTICAST;
15039 				break;
15040 			case MAC_ADDRTYPE_BROADCAST :
15041 				ll_multicast = HPE_BROADCAST;
15042 				break;
15043 			default :
15044 				break;
15045 			}
15046 		}
15047 
15048 		/* Only M_DATA can come here and it is always aligned */
15049 		ASSERT(DB_TYPE(mp) == M_DATA);
15050 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15051 
15052 		ipha = (ipha_t *)mp->b_rptr;
15053 		len = mp->b_wptr - rptr;
15054 		pkt_len = ntohs(ipha->ipha_length);
15055 
15056 		/*
15057 		 * We must count all incoming packets, even if they end
15058 		 * up being dropped later on.
15059 		 */
15060 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15061 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15062 
15063 		/* multiple mblk or too short */
15064 		len -= pkt_len;
15065 		if (len != 0) {
15066 			/*
15067 			 * Make sure we have data length consistent
15068 			 * with the IP header.
15069 			 */
15070 			if (mp->b_cont == NULL) {
15071 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15072 					BUMP_MIB(ill->ill_ip_mib,
15073 					    ipIfStatsInHdrErrors);
15074 					ip2dbg(("ip_input: drop pkt\n"));
15075 					freemsg(mp);
15076 					continue;
15077 				}
15078 				mp->b_wptr = rptr + pkt_len;
15079 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15080 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15081 					BUMP_MIB(ill->ill_ip_mib,
15082 					    ipIfStatsInHdrErrors);
15083 					ip2dbg(("ip_input: drop pkt\n"));
15084 					freemsg(mp);
15085 					continue;
15086 				}
15087 				(void) adjmsg(mp, -len);
15088 				IP_STAT(ipst, ip_multimblk3);
15089 			}
15090 		}
15091 
15092 		/* Obtain the dst of the current packet */
15093 		dst = ipha->ipha_dst;
15094 
15095 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15096 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15097 		    ipha, ip6_t *, NULL, int, 0);
15098 
15099 		/*
15100 		 * The following test for loopback is faster than
15101 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15102 		 * operations.
15103 		 * Note that these addresses are always in network byte order
15104 		 */
15105 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15106 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15107 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15108 			freemsg(mp);
15109 			continue;
15110 		}
15111 
15112 		/*
15113 		 * The event for packets being received from a 'physical'
15114 		 * interface is placed after validation of the source and/or
15115 		 * destination address as being local so that packets can be
15116 		 * redirected to loopback addresses using ipnat.
15117 		 */
15118 		DTRACE_PROBE4(ip4__physical__in__start,
15119 		    ill_t *, ill, ill_t *, NULL,
15120 		    ipha_t *, ipha, mblk_t *, first_mp);
15121 
15122 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15123 		    ipst->ips_ipv4firewall_physical_in,
15124 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15125 
15126 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15127 
15128 		if (first_mp == NULL) {
15129 			continue;
15130 		}
15131 		dst = ipha->ipha_dst;
15132 		/*
15133 		 * Attach any necessary label information to
15134 		 * this packet
15135 		 */
15136 		if (is_system_labeled() &&
15137 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15138 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15139 			freemsg(mp);
15140 			continue;
15141 		}
15142 
15143 		if (ipst->ips_ipobs_enabled) {
15144 			zoneid_t dzone;
15145 
15146 			/*
15147 			 * On the inbound path the src zone will be unknown as
15148 			 * this packet has come from the wire.
15149 			 */
15150 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15151 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15152 			    ill, IPV4_VERSION, 0, ipst);
15153 		}
15154 
15155 		/*
15156 		 * Reuse the cached ire only if the ipha_dst of the previous
15157 		 * packet is the same as the current packet AND it is not
15158 		 * INADDR_ANY.
15159 		 */
15160 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15161 		    (ire != NULL)) {
15162 			ire_refrele(ire);
15163 			ire = NULL;
15164 		}
15165 
15166 		opt_len = ipha->ipha_version_and_hdr_length -
15167 		    IP_SIMPLE_HDR_VERSION;
15168 
15169 		/*
15170 		 * Check to see if we can take the fastpath.
15171 		 * That is possible if the following conditions are met
15172 		 *	o Tsol disabled
15173 		 *	o CGTP disabled
15174 		 *	o ipp_action_count is 0
15175 		 *	o no options in the packet
15176 		 *	o not a RSVP packet
15177 		 * 	o not a multicast packet
15178 		 *	o ill not in IP_DHCPINIT_IF mode
15179 		 */
15180 		if (!is_system_labeled() &&
15181 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15182 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15183 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15184 			if (ire == NULL)
15185 				ire = ire_cache_lookup_simple(dst, ipst);
15186 			/*
15187 			 * Unless forwarding is enabled, dont call
15188 			 * ip_fast_forward(). Incoming packet is for forwarding
15189 			 */
15190 			if ((ill->ill_flags & ILLF_ROUTER) &&
15191 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15192 				ire = ip_fast_forward(ire, dst, ill, mp);
15193 				continue;
15194 			}
15195 			/* incoming packet is for local consumption */
15196 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15197 				goto local;
15198 		}
15199 
15200 		/*
15201 		 * Disable ire caching for anything more complex
15202 		 * than the simple fast path case we checked for above.
15203 		 */
15204 		if (ire != NULL) {
15205 			ire_refrele(ire);
15206 			ire = NULL;
15207 		}
15208 
15209 		/*
15210 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15211 		 * server to unicast DHCP packets to a DHCP client using the
15212 		 * IP address it is offering to the client.  This can be
15213 		 * disabled through the "broadcast bit", but not all DHCP
15214 		 * servers honor that bit.  Therefore, to interoperate with as
15215 		 * many DHCP servers as possible, the DHCP client allows the
15216 		 * server to unicast, but we treat those packets as broadcast
15217 		 * here.  Note that we don't rewrite the packet itself since
15218 		 * (a) that would mess up the checksums and (b) the DHCP
15219 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15220 		 * hand it the packet regardless.
15221 		 */
15222 		if (ill->ill_dhcpinit != 0 &&
15223 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15224 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15225 			udpha_t *udpha;
15226 
15227 			/*
15228 			 * Reload ipha since pullupmsg() can change b_rptr.
15229 			 */
15230 			ipha = (ipha_t *)mp->b_rptr;
15231 			udpha = (udpha_t *)&ipha[1];
15232 
15233 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15234 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15235 				    mblk_t *, mp);
15236 				dst = INADDR_BROADCAST;
15237 			}
15238 		}
15239 
15240 		/* Full-blown slow path */
15241 		if (opt_len != 0) {
15242 			if (len != 0)
15243 				IP_STAT(ipst, ip_multimblk4);
15244 			else
15245 				IP_STAT(ipst, ip_ipoptions);
15246 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15247 			    &dst, ipst))
15248 				continue;
15249 		}
15250 
15251 		/*
15252 		 * Invoke the CGTP (multirouting) filtering module to process
15253 		 * the incoming packet. Packets identified as duplicates
15254 		 * must be discarded. Filtering is active only if the
15255 		 * the ip_cgtp_filter ndd variable is non-zero.
15256 		 */
15257 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15258 		if (ipst->ips_ip_cgtp_filter &&
15259 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15260 			netstackid_t stackid;
15261 
15262 			stackid = ipst->ips_netstack->netstack_stackid;
15263 			cgtp_flt_pkt =
15264 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15265 			    ill->ill_phyint->phyint_ifindex, mp);
15266 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15267 				freemsg(first_mp);
15268 				continue;
15269 			}
15270 		}
15271 
15272 		/*
15273 		 * If rsvpd is running, let RSVP daemon handle its processing
15274 		 * and forwarding of RSVP multicast/unicast packets.
15275 		 * If rsvpd is not running but mrouted is running, RSVP
15276 		 * multicast packets are forwarded as multicast traffic
15277 		 * and RSVP unicast packets are forwarded by unicast router.
15278 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15279 		 * packets are not forwarded, but the unicast packets are
15280 		 * forwarded like unicast traffic.
15281 		 */
15282 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15283 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15284 		    NULL) {
15285 			/* RSVP packet and rsvpd running. Treat as ours */
15286 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15287 			/*
15288 			 * This assumes that we deliver to all streams for
15289 			 * multicast and broadcast packets.
15290 			 * We have to force ll_multicast to 1 to handle the
15291 			 * M_DATA messages passed in from ip_mroute_decap.
15292 			 */
15293 			dst = INADDR_BROADCAST;
15294 			ll_multicast = 1;
15295 		} else if (CLASSD(dst)) {
15296 			/* packet is multicast */
15297 			mp->b_next = NULL;
15298 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15299 			    &ll_multicast, &dst))
15300 				continue;
15301 		}
15302 
15303 		if (ire == NULL) {
15304 			ire = ire_cache_lookup(dst, ALL_ZONES,
15305 			    msg_getlabel(mp), ipst);
15306 		}
15307 
15308 		if (ire != NULL && ire->ire_stq != NULL &&
15309 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15310 		    ire->ire_zoneid != ALL_ZONES) {
15311 			/*
15312 			 * Should only use IREs that are visible from the
15313 			 * global zone for forwarding.
15314 			 */
15315 			ire_refrele(ire);
15316 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15317 			    msg_getlabel(mp), ipst);
15318 		}
15319 
15320 		if (ire == NULL) {
15321 			/*
15322 			 * No IRE for this destination, so it can't be for us.
15323 			 * Unless we are forwarding, drop the packet.
15324 			 * We have to let source routed packets through
15325 			 * since we don't yet know if they are 'ping -l'
15326 			 * packets i.e. if they will go out over the
15327 			 * same interface as they came in on.
15328 			 */
15329 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15330 			if (ire == NULL)
15331 				continue;
15332 		}
15333 
15334 		/*
15335 		 * Broadcast IRE may indicate either broadcast or
15336 		 * multicast packet
15337 		 */
15338 		if (ire->ire_type == IRE_BROADCAST) {
15339 			/*
15340 			 * Skip broadcast checks if packet is UDP multicast;
15341 			 * we'd rather not enter ip_rput_process_broadcast()
15342 			 * unless the packet is broadcast for real, since
15343 			 * that routine is a no-op for multicast.
15344 			 */
15345 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15346 			    !CLASSD(ipha->ipha_dst)) {
15347 				ire = ip_rput_process_broadcast(&q, mp,
15348 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15349 				    ll_multicast);
15350 				if (ire == NULL)
15351 					continue;
15352 			}
15353 		} else if (ire->ire_stq != NULL) {
15354 			/* fowarding? */
15355 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15356 			    ll_multicast, B_FALSE);
15357 			/* ip_rput_process_forward consumed the packet */
15358 			continue;
15359 		}
15360 
15361 local:
15362 		/*
15363 		 * If the queue in the ire is different to the ingress queue
15364 		 * then we need to check to see if we can accept the packet.
15365 		 * Note that for multicast packets and broadcast packets sent
15366 		 * to a broadcast address which is shared between multiple
15367 		 * interfaces we should not do this since we just got a random
15368 		 * broadcast ire.
15369 		 */
15370 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15371 			ire = ip_check_multihome(&ipha->ipha_dst, ire, ill);
15372 			if (ire == NULL) {
15373 				/* Drop packet */
15374 				BUMP_MIB(ill->ill_ip_mib,
15375 				    ipIfStatsForwProhibits);
15376 				freemsg(mp);
15377 				continue;
15378 			}
15379 			if (ire->ire_rfq != NULL)
15380 				q = ire->ire_rfq;
15381 		}
15382 
15383 		switch (ipha->ipha_protocol) {
15384 		case IPPROTO_TCP:
15385 			ASSERT(first_mp == mp);
15386 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15387 			    mp, 0, q, ip_ring)) != NULL) {
15388 				if (curr_sqp == NULL) {
15389 					curr_sqp = GET_SQUEUE(mp);
15390 					ASSERT(cnt == 0);
15391 					cnt++;
15392 					head = tail = mp;
15393 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15394 					ASSERT(tail != NULL);
15395 					cnt++;
15396 					tail->b_next = mp;
15397 					tail = mp;
15398 				} else {
15399 					/*
15400 					 * A different squeue. Send the
15401 					 * chain for the previous squeue on
15402 					 * its way. This shouldn't happen
15403 					 * often unless interrupt binding
15404 					 * changes.
15405 					 */
15406 					IP_STAT(ipst, ip_input_multi_squeue);
15407 					SQUEUE_ENTER(curr_sqp, head,
15408 					    tail, cnt, SQ_PROCESS, tag);
15409 					curr_sqp = GET_SQUEUE(mp);
15410 					head = mp;
15411 					tail = mp;
15412 					cnt = 1;
15413 				}
15414 			}
15415 			continue;
15416 		case IPPROTO_UDP:
15417 			ASSERT(first_mp == mp);
15418 			ip_udp_input(q, mp, ipha, ire, ill);
15419 			continue;
15420 		case IPPROTO_SCTP:
15421 			ASSERT(first_mp == mp);
15422 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15423 			    q, dst);
15424 			/* ire has been released by ip_sctp_input */
15425 			ire = NULL;
15426 			continue;
15427 		default:
15428 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15429 			continue;
15430 		}
15431 	}
15432 
15433 	if (ire != NULL)
15434 		ire_refrele(ire);
15435 
15436 	if (head != NULL)
15437 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15438 
15439 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15440 	    "ip_input_end: q %p (%S)", q, "end");
15441 #undef  rptr
15442 }
15443 
15444 /*
15445  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15446  * a chain of packets in the poll mode. The packets have gone through the
15447  * data link processing but not IP processing. For performance and latency
15448  * reasons, the squeue wants to process the chain in line instead of feeding
15449  * it back via ip_input path.
15450  *
15451  * So this is a light weight function which checks to see if the packets
15452  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15453  * but we still do the paranoid check) meant for local machine and we don't
15454  * have labels etc enabled. Packets that meet the criterion are returned to
15455  * the squeue and processed inline while the rest go via ip_input path.
15456  */
15457 /*ARGSUSED*/
15458 mblk_t *
15459 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15460     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15461 {
15462 	mblk_t 		*mp;
15463 	ipaddr_t	dst = NULL;
15464 	ipaddr_t	prev_dst;
15465 	ire_t		*ire = NULL;
15466 	ipha_t		*ipha;
15467 	uint_t		pkt_len;
15468 	ssize_t		len;
15469 	uint_t		opt_len;
15470 	queue_t		*q = ill->ill_rq;
15471 	squeue_t	*curr_sqp;
15472 	mblk_t 		*ahead = NULL;	/* Accepted head */
15473 	mblk_t		*atail = NULL;	/* Accepted tail */
15474 	uint_t		acnt = 0;	/* Accepted count */
15475 	mblk_t		*utail = NULL;	/* Unaccepted head */
15476 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15477 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15478 	ip_stack_t	*ipst = ill->ill_ipst;
15479 
15480 	*cnt = 0;
15481 
15482 	ASSERT(ill != NULL);
15483 	ASSERT(ip_ring != NULL);
15484 
15485 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15486 
15487 #define	rptr	((uchar_t *)ipha)
15488 
15489 	while (mp_chain != NULL) {
15490 		mp = mp_chain;
15491 		mp_chain = mp_chain->b_next;
15492 		mp->b_next = NULL;
15493 
15494 		/*
15495 		 * We do ire caching from one iteration to
15496 		 * another. In the event the packet chain contains
15497 		 * all packets from the same dst, this caching saves
15498 		 * an ire_cache_lookup for each of the succeeding
15499 		 * packets in a packet chain.
15500 		 */
15501 		prev_dst = dst;
15502 
15503 		ipha = (ipha_t *)mp->b_rptr;
15504 		len = mp->b_wptr - rptr;
15505 
15506 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15507 
15508 		/*
15509 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15510 		 * or doesn't have min len, reject.
15511 		 */
15512 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15513 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15514 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15515 			continue;
15516 		}
15517 
15518 		pkt_len = ntohs(ipha->ipha_length);
15519 		if (len != pkt_len) {
15520 			if (len > pkt_len) {
15521 				mp->b_wptr = rptr + pkt_len;
15522 			} else {
15523 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15524 				continue;
15525 			}
15526 		}
15527 
15528 		opt_len = ipha->ipha_version_and_hdr_length -
15529 		    IP_SIMPLE_HDR_VERSION;
15530 		dst = ipha->ipha_dst;
15531 
15532 		/* IP version bad or there are IP options */
15533 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15534 		    mp, &ipha, &dst, ipst)))
15535 			continue;
15536 
15537 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15538 		    (ipst->ips_ip_cgtp_filter &&
15539 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15540 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15541 			continue;
15542 		}
15543 
15544 		/*
15545 		 * Reuse the cached ire only if the ipha_dst of the previous
15546 		 * packet is the same as the current packet AND it is not
15547 		 * INADDR_ANY.
15548 		 */
15549 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15550 		    (ire != NULL)) {
15551 			ire_refrele(ire);
15552 			ire = NULL;
15553 		}
15554 
15555 		if (ire == NULL)
15556 			ire = ire_cache_lookup_simple(dst, ipst);
15557 
15558 		/*
15559 		 * Unless forwarding is enabled, dont call
15560 		 * ip_fast_forward(). Incoming packet is for forwarding
15561 		 */
15562 		if ((ill->ill_flags & ILLF_ROUTER) &&
15563 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15564 
15565 			DTRACE_PROBE4(ip4__physical__in__start,
15566 			    ill_t *, ill, ill_t *, NULL,
15567 			    ipha_t *, ipha, mblk_t *, mp);
15568 
15569 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15570 			    ipst->ips_ipv4firewall_physical_in,
15571 			    ill, NULL, ipha, mp, mp, 0, ipst);
15572 
15573 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15574 
15575 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15576 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15577 			    pkt_len);
15578 
15579 			if (mp != NULL)
15580 				ire = ip_fast_forward(ire, dst, ill, mp);
15581 			continue;
15582 		}
15583 
15584 		/* incoming packet is for local consumption */
15585 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15586 			goto local_accept;
15587 
15588 		/*
15589 		 * Disable ire caching for anything more complex
15590 		 * than the simple fast path case we checked for above.
15591 		 */
15592 		if (ire != NULL) {
15593 			ire_refrele(ire);
15594 			ire = NULL;
15595 		}
15596 
15597 		ire = ire_cache_lookup(dst, ALL_ZONES, msg_getlabel(mp),
15598 		    ipst);
15599 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15600 		    ire->ire_stq != NULL) {
15601 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15602 			if (ire != NULL) {
15603 				ire_refrele(ire);
15604 				ire = NULL;
15605 			}
15606 			continue;
15607 		}
15608 
15609 local_accept:
15610 
15611 		if (ire->ire_rfq != q) {
15612 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15613 			if (ire != NULL) {
15614 				ire_refrele(ire);
15615 				ire = NULL;
15616 			}
15617 			continue;
15618 		}
15619 
15620 		/*
15621 		 * The event for packets being received from a 'physical'
15622 		 * interface is placed after validation of the source and/or
15623 		 * destination address as being local so that packets can be
15624 		 * redirected to loopback addresses using ipnat.
15625 		 */
15626 		DTRACE_PROBE4(ip4__physical__in__start,
15627 		    ill_t *, ill, ill_t *, NULL,
15628 		    ipha_t *, ipha, mblk_t *, mp);
15629 
15630 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15631 		    ipst->ips_ipv4firewall_physical_in,
15632 		    ill, NULL, ipha, mp, mp, 0, ipst);
15633 
15634 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15635 
15636 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15637 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15638 
15639 		if (mp != NULL &&
15640 		    (mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15641 		    0, q, ip_ring)) != NULL) {
15642 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15643 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15644 			} else {
15645 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15646 				    SQ_FILL, SQTAG_IP_INPUT);
15647 			}
15648 		}
15649 	}
15650 
15651 	if (ire != NULL)
15652 		ire_refrele(ire);
15653 
15654 	if (uhead != NULL)
15655 		ip_input(ill, ip_ring, uhead, NULL);
15656 
15657 	if (ahead != NULL) {
15658 		*last = atail;
15659 		*cnt = acnt;
15660 		return (ahead);
15661 	}
15662 
15663 	return (NULL);
15664 #undef  rptr
15665 }
15666 
15667 static void
15668 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15669     t_uscalar_t err)
15670 {
15671 	if (dl_err == DL_SYSERR) {
15672 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15673 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15674 		    ill->ill_name, dl_primstr(prim), err);
15675 		return;
15676 	}
15677 
15678 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15679 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15680 	    dl_errstr(dl_err));
15681 }
15682 
15683 /*
15684  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15685  * than DL_UNITDATA_IND messages. If we need to process this message
15686  * exclusively, we call qwriter_ip, in which case we also need to call
15687  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15688  */
15689 void
15690 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15691 {
15692 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15693 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15694 	ill_t		*ill = q->q_ptr;
15695 	t_uscalar_t	prim = dloa->dl_primitive;
15696 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15697 
15698 	ip1dbg(("ip_rput_dlpi"));
15699 
15700 	/*
15701 	 * If we received an ACK but didn't send a request for it, then it
15702 	 * can't be part of any pending operation; discard up-front.
15703 	 */
15704 	switch (prim) {
15705 	case DL_ERROR_ACK:
15706 		reqprim = dlea->dl_error_primitive;
15707 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15708 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15709 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15710 		    dlea->dl_unix_errno));
15711 		break;
15712 	case DL_OK_ACK:
15713 		reqprim = dloa->dl_correct_primitive;
15714 		break;
15715 	case DL_INFO_ACK:
15716 		reqprim = DL_INFO_REQ;
15717 		break;
15718 	case DL_BIND_ACK:
15719 		reqprim = DL_BIND_REQ;
15720 		break;
15721 	case DL_PHYS_ADDR_ACK:
15722 		reqprim = DL_PHYS_ADDR_REQ;
15723 		break;
15724 	case DL_NOTIFY_ACK:
15725 		reqprim = DL_NOTIFY_REQ;
15726 		break;
15727 	case DL_CONTROL_ACK:
15728 		reqprim = DL_CONTROL_REQ;
15729 		break;
15730 	case DL_CAPABILITY_ACK:
15731 		reqprim = DL_CAPABILITY_REQ;
15732 		break;
15733 	}
15734 
15735 	if (prim != DL_NOTIFY_IND) {
15736 		if (reqprim == DL_PRIM_INVAL ||
15737 		    !ill_dlpi_pending(ill, reqprim)) {
15738 			/* Not a DLPI message we support or expected */
15739 			freemsg(mp);
15740 			return;
15741 		}
15742 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15743 		    dl_primstr(reqprim)));
15744 	}
15745 
15746 	switch (reqprim) {
15747 	case DL_UNBIND_REQ:
15748 		/*
15749 		 * NOTE: we mark the unbind as complete even if we got a
15750 		 * DL_ERROR_ACK, since there's not much else we can do.
15751 		 */
15752 		mutex_enter(&ill->ill_lock);
15753 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15754 		cv_signal(&ill->ill_cv);
15755 		mutex_exit(&ill->ill_lock);
15756 		break;
15757 
15758 	case DL_ENABMULTI_REQ:
15759 		if (prim == DL_OK_ACK) {
15760 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15761 				ill->ill_dlpi_multicast_state = IDS_OK;
15762 		}
15763 		break;
15764 	}
15765 
15766 	/*
15767 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15768 	 * need to become writer to continue to process it.  Because an
15769 	 * exclusive operation doesn't complete until replies to all queued
15770 	 * DLPI messages have been received, we know we're in the middle of an
15771 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15772 	 *
15773 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15774 	 * Since this is on the ill stream we unconditionally bump up the
15775 	 * refcount without doing ILL_CAN_LOOKUP().
15776 	 */
15777 	ill_refhold(ill);
15778 	if (prim == DL_NOTIFY_IND)
15779 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15780 	else
15781 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15782 }
15783 
15784 /*
15785  * Handling of DLPI messages that require exclusive access to the ipsq.
15786  *
15787  * Need to do ill_pending_mp_release on ioctl completion, which could
15788  * happen here. (along with mi_copy_done)
15789  */
15790 /* ARGSUSED */
15791 static void
15792 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15793 {
15794 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15795 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15796 	int		err = 0;
15797 	ill_t		*ill;
15798 	ipif_t		*ipif = NULL;
15799 	mblk_t		*mp1 = NULL;
15800 	conn_t		*connp = NULL;
15801 	t_uscalar_t	paddrreq;
15802 	mblk_t		*mp_hw;
15803 	boolean_t	success;
15804 	boolean_t	ioctl_aborted = B_FALSE;
15805 	boolean_t	log = B_TRUE;
15806 	ip_stack_t		*ipst;
15807 
15808 	ip1dbg(("ip_rput_dlpi_writer .."));
15809 	ill = (ill_t *)q->q_ptr;
15810 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
15811 	ASSERT(IAM_WRITER_ILL(ill));
15812 
15813 	ipst = ill->ill_ipst;
15814 
15815 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
15816 	/*
15817 	 * The current ioctl could have been aborted by the user and a new
15818 	 * ioctl to bring up another ill could have started. We could still
15819 	 * get a response from the driver later.
15820 	 */
15821 	if (ipif != NULL && ipif->ipif_ill != ill)
15822 		ioctl_aborted = B_TRUE;
15823 
15824 	switch (dloa->dl_primitive) {
15825 	case DL_ERROR_ACK:
15826 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15827 		    dl_primstr(dlea->dl_error_primitive)));
15828 
15829 		switch (dlea->dl_error_primitive) {
15830 		case DL_DISABMULTI_REQ:
15831 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15832 			break;
15833 		case DL_PROMISCON_REQ:
15834 		case DL_PROMISCOFF_REQ:
15835 		case DL_UNBIND_REQ:
15836 		case DL_ATTACH_REQ:
15837 		case DL_INFO_REQ:
15838 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15839 			break;
15840 		case DL_NOTIFY_REQ:
15841 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15842 			log = B_FALSE;
15843 			break;
15844 		case DL_PHYS_ADDR_REQ:
15845 			/*
15846 			 * For IPv6 only, there are two additional
15847 			 * phys_addr_req's sent to the driver to get the
15848 			 * IPv6 token and lla. This allows IP to acquire
15849 			 * the hardware address format for a given interface
15850 			 * without having built in knowledge of the hardware
15851 			 * address. ill_phys_addr_pend keeps track of the last
15852 			 * DL_PAR sent so we know which response we are
15853 			 * dealing with. ill_dlpi_done will update
15854 			 * ill_phys_addr_pend when it sends the next req.
15855 			 * We don't complete the IOCTL until all three DL_PARs
15856 			 * have been attempted, so set *_len to 0 and break.
15857 			 */
15858 			paddrreq = ill->ill_phys_addr_pend;
15859 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15860 			if (paddrreq == DL_IPV6_TOKEN) {
15861 				ill->ill_token_length = 0;
15862 				log = B_FALSE;
15863 				break;
15864 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15865 				ill->ill_nd_lla_len = 0;
15866 				log = B_FALSE;
15867 				break;
15868 			}
15869 			/*
15870 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15871 			 * We presumably have an IOCTL hanging out waiting
15872 			 * for completion. Find it and complete the IOCTL
15873 			 * with the error noted.
15874 			 * However, ill_dl_phys was called on an ill queue
15875 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15876 			 * set. But the ioctl is known to be pending on ill_wq.
15877 			 */
15878 			if (!ill->ill_ifname_pending)
15879 				break;
15880 			ill->ill_ifname_pending = 0;
15881 			if (!ioctl_aborted)
15882 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15883 			if (mp1 != NULL) {
15884 				/*
15885 				 * This operation (SIOCSLIFNAME) must have
15886 				 * happened on the ill. Assert there is no conn
15887 				 */
15888 				ASSERT(connp == NULL);
15889 				q = ill->ill_wq;
15890 			}
15891 			break;
15892 		case DL_BIND_REQ:
15893 			ill_dlpi_done(ill, DL_BIND_REQ);
15894 			if (ill->ill_ifname_pending)
15895 				break;
15896 			/*
15897 			 * Something went wrong with the bind.  We presumably
15898 			 * have an IOCTL hanging out waiting for completion.
15899 			 * Find it, take down the interface that was coming
15900 			 * up, and complete the IOCTL with the error noted.
15901 			 */
15902 			if (!ioctl_aborted)
15903 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15904 			if (mp1 != NULL) {
15905 				/*
15906 				 * This might be a result of a DL_NOTE_REPLUMB
15907 				 * notification. In that case, connp is NULL.
15908 				 */
15909 				if (connp != NULL)
15910 					q = CONNP_TO_WQ(connp);
15911 
15912 				(void) ipif_down(ipif, NULL, NULL);
15913 				/* error is set below the switch */
15914 			}
15915 			break;
15916 		case DL_ENABMULTI_REQ:
15917 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15918 
15919 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15920 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15921 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15922 				ipif_t *ipif;
15923 
15924 				printf("ip: joining multicasts failed (%d)"
15925 				    " on %s - will use link layer "
15926 				    "broadcasts for multicast\n",
15927 				    dlea->dl_errno, ill->ill_name);
15928 
15929 				/*
15930 				 * Set up the multicast mapping alone.
15931 				 * writer, so ok to access ill->ill_ipif
15932 				 * without any lock.
15933 				 */
15934 				ipif = ill->ill_ipif;
15935 				mutex_enter(&ill->ill_phyint->phyint_lock);
15936 				ill->ill_phyint->phyint_flags |=
15937 				    PHYI_MULTI_BCAST;
15938 				mutex_exit(&ill->ill_phyint->phyint_lock);
15939 
15940 				if (!ill->ill_isv6) {
15941 					(void) ipif_arp_setup_multicast(ipif,
15942 					    NULL);
15943 				} else {
15944 					(void) ipif_ndp_setup_multicast(ipif,
15945 					    NULL);
15946 				}
15947 			}
15948 			freemsg(mp);	/* Don't want to pass this up */
15949 			return;
15950 		case DL_CONTROL_REQ:
15951 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15952 			    "DL_CONTROL_REQ\n"));
15953 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15954 			freemsg(mp);
15955 			return;
15956 		case DL_CAPABILITY_REQ:
15957 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15958 			    "DL_CAPABILITY REQ\n"));
15959 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
15960 				ill->ill_dlpi_capab_state = IDCS_FAILED;
15961 			ill_capability_done(ill);
15962 			freemsg(mp);
15963 			return;
15964 		}
15965 		/*
15966 		 * Note the error for IOCTL completion (mp1 is set when
15967 		 * ready to complete ioctl). If ill_ifname_pending_err is
15968 		 * set, an error occured during plumbing (ill_ifname_pending),
15969 		 * so we want to report that error.
15970 		 *
15971 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15972 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15973 		 * expected to get errack'd if the driver doesn't support
15974 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15975 		 * if these error conditions are encountered.
15976 		 */
15977 		if (mp1 != NULL) {
15978 			if (ill->ill_ifname_pending_err != 0)  {
15979 				err = ill->ill_ifname_pending_err;
15980 				ill->ill_ifname_pending_err = 0;
15981 			} else {
15982 				err = dlea->dl_unix_errno ?
15983 				    dlea->dl_unix_errno : ENXIO;
15984 			}
15985 		/*
15986 		 * If we're plumbing an interface and an error hasn't already
15987 		 * been saved, set ill_ifname_pending_err to the error passed
15988 		 * up. Ignore the error if log is B_FALSE (see comment above).
15989 		 */
15990 		} else if (log && ill->ill_ifname_pending &&
15991 		    ill->ill_ifname_pending_err == 0) {
15992 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15993 			    dlea->dl_unix_errno : ENXIO;
15994 		}
15995 
15996 		if (log)
15997 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15998 			    dlea->dl_errno, dlea->dl_unix_errno);
15999 		break;
16000 	case DL_CAPABILITY_ACK:
16001 		ill_capability_ack(ill, mp);
16002 		/*
16003 		 * The message has been handed off to ill_capability_ack
16004 		 * and must not be freed below
16005 		 */
16006 		mp = NULL;
16007 		break;
16008 
16009 	case DL_CONTROL_ACK:
16010 		/* We treat all of these as "fire and forget" */
16011 		ill_dlpi_done(ill, DL_CONTROL_REQ);
16012 		break;
16013 	case DL_INFO_ACK:
16014 		/* Call a routine to handle this one. */
16015 		ill_dlpi_done(ill, DL_INFO_REQ);
16016 		ip_ll_subnet_defaults(ill, mp);
16017 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16018 		return;
16019 	case DL_BIND_ACK:
16020 		/*
16021 		 * We should have an IOCTL waiting on this unless
16022 		 * sent by ill_dl_phys, in which case just return
16023 		 */
16024 		ill_dlpi_done(ill, DL_BIND_REQ);
16025 		if (ill->ill_ifname_pending)
16026 			break;
16027 
16028 		if (!ioctl_aborted)
16029 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16030 		if (mp1 == NULL)
16031 			break;
16032 		/*
16033 		 * mp1 was added by ill_dl_up(). if that is a result of
16034 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
16035 		 */
16036 		if (connp != NULL)
16037 			q = CONNP_TO_WQ(connp);
16038 
16039 		/*
16040 		 * We are exclusive. So nothing can change even after
16041 		 * we get the pending mp. If need be we can put it back
16042 		 * and restart, as in calling ipif_arp_up()  below.
16043 		 */
16044 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16045 
16046 		mutex_enter(&ill->ill_lock);
16047 		ill->ill_dl_up = 1;
16048 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16049 		mutex_exit(&ill->ill_lock);
16050 
16051 		/*
16052 		 * Now bring up the resolver; when that is complete, we'll
16053 		 * create IREs.  Note that we intentionally mirror what
16054 		 * ipif_up() would have done, because we got here by way of
16055 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16056 		 */
16057 		if (ill->ill_isv6) {
16058 			if (ill->ill_flags & ILLF_XRESOLV) {
16059 				if (connp != NULL)
16060 					mutex_enter(&connp->conn_lock);
16061 				mutex_enter(&ill->ill_lock);
16062 				success = ipsq_pending_mp_add(connp, ipif, q,
16063 				    mp1, 0);
16064 				mutex_exit(&ill->ill_lock);
16065 				if (connp != NULL)
16066 					mutex_exit(&connp->conn_lock);
16067 				if (success) {
16068 					err = ipif_resolver_up(ipif,
16069 					    Res_act_initial);
16070 					if (err == EINPROGRESS) {
16071 						freemsg(mp);
16072 						return;
16073 					}
16074 					ASSERT(err != 0);
16075 					mp1 = ipsq_pending_mp_get(ipsq, &connp);
16076 					ASSERT(mp1 != NULL);
16077 				} else {
16078 					/* conn has started closing */
16079 					err = EINTR;
16080 				}
16081 			} else { /* Non XRESOLV interface */
16082 				(void) ipif_resolver_up(ipif, Res_act_initial);
16083 				if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
16084 					err = ipif_up_done_v6(ipif);
16085 			}
16086 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16087 			/*
16088 			 * ARP and other v4 external resolvers.
16089 			 * Leave the pending mblk intact so that
16090 			 * the ioctl completes in ip_rput().
16091 			 */
16092 			if (connp != NULL)
16093 				mutex_enter(&connp->conn_lock);
16094 			mutex_enter(&ill->ill_lock);
16095 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16096 			mutex_exit(&ill->ill_lock);
16097 			if (connp != NULL)
16098 				mutex_exit(&connp->conn_lock);
16099 			if (success) {
16100 				err = ipif_resolver_up(ipif, Res_act_initial);
16101 				if (err == EINPROGRESS) {
16102 					freemsg(mp);
16103 					return;
16104 				}
16105 				ASSERT(err != 0);
16106 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16107 			} else {
16108 				/* The conn has started closing */
16109 				err = EINTR;
16110 			}
16111 		} else {
16112 			/*
16113 			 * This one is complete. Reply to pending ioctl.
16114 			 */
16115 			(void) ipif_resolver_up(ipif, Res_act_initial);
16116 			err = ipif_up_done(ipif);
16117 		}
16118 
16119 		if ((err == 0) && (ill->ill_up_ipifs)) {
16120 			err = ill_up_ipifs(ill, q, mp1);
16121 			if (err == EINPROGRESS) {
16122 				freemsg(mp);
16123 				return;
16124 			}
16125 		}
16126 
16127 		/*
16128 		 * If we have a moved ipif to bring up, and everything has
16129 		 * succeeded to this point, bring it up on the IPMP ill.
16130 		 * Otherwise, leave it down -- the admin can try to bring it
16131 		 * up by hand if need be.
16132 		 */
16133 		if (ill->ill_move_ipif != NULL) {
16134 			if (err != 0) {
16135 				ill->ill_move_ipif = NULL;
16136 			} else {
16137 				ipif = ill->ill_move_ipif;
16138 				ill->ill_move_ipif = NULL;
16139 				err = ipif_up(ipif, q, mp1);
16140 				if (err == EINPROGRESS) {
16141 					freemsg(mp);
16142 					return;
16143 				}
16144 			}
16145 		}
16146 		break;
16147 
16148 	case DL_NOTIFY_IND: {
16149 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16150 		ire_t *ire;
16151 		uint_t orig_mtu;
16152 		boolean_t need_ire_walk_v4 = B_FALSE;
16153 		boolean_t need_ire_walk_v6 = B_FALSE;
16154 
16155 		switch (notify->dl_notification) {
16156 		case DL_NOTE_PHYS_ADDR:
16157 			err = ill_set_phys_addr(ill, mp);
16158 			break;
16159 
16160 		case DL_NOTE_REPLUMB:
16161 			/*
16162 			 * Directly return after calling ill_replumb().
16163 			 * Note that we should not free mp as it is reused
16164 			 * in the ill_replumb() function.
16165 			 */
16166 			err = ill_replumb(ill, mp);
16167 			return;
16168 
16169 		case DL_NOTE_FASTPATH_FLUSH:
16170 			ill_fastpath_flush(ill);
16171 			break;
16172 
16173 		case DL_NOTE_SDU_SIZE:
16174 			/*
16175 			 * Change the MTU size of the interface, of all
16176 			 * attached ipif's, and of all relevant ire's.  The
16177 			 * new value's a uint32_t at notify->dl_data.
16178 			 * Mtu change Vs. new ire creation - protocol below.
16179 			 *
16180 			 * a Mark the ipif as IPIF_CHANGING.
16181 			 * b Set the new mtu in the ipif.
16182 			 * c Change the ire_max_frag on all affected ires
16183 			 * d Unmark the IPIF_CHANGING
16184 			 *
16185 			 * To see how the protocol works, assume an interface
16186 			 * route is also being added simultaneously by
16187 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16188 			 * the ire. If the ire is created before step a,
16189 			 * it will be cleaned up by step c. If the ire is
16190 			 * created after step d, it will see the new value of
16191 			 * ipif_mtu. Any attempt to create the ire between
16192 			 * steps a to d will fail because of the IPIF_CHANGING
16193 			 * flag. Note that ire_create() is passed a pointer to
16194 			 * the ipif_mtu, and not the value. During ire_add
16195 			 * under the bucket lock, the ire_max_frag of the
16196 			 * new ire being created is set from the ipif/ire from
16197 			 * which it is being derived.
16198 			 */
16199 			mutex_enter(&ill->ill_lock);
16200 
16201 			orig_mtu = ill->ill_max_mtu;
16202 			ill->ill_max_frag = (uint_t)notify->dl_data;
16203 			ill->ill_max_mtu = (uint_t)notify->dl_data;
16204 
16205 			/*
16206 			 * If ill_user_mtu was set (via SIOCSLIFLNKINFO),
16207 			 * clamp ill_max_mtu at it.
16208 			 */
16209 			if (ill->ill_user_mtu != 0 &&
16210 			    ill->ill_user_mtu < ill->ill_max_mtu)
16211 				ill->ill_max_mtu = ill->ill_user_mtu;
16212 
16213 			/*
16214 			 * If the MTU is unchanged, we're done.
16215 			 */
16216 			if (orig_mtu == ill->ill_max_mtu) {
16217 				mutex_exit(&ill->ill_lock);
16218 				break;
16219 			}
16220 
16221 			if (ill->ill_isv6) {
16222 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16223 					ill->ill_max_mtu = IPV6_MIN_MTU;
16224 			} else {
16225 				if (ill->ill_max_mtu < IP_MIN_MTU)
16226 					ill->ill_max_mtu = IP_MIN_MTU;
16227 			}
16228 			for (ipif = ill->ill_ipif; ipif != NULL;
16229 			    ipif = ipif->ipif_next) {
16230 				/*
16231 				 * Don't override the mtu if the user
16232 				 * has explicitly set it.
16233 				 */
16234 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16235 					continue;
16236 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16237 				if (ipif->ipif_isv6)
16238 					ire = ipif_to_ire_v6(ipif);
16239 				else
16240 					ire = ipif_to_ire(ipif);
16241 				if (ire != NULL) {
16242 					ire->ire_max_frag = ipif->ipif_mtu;
16243 					ire_refrele(ire);
16244 				}
16245 				if (ipif->ipif_flags & IPIF_UP) {
16246 					if (ill->ill_isv6)
16247 						need_ire_walk_v6 = B_TRUE;
16248 					else
16249 						need_ire_walk_v4 = B_TRUE;
16250 				}
16251 			}
16252 			mutex_exit(&ill->ill_lock);
16253 			if (need_ire_walk_v4)
16254 				ire_walk_v4(ill_mtu_change, (char *)ill,
16255 				    ALL_ZONES, ipst);
16256 			if (need_ire_walk_v6)
16257 				ire_walk_v6(ill_mtu_change, (char *)ill,
16258 				    ALL_ZONES, ipst);
16259 
16260 			/*
16261 			 * Refresh IPMP meta-interface MTU if necessary.
16262 			 */
16263 			if (IS_UNDER_IPMP(ill))
16264 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
16265 			break;
16266 
16267 		case DL_NOTE_LINK_UP:
16268 		case DL_NOTE_LINK_DOWN: {
16269 			/*
16270 			 * We are writer. ill / phyint / ipsq assocs stable.
16271 			 * The RUNNING flag reflects the state of the link.
16272 			 */
16273 			phyint_t *phyint = ill->ill_phyint;
16274 			uint64_t new_phyint_flags;
16275 			boolean_t changed = B_FALSE;
16276 			boolean_t went_up;
16277 
16278 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16279 			mutex_enter(&phyint->phyint_lock);
16280 
16281 			new_phyint_flags = went_up ?
16282 			    phyint->phyint_flags | PHYI_RUNNING :
16283 			    phyint->phyint_flags & ~PHYI_RUNNING;
16284 
16285 			if (IS_IPMP(ill)) {
16286 				new_phyint_flags = went_up ?
16287 				    new_phyint_flags & ~PHYI_FAILED :
16288 				    new_phyint_flags | PHYI_FAILED;
16289 			}
16290 
16291 			if (new_phyint_flags != phyint->phyint_flags) {
16292 				phyint->phyint_flags = new_phyint_flags;
16293 				changed = B_TRUE;
16294 			}
16295 			mutex_exit(&phyint->phyint_lock);
16296 			/*
16297 			 * ill_restart_dad handles the DAD restart and routing
16298 			 * socket notification logic.
16299 			 */
16300 			if (changed) {
16301 				ill_restart_dad(phyint->phyint_illv4, went_up);
16302 				ill_restart_dad(phyint->phyint_illv6, went_up);
16303 			}
16304 			break;
16305 		}
16306 		case DL_NOTE_PROMISC_ON_PHYS:
16307 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16308 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16309 			mutex_enter(&ill->ill_lock);
16310 			ill->ill_promisc_on_phys = B_TRUE;
16311 			mutex_exit(&ill->ill_lock);
16312 			break;
16313 		case DL_NOTE_PROMISC_OFF_PHYS:
16314 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16315 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16316 			mutex_enter(&ill->ill_lock);
16317 			ill->ill_promisc_on_phys = B_FALSE;
16318 			mutex_exit(&ill->ill_lock);
16319 			break;
16320 		case DL_NOTE_CAPAB_RENEG:
16321 			/*
16322 			 * Something changed on the driver side.
16323 			 * It wants us to renegotiate the capabilities
16324 			 * on this ill. One possible cause is the aggregation
16325 			 * interface under us where a port got added or
16326 			 * went away.
16327 			 *
16328 			 * If the capability negotiation is already done
16329 			 * or is in progress, reset the capabilities and
16330 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16331 			 * so that when the ack comes back, we can start
16332 			 * the renegotiation process.
16333 			 *
16334 			 * Note that if ill_capab_reneg is already B_TRUE
16335 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16336 			 * the capability resetting request has been sent
16337 			 * and the renegotiation has not been started yet;
16338 			 * nothing needs to be done in this case.
16339 			 */
16340 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16341 			ill_capability_reset(ill, B_TRUE);
16342 			ipsq_current_finish(ipsq);
16343 			break;
16344 		default:
16345 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16346 			    "type 0x%x for DL_NOTIFY_IND\n",
16347 			    notify->dl_notification));
16348 			break;
16349 		}
16350 
16351 		/*
16352 		 * As this is an asynchronous operation, we
16353 		 * should not call ill_dlpi_done
16354 		 */
16355 		break;
16356 	}
16357 	case DL_NOTIFY_ACK: {
16358 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16359 
16360 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16361 			ill->ill_note_link = 1;
16362 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16363 		break;
16364 	}
16365 	case DL_PHYS_ADDR_ACK: {
16366 		/*
16367 		 * As part of plumbing the interface via SIOCSLIFNAME,
16368 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16369 		 * whose answers we receive here.  As each answer is received,
16370 		 * we call ill_dlpi_done() to dispatch the next request as
16371 		 * we're processing the current one.  Once all answers have
16372 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16373 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16374 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16375 		 * available, but we know the ioctl is pending on ill_wq.)
16376 		 */
16377 		uint_t	paddrlen, paddroff;
16378 
16379 		paddrreq = ill->ill_phys_addr_pend;
16380 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16381 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16382 
16383 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16384 		if (paddrreq == DL_IPV6_TOKEN) {
16385 			/*
16386 			 * bcopy to low-order bits of ill_token
16387 			 *
16388 			 * XXX Temporary hack - currently, all known tokens
16389 			 * are 64 bits, so I'll cheat for the moment.
16390 			 */
16391 			bcopy(mp->b_rptr + paddroff,
16392 			    &ill->ill_token.s6_addr32[2], paddrlen);
16393 			ill->ill_token_length = paddrlen;
16394 			break;
16395 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16396 			ASSERT(ill->ill_nd_lla_mp == NULL);
16397 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16398 			mp = NULL;
16399 			break;
16400 		}
16401 
16402 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16403 		ASSERT(ill->ill_phys_addr_mp == NULL);
16404 		if (!ill->ill_ifname_pending)
16405 			break;
16406 		ill->ill_ifname_pending = 0;
16407 		if (!ioctl_aborted)
16408 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16409 		if (mp1 != NULL) {
16410 			ASSERT(connp == NULL);
16411 			q = ill->ill_wq;
16412 		}
16413 		/*
16414 		 * If any error acks received during the plumbing sequence,
16415 		 * ill_ifname_pending_err will be set. Break out and send up
16416 		 * the error to the pending ioctl.
16417 		 */
16418 		if (ill->ill_ifname_pending_err != 0) {
16419 			err = ill->ill_ifname_pending_err;
16420 			ill->ill_ifname_pending_err = 0;
16421 			break;
16422 		}
16423 
16424 		ill->ill_phys_addr_mp = mp;
16425 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16426 		mp = NULL;
16427 
16428 		/*
16429 		 * If paddrlen is zero, the DLPI provider doesn't support
16430 		 * physical addresses.  The other two tests were historical
16431 		 * workarounds for bugs in our former PPP implementation, but
16432 		 * now other things have grown dependencies on them -- e.g.,
16433 		 * the tun module specifies a dl_addr_length of zero in its
16434 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16435 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16436 		 * but only after careful testing ensures that all dependent
16437 		 * broken DLPI providers have been fixed.
16438 		 */
16439 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16440 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16441 			ill->ill_phys_addr = NULL;
16442 		} else if (paddrlen != ill->ill_phys_addr_length) {
16443 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16444 			    paddrlen, ill->ill_phys_addr_length));
16445 			err = EINVAL;
16446 			break;
16447 		}
16448 
16449 		if (ill->ill_nd_lla_mp == NULL) {
16450 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16451 				err = ENOMEM;
16452 				break;
16453 			}
16454 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16455 		}
16456 
16457 		/*
16458 		 * Set the interface token.  If the zeroth interface address
16459 		 * is unspecified, then set it to the link local address.
16460 		 */
16461 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16462 			(void) ill_setdefaulttoken(ill);
16463 
16464 		ASSERT(ill->ill_ipif->ipif_id == 0);
16465 		if (ipif != NULL &&
16466 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16467 			(void) ipif_setlinklocal(ipif);
16468 		}
16469 		break;
16470 	}
16471 	case DL_OK_ACK:
16472 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16473 		    dl_primstr((int)dloa->dl_correct_primitive),
16474 		    dloa->dl_correct_primitive));
16475 		switch (dloa->dl_correct_primitive) {
16476 		case DL_ENABMULTI_REQ:
16477 		case DL_DISABMULTI_REQ:
16478 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16479 			break;
16480 		case DL_PROMISCON_REQ:
16481 		case DL_PROMISCOFF_REQ:
16482 		case DL_UNBIND_REQ:
16483 		case DL_ATTACH_REQ:
16484 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16485 			break;
16486 		}
16487 		break;
16488 	default:
16489 		break;
16490 	}
16491 
16492 	freemsg(mp);
16493 	if (mp1 == NULL)
16494 		return;
16495 
16496 	/*
16497 	 * The operation must complete without EINPROGRESS since
16498 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
16499 	 * the operation will be stuck forever inside the IPSQ.
16500 	 */
16501 	ASSERT(err != EINPROGRESS);
16502 
16503 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
16504 	case 0:
16505 		ipsq_current_finish(ipsq);
16506 		break;
16507 
16508 	case SIOCSLIFNAME:
16509 	case IF_UNITSEL: {
16510 		ill_t *ill_other = ILL_OTHER(ill);
16511 
16512 		/*
16513 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
16514 		 * ill has a peer which is in an IPMP group, then place ill
16515 		 * into the same group.  One catch: although ifconfig plumbs
16516 		 * the appropriate IPMP meta-interface prior to plumbing this
16517 		 * ill, it is possible for multiple ifconfig applications to
16518 		 * race (or for another application to adjust plumbing), in
16519 		 * which case the IPMP meta-interface we need will be missing.
16520 		 * If so, kick the phyint out of the group.
16521 		 */
16522 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
16523 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
16524 			ipmp_illgrp_t	*illg;
16525 
16526 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
16527 			if (illg == NULL)
16528 				ipmp_phyint_leave_grp(ill->ill_phyint);
16529 			else
16530 				ipmp_ill_join_illgrp(ill, illg);
16531 		}
16532 
16533 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
16534 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16535 		else
16536 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16537 		break;
16538 	}
16539 	case SIOCLIFADDIF:
16540 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16541 		break;
16542 
16543 	default:
16544 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16545 		break;
16546 	}
16547 }
16548 
16549 /*
16550  * ip_rput_other is called by ip_rput to handle messages modifying the global
16551  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16552  */
16553 /* ARGSUSED */
16554 void
16555 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16556 {
16557 	ill_t		*ill = q->q_ptr;
16558 	struct iocblk	*iocp;
16559 	mblk_t		*mp1;
16560 	conn_t		*connp = NULL;
16561 
16562 	ip1dbg(("ip_rput_other "));
16563 	if (ipsq != NULL) {
16564 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16565 		ASSERT(ipsq->ipsq_xop ==
16566 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
16567 	}
16568 
16569 	switch (mp->b_datap->db_type) {
16570 	case M_ERROR:
16571 	case M_HANGUP:
16572 		/*
16573 		 * The device has a problem.  We force the ILL down.  It can
16574 		 * be brought up again manually using SIOCSIFFLAGS (via
16575 		 * ifconfig or equivalent).
16576 		 */
16577 		ASSERT(ipsq != NULL);
16578 		if (mp->b_rptr < mp->b_wptr)
16579 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16580 		if (ill->ill_error == 0)
16581 			ill->ill_error = ENXIO;
16582 		if (!ill_down_start(q, mp))
16583 			return;
16584 		ipif_all_down_tail(ipsq, q, mp, NULL);
16585 		break;
16586 	case M_IOCACK:
16587 		iocp = (struct iocblk *)mp->b_rptr;
16588 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16589 		switch (iocp->ioc_cmd) {
16590 		case SIOCSTUNPARAM:
16591 		case OSIOCSTUNPARAM:
16592 			ASSERT(ipsq != NULL);
16593 			/*
16594 			 * Finish socket ioctl passed through to tun.
16595 			 * We should have an IOCTL waiting on this.
16596 			 */
16597 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16598 			if (ill->ill_isv6) {
16599 				struct iftun_req *ta;
16600 
16601 				/*
16602 				 * if a source or destination is
16603 				 * being set, try and set the link
16604 				 * local address for the tunnel
16605 				 */
16606 				ta = (struct iftun_req *)mp->b_cont->
16607 				    b_cont->b_rptr;
16608 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16609 					ipif_set_tun_llink(ill, ta);
16610 				}
16611 
16612 			}
16613 			if (mp1 != NULL) {
16614 				/*
16615 				 * Now copy back the b_next/b_prev used by
16616 				 * mi code for the mi_copy* functions.
16617 				 * See ip_sioctl_tunparam() for the reason.
16618 				 * Also protect against missing b_cont.
16619 				 */
16620 				if (mp->b_cont != NULL) {
16621 					mp->b_cont->b_next =
16622 					    mp1->b_cont->b_next;
16623 					mp->b_cont->b_prev =
16624 					    mp1->b_cont->b_prev;
16625 				}
16626 				inet_freemsg(mp1);
16627 				ASSERT(connp != NULL);
16628 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16629 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16630 			} else {
16631 				ASSERT(connp == NULL);
16632 				putnext(q, mp);
16633 			}
16634 			break;
16635 		case SIOCGTUNPARAM:
16636 		case OSIOCGTUNPARAM:
16637 			/*
16638 			 * This is really M_IOCDATA from the tunnel driver.
16639 			 * convert back and complete the ioctl.
16640 			 * We should have an IOCTL waiting on this.
16641 			 */
16642 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16643 			if (mp1) {
16644 				/*
16645 				 * Now copy back the b_next/b_prev used by
16646 				 * mi code for the mi_copy* functions.
16647 				 * See ip_sioctl_tunparam() for the reason.
16648 				 * Also protect against missing b_cont.
16649 				 */
16650 				if (mp->b_cont != NULL) {
16651 					mp->b_cont->b_next =
16652 					    mp1->b_cont->b_next;
16653 					mp->b_cont->b_prev =
16654 					    mp1->b_cont->b_prev;
16655 				}
16656 				inet_freemsg(mp1);
16657 				if (iocp->ioc_error == 0)
16658 					mp->b_datap->db_type = M_IOCDATA;
16659 				ASSERT(connp != NULL);
16660 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16661 				    iocp->ioc_error, COPYOUT, NULL);
16662 			} else {
16663 				ASSERT(connp == NULL);
16664 				putnext(q, mp);
16665 			}
16666 			break;
16667 		default:
16668 			break;
16669 		}
16670 		break;
16671 	case M_IOCNAK:
16672 		iocp = (struct iocblk *)mp->b_rptr;
16673 
16674 		switch (iocp->ioc_cmd) {
16675 			int mode;
16676 
16677 		case DL_IOC_HDR_INFO:
16678 			/*
16679 			 * If this was the first attempt, turn off the
16680 			 * fastpath probing.
16681 			 */
16682 			mutex_enter(&ill->ill_lock);
16683 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16684 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16685 				mutex_exit(&ill->ill_lock);
16686 				ill_fastpath_nack(ill);
16687 				ip1dbg(("ip_rput: DLPI fastpath off on "
16688 				    "interface %s\n",
16689 				    ill->ill_name));
16690 			} else {
16691 				mutex_exit(&ill->ill_lock);
16692 			}
16693 			freemsg(mp);
16694 			break;
16695 			case SIOCSTUNPARAM:
16696 		case OSIOCSTUNPARAM:
16697 			ASSERT(ipsq != NULL);
16698 			/*
16699 			 * Finish socket ioctl passed through to tun
16700 			 * We should have an IOCTL waiting on this.
16701 			 */
16702 			/* FALLTHRU */
16703 		case SIOCGTUNPARAM:
16704 		case OSIOCGTUNPARAM:
16705 			/*
16706 			 * This is really M_IOCDATA from the tunnel driver.
16707 			 * convert back and complete the ioctl.
16708 			 * We should have an IOCTL waiting on this.
16709 			 */
16710 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16711 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16712 				mp1 = ill_pending_mp_get(ill, &connp,
16713 				    iocp->ioc_id);
16714 				mode = COPYOUT;
16715 				ipsq = NULL;
16716 			} else {
16717 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16718 				mode = NO_COPYOUT;
16719 			}
16720 			if (mp1 != NULL) {
16721 				/*
16722 				 * Now copy back the b_next/b_prev used by
16723 				 * mi code for the mi_copy* functions.
16724 				 * See ip_sioctl_tunparam() for the reason.
16725 				 * Also protect against missing b_cont.
16726 				 */
16727 				if (mp->b_cont != NULL) {
16728 					mp->b_cont->b_next =
16729 					    mp1->b_cont->b_next;
16730 					mp->b_cont->b_prev =
16731 					    mp1->b_cont->b_prev;
16732 				}
16733 				inet_freemsg(mp1);
16734 				if (iocp->ioc_error == 0)
16735 					iocp->ioc_error = EINVAL;
16736 				ASSERT(connp != NULL);
16737 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16738 				    iocp->ioc_error, mode, ipsq);
16739 			} else {
16740 				ASSERT(connp == NULL);
16741 				putnext(q, mp);
16742 			}
16743 			break;
16744 		default:
16745 			break;
16746 		}
16747 	default:
16748 		break;
16749 	}
16750 }
16751 
16752 /*
16753  * NOTE : This function does not ire_refrele the ire argument passed in.
16754  *
16755  * IPQoS notes
16756  * IP policy is invoked twice for a forwarded packet, once on the read side
16757  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16758  * enabled. An additional parameter, in_ill, has been added for this purpose.
16759  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16760  * because ip_mroute drops this information.
16761  *
16762  */
16763 void
16764 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16765 {
16766 	uint32_t	old_pkt_len;
16767 	uint32_t	pkt_len;
16768 	queue_t	*q;
16769 	uint32_t	sum;
16770 #define	rptr	((uchar_t *)ipha)
16771 	uint32_t	max_frag;
16772 	uint32_t	ill_index;
16773 	ill_t		*out_ill;
16774 	mib2_ipIfStatsEntry_t *mibptr;
16775 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16776 
16777 	/* Get the ill_index of the incoming ILL */
16778 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16779 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16780 
16781 	/* Initiate Read side IPPF processing */
16782 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16783 		ip_process(IPP_FWD_IN, &mp, ill_index);
16784 		if (mp == NULL) {
16785 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16786 			    "during IPPF processing\n"));
16787 			return;
16788 		}
16789 	}
16790 
16791 	/* Adjust the checksum to reflect the ttl decrement. */
16792 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16793 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16794 
16795 	if (ipha->ipha_ttl-- <= 1) {
16796 		if (ip_csum_hdr(ipha)) {
16797 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16798 			goto drop_pkt;
16799 		}
16800 		/*
16801 		 * Note: ire_stq this will be NULL for multicast
16802 		 * datagrams using the long path through arp (the IRE
16803 		 * is not an IRE_CACHE). This should not cause
16804 		 * problems since we don't generate ICMP errors for
16805 		 * multicast packets.
16806 		 */
16807 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16808 		q = ire->ire_stq;
16809 		if (q != NULL) {
16810 			/* Sent by forwarding path, and router is global zone */
16811 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16812 			    GLOBAL_ZONEID, ipst);
16813 		} else
16814 			freemsg(mp);
16815 		return;
16816 	}
16817 
16818 	/*
16819 	 * Don't forward if the interface is down
16820 	 */
16821 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16822 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16823 		ip2dbg(("ip_rput_forward:interface is down\n"));
16824 		goto drop_pkt;
16825 	}
16826 
16827 	/* Get the ill_index of the outgoing ILL */
16828 	out_ill = ire_to_ill(ire);
16829 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16830 
16831 	DTRACE_PROBE4(ip4__forwarding__start,
16832 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16833 
16834 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16835 	    ipst->ips_ipv4firewall_forwarding,
16836 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16837 
16838 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16839 
16840 	if (mp == NULL)
16841 		return;
16842 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16843 
16844 	if (is_system_labeled()) {
16845 		mblk_t *mp1;
16846 
16847 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16848 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16849 			goto drop_pkt;
16850 		}
16851 		/* Size may have changed */
16852 		mp = mp1;
16853 		ipha = (ipha_t *)mp->b_rptr;
16854 		pkt_len = ntohs(ipha->ipha_length);
16855 	}
16856 
16857 	/* Check if there are options to update */
16858 	if (!IS_SIMPLE_IPH(ipha)) {
16859 		if (ip_csum_hdr(ipha)) {
16860 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16861 			goto drop_pkt;
16862 		}
16863 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16864 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16865 			return;
16866 		}
16867 
16868 		ipha->ipha_hdr_checksum = 0;
16869 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16870 	}
16871 	max_frag = ire->ire_max_frag;
16872 	if (pkt_len > max_frag) {
16873 		/*
16874 		 * It needs fragging on its way out.  We haven't
16875 		 * verified the header checksum yet.  Since we
16876 		 * are going to put a surely good checksum in the
16877 		 * outgoing header, we have to make sure that it
16878 		 * was good coming in.
16879 		 */
16880 		if (ip_csum_hdr(ipha)) {
16881 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16882 			goto drop_pkt;
16883 		}
16884 		/* Initiate Write side IPPF processing */
16885 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16886 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16887 			if (mp == NULL) {
16888 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16889 				    " during IPPF processing\n"));
16890 				return;
16891 			}
16892 		}
16893 		/*
16894 		 * Handle labeled packet resizing.
16895 		 *
16896 		 * If we have added a label, inform ip_wput_frag() of its
16897 		 * effect on the MTU for ICMP messages.
16898 		 */
16899 		if (pkt_len > old_pkt_len) {
16900 			uint32_t secopt_size;
16901 
16902 			secopt_size = pkt_len - old_pkt_len;
16903 			if (secopt_size < max_frag)
16904 				max_frag -= secopt_size;
16905 		}
16906 
16907 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16908 		    GLOBAL_ZONEID, ipst, NULL);
16909 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16910 		return;
16911 	}
16912 
16913 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16914 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16915 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16916 	    ipst->ips_ipv4firewall_physical_out,
16917 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16918 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16919 	if (mp == NULL)
16920 		return;
16921 
16922 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16923 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16924 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16925 	/* ip_xmit_v4 always consumes the packet */
16926 	return;
16927 
16928 drop_pkt:;
16929 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16930 	freemsg(mp);
16931 #undef	rptr
16932 }
16933 
16934 void
16935 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16936 {
16937 	ire_t	*ire;
16938 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16939 
16940 	ASSERT(!ipif->ipif_isv6);
16941 	/*
16942 	 * Find an IRE which matches the destination and the outgoing
16943 	 * queue in the cache table. All we need is an IRE_CACHE which
16944 	 * is pointing at ipif->ipif_ill.
16945 	 */
16946 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16947 		dst = ipif->ipif_pp_dst_addr;
16948 
16949 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, msg_getlabel(mp),
16950 	    MATCH_IRE_ILL | MATCH_IRE_SECATTR, ipst);
16951 	if (ire == NULL) {
16952 		/*
16953 		 * Mark this packet to make it be delivered to
16954 		 * ip_rput_forward after the new ire has been
16955 		 * created.
16956 		 */
16957 		mp->b_prev = NULL;
16958 		mp->b_next = mp;
16959 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16960 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16961 	} else {
16962 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16963 		IRE_REFRELE(ire);
16964 	}
16965 }
16966 
16967 /* Update any source route, record route or timestamp options */
16968 static int
16969 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16970 {
16971 	ipoptp_t	opts;
16972 	uchar_t		*opt;
16973 	uint8_t		optval;
16974 	uint8_t		optlen;
16975 	ipaddr_t	dst;
16976 	uint32_t	ts;
16977 	ire_t		*dst_ire = NULL;
16978 	ire_t		*tmp_ire = NULL;
16979 	timestruc_t	now;
16980 
16981 	ip2dbg(("ip_rput_forward_options\n"));
16982 	dst = ipha->ipha_dst;
16983 	for (optval = ipoptp_first(&opts, ipha);
16984 	    optval != IPOPT_EOL;
16985 	    optval = ipoptp_next(&opts)) {
16986 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16987 		opt = opts.ipoptp_cur;
16988 		optlen = opts.ipoptp_len;
16989 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16990 		    optval, opts.ipoptp_len));
16991 		switch (optval) {
16992 			uint32_t off;
16993 		case IPOPT_SSRR:
16994 		case IPOPT_LSRR:
16995 			/* Check if adminstratively disabled */
16996 			if (!ipst->ips_ip_forward_src_routed) {
16997 				if (ire->ire_stq != NULL) {
16998 					/*
16999 					 * Sent by forwarding path, and router
17000 					 * is global zone
17001 					 */
17002 					icmp_unreachable(ire->ire_stq, mp,
17003 					    ICMP_SOURCE_ROUTE_FAILED,
17004 					    GLOBAL_ZONEID, ipst);
17005 				} else {
17006 					ip0dbg(("ip_rput_forward_options: "
17007 					    "unable to send unreach\n"));
17008 					freemsg(mp);
17009 				}
17010 				return (-1);
17011 			}
17012 
17013 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17014 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17015 			if (dst_ire == NULL) {
17016 				/*
17017 				 * Must be partial since ip_rput_options
17018 				 * checked for strict.
17019 				 */
17020 				break;
17021 			}
17022 			off = opt[IPOPT_OFFSET];
17023 			off--;
17024 		redo_srr:
17025 			if (optlen < IP_ADDR_LEN ||
17026 			    off > optlen - IP_ADDR_LEN) {
17027 				/* End of source route */
17028 				ip1dbg((
17029 				    "ip_rput_forward_options: end of SR\n"));
17030 				ire_refrele(dst_ire);
17031 				break;
17032 			}
17033 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17034 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17035 			    IP_ADDR_LEN);
17036 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17037 			    ntohl(dst)));
17038 
17039 			/*
17040 			 * Check if our address is present more than
17041 			 * once as consecutive hops in source route.
17042 			 */
17043 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17044 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17045 			if (tmp_ire != NULL) {
17046 				ire_refrele(tmp_ire);
17047 				off += IP_ADDR_LEN;
17048 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17049 				goto redo_srr;
17050 			}
17051 			ipha->ipha_dst = dst;
17052 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17053 			ire_refrele(dst_ire);
17054 			break;
17055 		case IPOPT_RR:
17056 			off = opt[IPOPT_OFFSET];
17057 			off--;
17058 			if (optlen < IP_ADDR_LEN ||
17059 			    off > optlen - IP_ADDR_LEN) {
17060 				/* No more room - ignore */
17061 				ip1dbg((
17062 				    "ip_rput_forward_options: end of RR\n"));
17063 				break;
17064 			}
17065 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17066 			    IP_ADDR_LEN);
17067 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17068 			break;
17069 		case IPOPT_TS:
17070 			/* Insert timestamp if there is room */
17071 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17072 			case IPOPT_TS_TSONLY:
17073 				off = IPOPT_TS_TIMELEN;
17074 				break;
17075 			case IPOPT_TS_PRESPEC:
17076 			case IPOPT_TS_PRESPEC_RFC791:
17077 				/* Verify that the address matched */
17078 				off = opt[IPOPT_OFFSET] - 1;
17079 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17080 				dst_ire = ire_ctable_lookup(dst, 0,
17081 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17082 				    MATCH_IRE_TYPE, ipst);
17083 				if (dst_ire == NULL) {
17084 					/* Not for us */
17085 					break;
17086 				}
17087 				ire_refrele(dst_ire);
17088 				/* FALLTHRU */
17089 			case IPOPT_TS_TSANDADDR:
17090 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17091 				break;
17092 			default:
17093 				/*
17094 				 * ip_*put_options should have already
17095 				 * dropped this packet.
17096 				 */
17097 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17098 				    "unknown IT - bug in ip_rput_options?\n");
17099 				return (0);	/* Keep "lint" happy */
17100 			}
17101 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17102 				/* Increase overflow counter */
17103 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17104 				opt[IPOPT_POS_OV_FLG] =
17105 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17106 				    (off << 4));
17107 				break;
17108 			}
17109 			off = opt[IPOPT_OFFSET] - 1;
17110 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17111 			case IPOPT_TS_PRESPEC:
17112 			case IPOPT_TS_PRESPEC_RFC791:
17113 			case IPOPT_TS_TSANDADDR:
17114 				bcopy(&ire->ire_src_addr,
17115 				    (char *)opt + off, IP_ADDR_LEN);
17116 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17117 				/* FALLTHRU */
17118 			case IPOPT_TS_TSONLY:
17119 				off = opt[IPOPT_OFFSET] - 1;
17120 				/* Compute # of milliseconds since midnight */
17121 				gethrestime(&now);
17122 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17123 				    now.tv_nsec / (NANOSEC / MILLISEC);
17124 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17125 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17126 				break;
17127 			}
17128 			break;
17129 		}
17130 	}
17131 	return (0);
17132 }
17133 
17134 /*
17135  * This is called after processing at least one of AH/ESP headers.
17136  *
17137  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17138  * the actual, physical interface on which the packet was received,
17139  * but, when ip_strict_dst_multihoming is set to 1, could be the
17140  * interface which had the ipha_dst configured when the packet went
17141  * through ip_rput. The ill_index corresponding to the recv_ill
17142  * is saved in ipsec_in_rill_index
17143  *
17144  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17145  * cannot assume "ire" points to valid data for any IPv6 cases.
17146  */
17147 void
17148 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17149 {
17150 	mblk_t *mp;
17151 	ipaddr_t dst;
17152 	in6_addr_t *v6dstp;
17153 	ipha_t *ipha;
17154 	ip6_t *ip6h;
17155 	ipsec_in_t *ii;
17156 	boolean_t ill_need_rele = B_FALSE;
17157 	boolean_t rill_need_rele = B_FALSE;
17158 	boolean_t ire_need_rele = B_FALSE;
17159 	netstack_t	*ns;
17160 	ip_stack_t	*ipst;
17161 
17162 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17163 	ASSERT(ii->ipsec_in_ill_index != 0);
17164 	ns = ii->ipsec_in_ns;
17165 	ASSERT(ii->ipsec_in_ns != NULL);
17166 	ipst = ns->netstack_ip;
17167 
17168 	mp = ipsec_mp->b_cont;
17169 	ASSERT(mp != NULL);
17170 
17171 	if (ill == NULL) {
17172 		ASSERT(recv_ill == NULL);
17173 		/*
17174 		 * We need to get the original queue on which ip_rput_local
17175 		 * or ip_rput_data_v6 was called.
17176 		 */
17177 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17178 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17179 		ill_need_rele = B_TRUE;
17180 
17181 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17182 			recv_ill = ill_lookup_on_ifindex(
17183 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17184 			    NULL, NULL, NULL, NULL, ipst);
17185 			rill_need_rele = B_TRUE;
17186 		} else {
17187 			recv_ill = ill;
17188 		}
17189 
17190 		if ((ill == NULL) || (recv_ill == NULL)) {
17191 			ip0dbg(("ip_fanout_proto_again: interface "
17192 			    "disappeared\n"));
17193 			if (ill != NULL)
17194 				ill_refrele(ill);
17195 			if (recv_ill != NULL)
17196 				ill_refrele(recv_ill);
17197 			freemsg(ipsec_mp);
17198 			return;
17199 		}
17200 	}
17201 
17202 	ASSERT(ill != NULL && recv_ill != NULL);
17203 
17204 	if (mp->b_datap->db_type == M_CTL) {
17205 		/*
17206 		 * AH/ESP is returning the ICMP message after
17207 		 * removing their headers. Fanout again till
17208 		 * it gets to the right protocol.
17209 		 */
17210 		if (ii->ipsec_in_v4) {
17211 			icmph_t *icmph;
17212 			int iph_hdr_length;
17213 			int hdr_length;
17214 
17215 			ipha = (ipha_t *)mp->b_rptr;
17216 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17217 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17218 			ipha = (ipha_t *)&icmph[1];
17219 			hdr_length = IPH_HDR_LENGTH(ipha);
17220 			/*
17221 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17222 			 * Reset the type to M_DATA.
17223 			 */
17224 			mp->b_datap->db_type = M_DATA;
17225 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17226 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17227 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17228 		} else {
17229 			icmp6_t *icmp6;
17230 			int hdr_length;
17231 
17232 			ip6h = (ip6_t *)mp->b_rptr;
17233 			/* Don't call hdr_length_v6() unless you have to. */
17234 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17235 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17236 			else
17237 				hdr_length = IPV6_HDR_LEN;
17238 
17239 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17240 			/*
17241 			 * icmp_inbound_error_fanout_v6 may need to do
17242 			 * pullupmsg.  Reset the type to M_DATA.
17243 			 */
17244 			mp->b_datap->db_type = M_DATA;
17245 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17246 			    ip6h, icmp6, ill, recv_ill, B_TRUE,
17247 			    ii->ipsec_in_zoneid);
17248 		}
17249 		if (ill_need_rele)
17250 			ill_refrele(ill);
17251 		if (rill_need_rele)
17252 			ill_refrele(recv_ill);
17253 		return;
17254 	}
17255 
17256 	if (ii->ipsec_in_v4) {
17257 		ipha = (ipha_t *)mp->b_rptr;
17258 		dst = ipha->ipha_dst;
17259 		if (CLASSD(dst)) {
17260 			/*
17261 			 * Multicast has to be delivered to all streams.
17262 			 */
17263 			dst = INADDR_BROADCAST;
17264 		}
17265 
17266 		if (ire == NULL) {
17267 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17268 			    msg_getlabel(mp), ipst);
17269 			if (ire == NULL) {
17270 				if (ill_need_rele)
17271 					ill_refrele(ill);
17272 				if (rill_need_rele)
17273 					ill_refrele(recv_ill);
17274 				ip1dbg(("ip_fanout_proto_again: "
17275 				    "IRE not found"));
17276 				freemsg(ipsec_mp);
17277 				return;
17278 			}
17279 			ire_need_rele = B_TRUE;
17280 		}
17281 
17282 		switch (ipha->ipha_protocol) {
17283 		case IPPROTO_UDP:
17284 			ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17285 			    recv_ill);
17286 			if (ire_need_rele)
17287 				ire_refrele(ire);
17288 			break;
17289 		case IPPROTO_TCP:
17290 			if (!ire_need_rele)
17291 				IRE_REFHOLD(ire);
17292 			mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17293 			    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17294 			IRE_REFRELE(ire);
17295 			if (mp != NULL) {
17296 				SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17297 				    mp, 1, SQ_PROCESS,
17298 				    SQTAG_IP_PROTO_AGAIN);
17299 			}
17300 			break;
17301 		case IPPROTO_SCTP:
17302 			if (!ire_need_rele)
17303 				IRE_REFHOLD(ire);
17304 			ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17305 			    ipsec_mp, 0, ill->ill_rq, dst);
17306 			break;
17307 		default:
17308 			ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17309 			    recv_ill, 0);
17310 			if (ire_need_rele)
17311 				ire_refrele(ire);
17312 			break;
17313 		}
17314 	} else {
17315 		uint32_t rput_flags = 0;
17316 
17317 		ip6h = (ip6_t *)mp->b_rptr;
17318 		v6dstp = &ip6h->ip6_dst;
17319 		/*
17320 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17321 		 * address.
17322 		 *
17323 		 * Currently, we don't store that state in the IPSEC_IN
17324 		 * message, and we may need to.
17325 		 */
17326 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17327 		    IP6_IN_LLMCAST : 0);
17328 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17329 		    NULL, NULL);
17330 	}
17331 	if (ill_need_rele)
17332 		ill_refrele(ill);
17333 	if (rill_need_rele)
17334 		ill_refrele(recv_ill);
17335 }
17336 
17337 /*
17338  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17339  * returns 'true' if there are still fragments left on the queue, in
17340  * which case we restart the timer.
17341  */
17342 void
17343 ill_frag_timer(void *arg)
17344 {
17345 	ill_t	*ill = (ill_t *)arg;
17346 	boolean_t frag_pending;
17347 	ip_stack_t	*ipst = ill->ill_ipst;
17348 	time_t	timeout;
17349 
17350 	mutex_enter(&ill->ill_lock);
17351 	ASSERT(!ill->ill_fragtimer_executing);
17352 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17353 		ill->ill_frag_timer_id = 0;
17354 		mutex_exit(&ill->ill_lock);
17355 		return;
17356 	}
17357 	ill->ill_fragtimer_executing = 1;
17358 	mutex_exit(&ill->ill_lock);
17359 
17360 	if (ill->ill_isv6)
17361 		timeout = ipst->ips_ipv6_frag_timeout;
17362 	else
17363 		timeout = ipst->ips_ip_g_frag_timeout;
17364 
17365 	frag_pending = ill_frag_timeout(ill, timeout);
17366 
17367 	/*
17368 	 * Restart the timer, if we have fragments pending or if someone
17369 	 * wanted us to be scheduled again.
17370 	 */
17371 	mutex_enter(&ill->ill_lock);
17372 	ill->ill_fragtimer_executing = 0;
17373 	ill->ill_frag_timer_id = 0;
17374 	if (frag_pending || ill->ill_fragtimer_needrestart)
17375 		ill_frag_timer_start(ill);
17376 	mutex_exit(&ill->ill_lock);
17377 }
17378 
17379 void
17380 ill_frag_timer_start(ill_t *ill)
17381 {
17382 	ip_stack_t	*ipst = ill->ill_ipst;
17383 	clock_t	timeo_ms;
17384 
17385 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17386 
17387 	/* If the ill is closing or opening don't proceed */
17388 	if (ill->ill_state_flags & ILL_CONDEMNED)
17389 		return;
17390 
17391 	if (ill->ill_fragtimer_executing) {
17392 		/*
17393 		 * ill_frag_timer is currently executing. Just record the
17394 		 * the fact that we want the timer to be restarted.
17395 		 * ill_frag_timer will post a timeout before it returns,
17396 		 * ensuring it will be called again.
17397 		 */
17398 		ill->ill_fragtimer_needrestart = 1;
17399 		return;
17400 	}
17401 
17402 	if (ill->ill_frag_timer_id == 0) {
17403 		if (ill->ill_isv6)
17404 			timeo_ms = ipst->ips_ipv6_frag_timo_ms;
17405 		else
17406 			timeo_ms = ipst->ips_ip_g_frag_timo_ms;
17407 		/*
17408 		 * The timer is neither running nor is the timeout handler
17409 		 * executing. Post a timeout so that ill_frag_timer will be
17410 		 * called
17411 		 */
17412 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17413 		    MSEC_TO_TICK(timeo_ms >> 1));
17414 		ill->ill_fragtimer_needrestart = 0;
17415 	}
17416 }
17417 
17418 /*
17419  * This routine is needed for loopback when forwarding multicasts.
17420  *
17421  * IPQoS Notes:
17422  * IPPF processing is done in fanout routines.
17423  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17424  * processing for IPsec packets is done when it comes back in clear.
17425  * NOTE : The callers of this function need to do the ire_refrele for the
17426  *	  ire that is being passed in.
17427  */
17428 void
17429 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17430     ill_t *recv_ill, uint32_t esp_udp_ports)
17431 {
17432 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17433 	ill_t	*ill = (ill_t *)q->q_ptr;
17434 	uint32_t	sum;
17435 	uint32_t	u1;
17436 	uint32_t	u2;
17437 	int		hdr_length;
17438 	boolean_t	mctl_present;
17439 	mblk_t		*first_mp = mp;
17440 	mblk_t		*hada_mp = NULL;
17441 	ipha_t		*inner_ipha;
17442 	ip_stack_t	*ipst;
17443 
17444 	ASSERT(recv_ill != NULL);
17445 	ipst = recv_ill->ill_ipst;
17446 
17447 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17448 	    "ip_rput_locl_start: q %p", q);
17449 
17450 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17451 	ASSERT(ill != NULL);
17452 
17453 #define	rptr	((uchar_t *)ipha)
17454 #define	iphs	((uint16_t *)ipha)
17455 
17456 	/*
17457 	 * no UDP or TCP packet should come here anymore.
17458 	 */
17459 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17460 	    ipha->ipha_protocol != IPPROTO_UDP);
17461 
17462 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17463 	if (mctl_present &&
17464 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17465 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17466 
17467 		/*
17468 		 * It's an IPsec accelerated packet.
17469 		 * Keep a pointer to the data attributes around until
17470 		 * we allocate the ipsec_info_t.
17471 		 */
17472 		IPSECHW_DEBUG(IPSECHW_PKT,
17473 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17474 		hada_mp = first_mp;
17475 		hada_mp->b_cont = NULL;
17476 		/*
17477 		 * Since it is accelerated, it comes directly from
17478 		 * the ill and the data attributes is followed by
17479 		 * the packet data.
17480 		 */
17481 		ASSERT(mp->b_datap->db_type != M_CTL);
17482 		first_mp = mp;
17483 		mctl_present = B_FALSE;
17484 	}
17485 
17486 	/*
17487 	 * IF M_CTL is not present, then ipsec_in_is_secure
17488 	 * should return B_TRUE. There is a case where loopback
17489 	 * packets has an M_CTL in the front with all the
17490 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17491 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17492 	 * packets never comes here, it is safe to ASSERT the
17493 	 * following.
17494 	 */
17495 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17496 
17497 	/*
17498 	 * Also, we should never have an mctl_present if this is an
17499 	 * ESP-in-UDP packet.
17500 	 */
17501 	ASSERT(!mctl_present || !esp_in_udp_packet);
17502 
17503 	/* u1 is # words of IP options */
17504 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17505 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17506 
17507 	/*
17508 	 * Don't verify header checksum if we just removed UDP header or
17509 	 * packet is coming back from AH/ESP.
17510 	 */
17511 	if (!esp_in_udp_packet && !mctl_present) {
17512 		if (u1) {
17513 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17514 				if (hada_mp != NULL)
17515 					freemsg(hada_mp);
17516 				return;
17517 			}
17518 		} else {
17519 			/* Check the IP header checksum.  */
17520 #define	uph	((uint16_t *)ipha)
17521 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17522 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17523 #undef  uph
17524 			/* finish doing IP checksum */
17525 			sum = (sum & 0xFFFF) + (sum >> 16);
17526 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17527 			if (sum && sum != 0xFFFF) {
17528 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17529 				goto drop_pkt;
17530 			}
17531 		}
17532 	}
17533 
17534 	/*
17535 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17536 	 * might be called more than once for secure packets, count only
17537 	 * the first time.
17538 	 */
17539 	if (!mctl_present) {
17540 		UPDATE_IB_PKT_COUNT(ire);
17541 		ire->ire_last_used_time = lbolt;
17542 	}
17543 
17544 	/* Check for fragmentation offset. */
17545 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17546 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17547 	if (u1) {
17548 		/*
17549 		 * We re-assemble fragments before we do the AH/ESP
17550 		 * processing. Thus, M_CTL should not be present
17551 		 * while we are re-assembling.
17552 		 */
17553 		ASSERT(!mctl_present);
17554 		ASSERT(first_mp == mp);
17555 		if (!ip_rput_fragment(ill, recv_ill, &mp, ipha, NULL, NULL))
17556 			return;
17557 
17558 		/*
17559 		 * Make sure that first_mp points back to mp as
17560 		 * the mp we came in with could have changed in
17561 		 * ip_rput_fragment().
17562 		 */
17563 		ipha = (ipha_t *)mp->b_rptr;
17564 		first_mp = mp;
17565 	}
17566 
17567 	/*
17568 	 * Clear hardware checksumming flag as it is currently only
17569 	 * used by TCP and UDP.
17570 	 */
17571 	DB_CKSUMFLAGS(mp) = 0;
17572 
17573 	/* Now we have a complete datagram, destined for this machine. */
17574 	u1 = IPH_HDR_LENGTH(ipha);
17575 	switch (ipha->ipha_protocol) {
17576 	case IPPROTO_ICMP: {
17577 		ire_t		*ire_zone;
17578 		ilm_t		*ilm;
17579 		mblk_t		*mp1;
17580 		zoneid_t	last_zoneid;
17581 		ilm_walker_t	ilw;
17582 
17583 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17584 			ASSERT(ire->ire_type == IRE_BROADCAST);
17585 
17586 			/*
17587 			 * In the multicast case, applications may have joined
17588 			 * the group from different zones, so we need to deliver
17589 			 * the packet to each of them. Loop through the
17590 			 * multicast memberships structures (ilm) on the receive
17591 			 * ill and send a copy of the packet up each matching
17592 			 * one. However, we don't do this for multicasts sent on
17593 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17594 			 * they must stay in the sender's zone.
17595 			 *
17596 			 * ilm_add_v6() ensures that ilms in the same zone are
17597 			 * contiguous in the ill_ilm list. We use this property
17598 			 * to avoid sending duplicates needed when two
17599 			 * applications in the same zone join the same group on
17600 			 * different logical interfaces: we ignore the ilm if
17601 			 * its zoneid is the same as the last matching one.
17602 			 * In addition, the sending of the packet for
17603 			 * ire_zoneid is delayed until all of the other ilms
17604 			 * have been exhausted.
17605 			 */
17606 			last_zoneid = -1;
17607 			ilm = ilm_walker_start(&ilw, recv_ill);
17608 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
17609 				if (ipha->ipha_dst != ilm->ilm_addr ||
17610 				    ilm->ilm_zoneid == last_zoneid ||
17611 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17612 				    ilm->ilm_zoneid == ALL_ZONES ||
17613 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17614 					continue;
17615 				mp1 = ip_copymsg(first_mp);
17616 				if (mp1 == NULL)
17617 					continue;
17618 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
17619 				    0, sum, mctl_present, B_TRUE,
17620 				    recv_ill, ilm->ilm_zoneid);
17621 				last_zoneid = ilm->ilm_zoneid;
17622 			}
17623 			ilm_walker_finish(&ilw);
17624 		} else if (ire->ire_type == IRE_BROADCAST) {
17625 			/*
17626 			 * In the broadcast case, there may be many zones
17627 			 * which need a copy of the packet delivered to them.
17628 			 * There is one IRE_BROADCAST per broadcast address
17629 			 * and per zone; we walk those using a helper function.
17630 			 * In addition, the sending of the packet for ire is
17631 			 * delayed until all of the other ires have been
17632 			 * processed.
17633 			 */
17634 			IRB_REFHOLD(ire->ire_bucket);
17635 			ire_zone = NULL;
17636 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17637 			    ire)) != NULL) {
17638 				mp1 = ip_copymsg(first_mp);
17639 				if (mp1 == NULL)
17640 					continue;
17641 
17642 				UPDATE_IB_PKT_COUNT(ire_zone);
17643 				ire_zone->ire_last_used_time = lbolt;
17644 				icmp_inbound(q, mp1, B_TRUE, ill,
17645 				    0, sum, mctl_present, B_TRUE,
17646 				    recv_ill, ire_zone->ire_zoneid);
17647 			}
17648 			IRB_REFRELE(ire->ire_bucket);
17649 		}
17650 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17651 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17652 		    ire->ire_zoneid);
17653 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17654 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17655 		return;
17656 	}
17657 	case IPPROTO_IGMP:
17658 		/*
17659 		 * If we are not willing to accept IGMP packets in clear,
17660 		 * then check with global policy.
17661 		 */
17662 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17663 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17664 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17665 			if (first_mp == NULL)
17666 				return;
17667 		}
17668 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17669 			freemsg(first_mp);
17670 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17671 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17672 			return;
17673 		}
17674 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17675 			/* Bad packet - discarded by igmp_input */
17676 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17677 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17678 			if (mctl_present)
17679 				freeb(first_mp);
17680 			return;
17681 		}
17682 		/*
17683 		 * igmp_input() may have returned the pulled up message.
17684 		 * So first_mp and ipha need to be reinitialized.
17685 		 */
17686 		ipha = (ipha_t *)mp->b_rptr;
17687 		if (mctl_present)
17688 			first_mp->b_cont = mp;
17689 		else
17690 			first_mp = mp;
17691 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17692 		    connf_head != NULL) {
17693 			/* No user-level listener for IGMP packets */
17694 			goto drop_pkt;
17695 		}
17696 		/* deliver to local raw users */
17697 		break;
17698 	case IPPROTO_PIM:
17699 		/*
17700 		 * If we are not willing to accept PIM packets in clear,
17701 		 * then check with global policy.
17702 		 */
17703 		if (ipst->ips_pim_accept_clear_messages == 0) {
17704 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17705 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17706 			if (first_mp == NULL)
17707 				return;
17708 		}
17709 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17710 			freemsg(first_mp);
17711 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17712 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17713 			return;
17714 		}
17715 		if (pim_input(q, mp, ill) != 0) {
17716 			/* Bad packet - discarded by pim_input */
17717 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17718 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17719 			if (mctl_present)
17720 				freeb(first_mp);
17721 			return;
17722 		}
17723 
17724 		/*
17725 		 * pim_input() may have pulled up the message so ipha needs to
17726 		 * be reinitialized.
17727 		 */
17728 		ipha = (ipha_t *)mp->b_rptr;
17729 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17730 		    connf_head != NULL) {
17731 			/* No user-level listener for PIM packets */
17732 			goto drop_pkt;
17733 		}
17734 		/* deliver to local raw users */
17735 		break;
17736 	case IPPROTO_ENCAP:
17737 		/*
17738 		 * Handle self-encapsulated packets (IP-in-IP where
17739 		 * the inner addresses == the outer addresses).
17740 		 */
17741 		hdr_length = IPH_HDR_LENGTH(ipha);
17742 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17743 		    mp->b_wptr) {
17744 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17745 			    sizeof (ipha_t) - mp->b_rptr)) {
17746 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17747 				freemsg(first_mp);
17748 				return;
17749 			}
17750 			ipha = (ipha_t *)mp->b_rptr;
17751 		}
17752 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17753 		/*
17754 		 * Check the sanity of the inner IP header.
17755 		 */
17756 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17757 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17758 			freemsg(first_mp);
17759 			return;
17760 		}
17761 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17762 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17763 			freemsg(first_mp);
17764 			return;
17765 		}
17766 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17767 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17768 			ipsec_in_t *ii;
17769 
17770 			/*
17771 			 * Self-encapsulated tunnel packet. Remove
17772 			 * the outer IP header and fanout again.
17773 			 * We also need to make sure that the inner
17774 			 * header is pulled up until options.
17775 			 */
17776 			mp->b_rptr = (uchar_t *)inner_ipha;
17777 			ipha = inner_ipha;
17778 			hdr_length = IPH_HDR_LENGTH(ipha);
17779 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17780 				if (!pullupmsg(mp, (uchar_t *)ipha +
17781 				    + hdr_length - mp->b_rptr)) {
17782 					freemsg(first_mp);
17783 					return;
17784 				}
17785 				ipha = (ipha_t *)mp->b_rptr;
17786 			}
17787 			if (hdr_length > sizeof (ipha_t)) {
17788 				/* We got options on the inner packet. */
17789 				ipaddr_t dst = ipha->ipha_dst;
17790 
17791 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17792 				    -1) {
17793 					/* Bad options! */
17794 					return;
17795 				}
17796 				if (dst != ipha->ipha_dst) {
17797 					/*
17798 					 * Someone put a source-route in
17799 					 * the inside header of a self-
17800 					 * encapsulated packet.  Drop it
17801 					 * with extreme prejudice and let
17802 					 * the sender know.
17803 					 */
17804 					icmp_unreachable(q, first_mp,
17805 					    ICMP_SOURCE_ROUTE_FAILED,
17806 					    recv_ill->ill_zoneid, ipst);
17807 					return;
17808 				}
17809 			}
17810 			if (!mctl_present) {
17811 				ASSERT(first_mp == mp);
17812 				/*
17813 				 * This means that somebody is sending
17814 				 * Self-encapsualted packets without AH/ESP.
17815 				 * If AH/ESP was present, we would have already
17816 				 * allocated the first_mp.
17817 				 *
17818 				 * Send this packet to find a tunnel endpoint.
17819 				 * if I can't find one, an ICMP
17820 				 * PROTOCOL_UNREACHABLE will get sent.
17821 				 */
17822 				goto fanout;
17823 			}
17824 			/*
17825 			 * We generally store the ill_index if we need to
17826 			 * do IPsec processing as we lose the ill queue when
17827 			 * we come back. But in this case, we never should
17828 			 * have to store the ill_index here as it should have
17829 			 * been stored previously when we processed the
17830 			 * AH/ESP header in this routine or for non-ipsec
17831 			 * cases, we still have the queue. But for some bad
17832 			 * packets from the wire, we can get to IPsec after
17833 			 * this and we better store the index for that case.
17834 			 */
17835 			ill = (ill_t *)q->q_ptr;
17836 			ii = (ipsec_in_t *)first_mp->b_rptr;
17837 			ii->ipsec_in_ill_index =
17838 			    ill->ill_phyint->phyint_ifindex;
17839 			ii->ipsec_in_rill_index =
17840 			    recv_ill->ill_phyint->phyint_ifindex;
17841 			if (ii->ipsec_in_decaps) {
17842 				/*
17843 				 * This packet is self-encapsulated multiple
17844 				 * times. We don't want to recurse infinitely.
17845 				 * To keep it simple, drop the packet.
17846 				 */
17847 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17848 				freemsg(first_mp);
17849 				return;
17850 			}
17851 			ii->ipsec_in_decaps = B_TRUE;
17852 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17853 			    ire);
17854 			return;
17855 		}
17856 		break;
17857 	case IPPROTO_AH:
17858 	case IPPROTO_ESP: {
17859 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17860 
17861 		/*
17862 		 * Fast path for AH/ESP. If this is the first time
17863 		 * we are sending a datagram to AH/ESP, allocate
17864 		 * a IPSEC_IN message and prepend it. Otherwise,
17865 		 * just fanout.
17866 		 */
17867 
17868 		int ipsec_rc;
17869 		ipsec_in_t *ii;
17870 		netstack_t *ns = ipst->ips_netstack;
17871 
17872 		IP_STAT(ipst, ipsec_proto_ahesp);
17873 		if (!mctl_present) {
17874 			ASSERT(first_mp == mp);
17875 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17876 			if (first_mp == NULL) {
17877 				ip1dbg(("ip_proto_input: IPSEC_IN "
17878 				    "allocation failure.\n"));
17879 				freemsg(hada_mp); /* okay ifnull */
17880 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17881 				freemsg(mp);
17882 				return;
17883 			}
17884 			/*
17885 			 * Store the ill_index so that when we come back
17886 			 * from IPsec we ride on the same queue.
17887 			 */
17888 			ill = (ill_t *)q->q_ptr;
17889 			ii = (ipsec_in_t *)first_mp->b_rptr;
17890 			ii->ipsec_in_ill_index =
17891 			    ill->ill_phyint->phyint_ifindex;
17892 			ii->ipsec_in_rill_index =
17893 			    recv_ill->ill_phyint->phyint_ifindex;
17894 			first_mp->b_cont = mp;
17895 			/*
17896 			 * Cache hardware acceleration info.
17897 			 */
17898 			if (hada_mp != NULL) {
17899 				IPSECHW_DEBUG(IPSECHW_PKT,
17900 				    ("ip_rput_local: caching data attr.\n"));
17901 				ii->ipsec_in_accelerated = B_TRUE;
17902 				ii->ipsec_in_da = hada_mp;
17903 				hada_mp = NULL;
17904 			}
17905 		} else {
17906 			ii = (ipsec_in_t *)first_mp->b_rptr;
17907 		}
17908 
17909 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17910 
17911 		if (!ipsec_loaded(ipss)) {
17912 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17913 			    ire->ire_zoneid, ipst);
17914 			return;
17915 		}
17916 
17917 		ns = ipst->ips_netstack;
17918 		/* select inbound SA and have IPsec process the pkt */
17919 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17920 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17921 			boolean_t esp_in_udp_sa;
17922 			if (esph == NULL)
17923 				return;
17924 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17925 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17926 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17927 			    IPSA_F_NATT) != 0);
17928 			/*
17929 			 * The following is a fancy, but quick, way of saying:
17930 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17931 			 *    OR
17932 			 * ESP SA and ESP-in-UDP packet --> drop
17933 			 */
17934 			if (esp_in_udp_sa != esp_in_udp_packet) {
17935 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17936 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17937 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17938 				    &ns->netstack_ipsec->ipsec_dropper);
17939 				return;
17940 			}
17941 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17942 			    first_mp, esph);
17943 		} else {
17944 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17945 			if (ah == NULL)
17946 				return;
17947 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17948 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17949 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17950 			    first_mp, ah);
17951 		}
17952 
17953 		switch (ipsec_rc) {
17954 		case IPSEC_STATUS_SUCCESS:
17955 			break;
17956 		case IPSEC_STATUS_FAILED:
17957 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17958 			/* FALLTHRU */
17959 		case IPSEC_STATUS_PENDING:
17960 			return;
17961 		}
17962 		/* we're done with IPsec processing, send it up */
17963 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17964 		return;
17965 	}
17966 	default:
17967 		break;
17968 	}
17969 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17970 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17971 		    ire->ire_zoneid));
17972 		goto drop_pkt;
17973 	}
17974 	/*
17975 	 * Handle protocols with which IP is less intimate.  There
17976 	 * can be more than one stream bound to a particular
17977 	 * protocol.  When this is the case, each one gets a copy
17978 	 * of any incoming packets.
17979 	 */
17980 fanout:
17981 	ip_fanout_proto(q, first_mp, ill, ipha,
17982 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17983 	    B_TRUE, recv_ill, ire->ire_zoneid);
17984 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17985 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17986 	return;
17987 
17988 drop_pkt:
17989 	freemsg(first_mp);
17990 	if (hada_mp != NULL)
17991 		freeb(hada_mp);
17992 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17993 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17994 #undef	rptr
17995 #undef  iphs
17996 
17997 }
17998 
17999 /*
18000  * Update any source route, record route or timestamp options.
18001  * Check that we are at end of strict source route.
18002  * The options have already been checked for sanity in ip_rput_options().
18003  */
18004 static boolean_t
18005 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
18006     ip_stack_t *ipst)
18007 {
18008 	ipoptp_t	opts;
18009 	uchar_t		*opt;
18010 	uint8_t		optval;
18011 	uint8_t		optlen;
18012 	ipaddr_t	dst;
18013 	uint32_t	ts;
18014 	ire_t		*dst_ire;
18015 	timestruc_t	now;
18016 	zoneid_t	zoneid;
18017 	ill_t		*ill;
18018 
18019 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18020 
18021 	ip2dbg(("ip_rput_local_options\n"));
18022 
18023 	for (optval = ipoptp_first(&opts, ipha);
18024 	    optval != IPOPT_EOL;
18025 	    optval = ipoptp_next(&opts)) {
18026 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18027 		opt = opts.ipoptp_cur;
18028 		optlen = opts.ipoptp_len;
18029 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18030 		    optval, optlen));
18031 		switch (optval) {
18032 			uint32_t off;
18033 		case IPOPT_SSRR:
18034 		case IPOPT_LSRR:
18035 			off = opt[IPOPT_OFFSET];
18036 			off--;
18037 			if (optlen < IP_ADDR_LEN ||
18038 			    off > optlen - IP_ADDR_LEN) {
18039 				/* End of source route */
18040 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18041 				break;
18042 			}
18043 			/*
18044 			 * This will only happen if two consecutive entries
18045 			 * in the source route contains our address or if
18046 			 * it is a packet with a loose source route which
18047 			 * reaches us before consuming the whole source route
18048 			 */
18049 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18050 			if (optval == IPOPT_SSRR) {
18051 				goto bad_src_route;
18052 			}
18053 			/*
18054 			 * Hack: instead of dropping the packet truncate the
18055 			 * source route to what has been used by filling the
18056 			 * rest with IPOPT_NOP.
18057 			 */
18058 			opt[IPOPT_OLEN] = (uint8_t)off;
18059 			while (off < optlen) {
18060 				opt[off++] = IPOPT_NOP;
18061 			}
18062 			break;
18063 		case IPOPT_RR:
18064 			off = opt[IPOPT_OFFSET];
18065 			off--;
18066 			if (optlen < IP_ADDR_LEN ||
18067 			    off > optlen - IP_ADDR_LEN) {
18068 				/* No more room - ignore */
18069 				ip1dbg((
18070 				    "ip_rput_local_options: end of RR\n"));
18071 				break;
18072 			}
18073 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18074 			    IP_ADDR_LEN);
18075 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18076 			break;
18077 		case IPOPT_TS:
18078 			/* Insert timestamp if there is romm */
18079 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18080 			case IPOPT_TS_TSONLY:
18081 				off = IPOPT_TS_TIMELEN;
18082 				break;
18083 			case IPOPT_TS_PRESPEC:
18084 			case IPOPT_TS_PRESPEC_RFC791:
18085 				/* Verify that the address matched */
18086 				off = opt[IPOPT_OFFSET] - 1;
18087 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18088 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18089 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18090 				    ipst);
18091 				if (dst_ire == NULL) {
18092 					/* Not for us */
18093 					break;
18094 				}
18095 				ire_refrele(dst_ire);
18096 				/* FALLTHRU */
18097 			case IPOPT_TS_TSANDADDR:
18098 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18099 				break;
18100 			default:
18101 				/*
18102 				 * ip_*put_options should have already
18103 				 * dropped this packet.
18104 				 */
18105 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18106 				    "unknown IT - bug in ip_rput_options?\n");
18107 				return (B_TRUE);	/* Keep "lint" happy */
18108 			}
18109 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18110 				/* Increase overflow counter */
18111 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18112 				opt[IPOPT_POS_OV_FLG] =
18113 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18114 				    (off << 4));
18115 				break;
18116 			}
18117 			off = opt[IPOPT_OFFSET] - 1;
18118 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18119 			case IPOPT_TS_PRESPEC:
18120 			case IPOPT_TS_PRESPEC_RFC791:
18121 			case IPOPT_TS_TSANDADDR:
18122 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18123 				    IP_ADDR_LEN);
18124 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18125 				/* FALLTHRU */
18126 			case IPOPT_TS_TSONLY:
18127 				off = opt[IPOPT_OFFSET] - 1;
18128 				/* Compute # of milliseconds since midnight */
18129 				gethrestime(&now);
18130 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18131 				    now.tv_nsec / (NANOSEC / MILLISEC);
18132 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18133 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18134 				break;
18135 			}
18136 			break;
18137 		}
18138 	}
18139 	return (B_TRUE);
18140 
18141 bad_src_route:
18142 	q = WR(q);
18143 	if (q->q_next != NULL)
18144 		ill = q->q_ptr;
18145 	else
18146 		ill = NULL;
18147 
18148 	/* make sure we clear any indication of a hardware checksum */
18149 	DB_CKSUMFLAGS(mp) = 0;
18150 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18151 	if (zoneid == ALL_ZONES)
18152 		freemsg(mp);
18153 	else
18154 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18155 	return (B_FALSE);
18156 
18157 }
18158 
18159 /*
18160  * Process IP options in an inbound packet.  If an option affects the
18161  * effective destination address, return the next hop address via dstp.
18162  * Returns -1 if something fails in which case an ICMP error has been sent
18163  * and mp freed.
18164  */
18165 static int
18166 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18167     ip_stack_t *ipst)
18168 {
18169 	ipoptp_t	opts;
18170 	uchar_t		*opt;
18171 	uint8_t		optval;
18172 	uint8_t		optlen;
18173 	ipaddr_t	dst;
18174 	intptr_t	code = 0;
18175 	ire_t		*ire = NULL;
18176 	zoneid_t	zoneid;
18177 	ill_t		*ill;
18178 
18179 	ip2dbg(("ip_rput_options\n"));
18180 	dst = ipha->ipha_dst;
18181 	for (optval = ipoptp_first(&opts, ipha);
18182 	    optval != IPOPT_EOL;
18183 	    optval = ipoptp_next(&opts)) {
18184 		opt = opts.ipoptp_cur;
18185 		optlen = opts.ipoptp_len;
18186 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18187 		    optval, optlen));
18188 		/*
18189 		 * Note: we need to verify the checksum before we
18190 		 * modify anything thus this routine only extracts the next
18191 		 * hop dst from any source route.
18192 		 */
18193 		switch (optval) {
18194 			uint32_t off;
18195 		case IPOPT_SSRR:
18196 		case IPOPT_LSRR:
18197 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18198 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18199 			if (ire == NULL) {
18200 				if (optval == IPOPT_SSRR) {
18201 					ip1dbg(("ip_rput_options: not next"
18202 					    " strict source route 0x%x\n",
18203 					    ntohl(dst)));
18204 					code = (char *)&ipha->ipha_dst -
18205 					    (char *)ipha;
18206 					goto param_prob; /* RouterReq's */
18207 				}
18208 				ip2dbg(("ip_rput_options: "
18209 				    "not next source route 0x%x\n",
18210 				    ntohl(dst)));
18211 				break;
18212 			}
18213 			ire_refrele(ire);
18214 
18215 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18216 				ip1dbg((
18217 				    "ip_rput_options: bad option offset\n"));
18218 				code = (char *)&opt[IPOPT_OLEN] -
18219 				    (char *)ipha;
18220 				goto param_prob;
18221 			}
18222 			off = opt[IPOPT_OFFSET];
18223 			off--;
18224 		redo_srr:
18225 			if (optlen < IP_ADDR_LEN ||
18226 			    off > optlen - IP_ADDR_LEN) {
18227 				/* End of source route */
18228 				ip1dbg(("ip_rput_options: end of SR\n"));
18229 				break;
18230 			}
18231 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18232 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18233 			    ntohl(dst)));
18234 
18235 			/*
18236 			 * Check if our address is present more than
18237 			 * once as consecutive hops in source route.
18238 			 * XXX verify per-interface ip_forwarding
18239 			 * for source route?
18240 			 */
18241 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18242 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18243 
18244 			if (ire != NULL) {
18245 				ire_refrele(ire);
18246 				off += IP_ADDR_LEN;
18247 				goto redo_srr;
18248 			}
18249 
18250 			if (dst == htonl(INADDR_LOOPBACK)) {
18251 				ip1dbg(("ip_rput_options: loopback addr in "
18252 				    "source route!\n"));
18253 				goto bad_src_route;
18254 			}
18255 			/*
18256 			 * For strict: verify that dst is directly
18257 			 * reachable.
18258 			 */
18259 			if (optval == IPOPT_SSRR) {
18260 				ire = ire_ftable_lookup(dst, 0, 0,
18261 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18262 				    msg_getlabel(mp),
18263 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18264 				if (ire == NULL) {
18265 					ip1dbg(("ip_rput_options: SSRR not "
18266 					    "directly reachable: 0x%x\n",
18267 					    ntohl(dst)));
18268 					goto bad_src_route;
18269 				}
18270 				ire_refrele(ire);
18271 			}
18272 			/*
18273 			 * Defer update of the offset and the record route
18274 			 * until the packet is forwarded.
18275 			 */
18276 			break;
18277 		case IPOPT_RR:
18278 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18279 				ip1dbg((
18280 				    "ip_rput_options: bad option offset\n"));
18281 				code = (char *)&opt[IPOPT_OLEN] -
18282 				    (char *)ipha;
18283 				goto param_prob;
18284 			}
18285 			break;
18286 		case IPOPT_TS:
18287 			/*
18288 			 * Verify that length >= 5 and that there is either
18289 			 * room for another timestamp or that the overflow
18290 			 * counter is not maxed out.
18291 			 */
18292 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18293 			if (optlen < IPOPT_MINLEN_IT) {
18294 				goto param_prob;
18295 			}
18296 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18297 				ip1dbg((
18298 				    "ip_rput_options: bad option offset\n"));
18299 				code = (char *)&opt[IPOPT_OFFSET] -
18300 				    (char *)ipha;
18301 				goto param_prob;
18302 			}
18303 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18304 			case IPOPT_TS_TSONLY:
18305 				off = IPOPT_TS_TIMELEN;
18306 				break;
18307 			case IPOPT_TS_TSANDADDR:
18308 			case IPOPT_TS_PRESPEC:
18309 			case IPOPT_TS_PRESPEC_RFC791:
18310 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18311 				break;
18312 			default:
18313 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18314 				    (char *)ipha;
18315 				goto param_prob;
18316 			}
18317 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18318 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18319 				/*
18320 				 * No room and the overflow counter is 15
18321 				 * already.
18322 				 */
18323 				goto param_prob;
18324 			}
18325 			break;
18326 		}
18327 	}
18328 
18329 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18330 		*dstp = dst;
18331 		return (0);
18332 	}
18333 
18334 	ip1dbg(("ip_rput_options: error processing IP options."));
18335 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18336 
18337 param_prob:
18338 	q = WR(q);
18339 	if (q->q_next != NULL)
18340 		ill = q->q_ptr;
18341 	else
18342 		ill = NULL;
18343 
18344 	/* make sure we clear any indication of a hardware checksum */
18345 	DB_CKSUMFLAGS(mp) = 0;
18346 	/* Don't know whether this is for non-global or global/forwarding */
18347 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18348 	if (zoneid == ALL_ZONES)
18349 		freemsg(mp);
18350 	else
18351 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18352 	return (-1);
18353 
18354 bad_src_route:
18355 	q = WR(q);
18356 	if (q->q_next != NULL)
18357 		ill = q->q_ptr;
18358 	else
18359 		ill = NULL;
18360 
18361 	/* make sure we clear any indication of a hardware checksum */
18362 	DB_CKSUMFLAGS(mp) = 0;
18363 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18364 	if (zoneid == ALL_ZONES)
18365 		freemsg(mp);
18366 	else
18367 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18368 	return (-1);
18369 }
18370 
18371 /*
18372  * IP & ICMP info in >=14 msg's ...
18373  *  - ip fixed part (mib2_ip_t)
18374  *  - icmp fixed part (mib2_icmp_t)
18375  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18376  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18377  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18378  *  - ipRouteAttributeTable (ip 102)	labeled routes
18379  *  - ip multicast membership (ip_member_t)
18380  *  - ip multicast source filtering (ip_grpsrc_t)
18381  *  - igmp fixed part (struct igmpstat)
18382  *  - multicast routing stats (struct mrtstat)
18383  *  - multicast routing vifs (array of struct vifctl)
18384  *  - multicast routing routes (array of struct mfcctl)
18385  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18386  *					One per ill plus one generic
18387  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18388  *					One per ill plus one generic
18389  *  - ipv6RouteEntry			all IPv6 IREs
18390  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18391  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18392  *  - ipv6AddrEntry			all IPv6 ipifs
18393  *  - ipv6 multicast membership (ipv6_member_t)
18394  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18395  *
18396  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18397  *
18398  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18399  * already filled in by the caller.
18400  * Return value of 0 indicates that no messages were sent and caller
18401  * should free mpctl.
18402  */
18403 int
18404 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18405 {
18406 	ip_stack_t *ipst;
18407 	sctp_stack_t *sctps;
18408 
18409 	if (q->q_next != NULL) {
18410 		ipst = ILLQ_TO_IPST(q);
18411 	} else {
18412 		ipst = CONNQ_TO_IPST(q);
18413 	}
18414 	ASSERT(ipst != NULL);
18415 	sctps = ipst->ips_netstack->netstack_sctp;
18416 
18417 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18418 		return (0);
18419 	}
18420 
18421 	/*
18422 	 * For the purposes of the (broken) packet shell use
18423 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18424 	 * to make TCP and UDP appear first in the list of mib items.
18425 	 * TBD: We could expand this and use it in netstat so that
18426 	 * the kernel doesn't have to produce large tables (connections,
18427 	 * routes, etc) when netstat only wants the statistics or a particular
18428 	 * table.
18429 	 */
18430 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18431 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18432 			return (1);
18433 		}
18434 	}
18435 
18436 	if (level != MIB2_TCP) {
18437 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18438 			return (1);
18439 		}
18440 	}
18441 
18442 	if (level != MIB2_UDP) {
18443 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18444 			return (1);
18445 		}
18446 	}
18447 
18448 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18449 	    ipst)) == NULL) {
18450 		return (1);
18451 	}
18452 
18453 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18454 		return (1);
18455 	}
18456 
18457 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18458 		return (1);
18459 	}
18460 
18461 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18462 		return (1);
18463 	}
18464 
18465 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18466 		return (1);
18467 	}
18468 
18469 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18470 		return (1);
18471 	}
18472 
18473 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18474 		return (1);
18475 	}
18476 
18477 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18478 		return (1);
18479 	}
18480 
18481 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18482 		return (1);
18483 	}
18484 
18485 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18486 		return (1);
18487 	}
18488 
18489 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18490 		return (1);
18491 	}
18492 
18493 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18494 		return (1);
18495 	}
18496 
18497 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18498 		return (1);
18499 	}
18500 
18501 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18502 		return (1);
18503 	}
18504 
18505 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
18506 	if (mpctl == NULL)
18507 		return (1);
18508 
18509 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
18510 	if (mpctl == NULL)
18511 		return (1);
18512 
18513 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18514 		return (1);
18515 	}
18516 	freemsg(mpctl);
18517 	return (1);
18518 }
18519 
18520 /* Get global (legacy) IPv4 statistics */
18521 static mblk_t *
18522 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18523     ip_stack_t *ipst)
18524 {
18525 	mib2_ip_t		old_ip_mib;
18526 	struct opthdr		*optp;
18527 	mblk_t			*mp2ctl;
18528 
18529 	/*
18530 	 * make a copy of the original message
18531 	 */
18532 	mp2ctl = copymsg(mpctl);
18533 
18534 	/* fixed length IP structure... */
18535 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18536 	optp->level = MIB2_IP;
18537 	optp->name = 0;
18538 	SET_MIB(old_ip_mib.ipForwarding,
18539 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18540 	SET_MIB(old_ip_mib.ipDefaultTTL,
18541 	    (uint32_t)ipst->ips_ip_def_ttl);
18542 	SET_MIB(old_ip_mib.ipReasmTimeout,
18543 	    ipst->ips_ip_g_frag_timeout);
18544 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18545 	    sizeof (mib2_ipAddrEntry_t));
18546 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18547 	    sizeof (mib2_ipRouteEntry_t));
18548 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18549 	    sizeof (mib2_ipNetToMediaEntry_t));
18550 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18551 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18552 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18553 	    sizeof (mib2_ipAttributeEntry_t));
18554 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18555 
18556 	/*
18557 	 * Grab the statistics from the new IP MIB
18558 	 */
18559 	SET_MIB(old_ip_mib.ipInReceives,
18560 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18561 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18562 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18563 	SET_MIB(old_ip_mib.ipForwDatagrams,
18564 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18565 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18566 	    ipmib->ipIfStatsInUnknownProtos);
18567 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18568 	SET_MIB(old_ip_mib.ipInDelivers,
18569 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18570 	SET_MIB(old_ip_mib.ipOutRequests,
18571 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18572 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18573 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18574 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18575 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18576 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18577 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18578 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18579 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18580 
18581 	/* ipRoutingDiscards is not being used */
18582 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18583 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18584 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18585 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18586 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18587 	    ipmib->ipIfStatsReasmDuplicates);
18588 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18589 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18590 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18591 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18592 	SET_MIB(old_ip_mib.rawipInOverflows,
18593 	    ipmib->rawipIfStatsInOverflows);
18594 
18595 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18596 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18597 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18598 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18599 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18600 	    ipmib->ipIfStatsOutSwitchIPVersion);
18601 
18602 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18603 	    (int)sizeof (old_ip_mib))) {
18604 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18605 		    (uint_t)sizeof (old_ip_mib)));
18606 	}
18607 
18608 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18609 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18610 	    (int)optp->level, (int)optp->name, (int)optp->len));
18611 	qreply(q, mpctl);
18612 	return (mp2ctl);
18613 }
18614 
18615 /* Per interface IPv4 statistics */
18616 static mblk_t *
18617 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18618 {
18619 	struct opthdr		*optp;
18620 	mblk_t			*mp2ctl;
18621 	ill_t			*ill;
18622 	ill_walk_context_t	ctx;
18623 	mblk_t			*mp_tail = NULL;
18624 	mib2_ipIfStatsEntry_t	global_ip_mib;
18625 
18626 	/*
18627 	 * Make a copy of the original message
18628 	 */
18629 	mp2ctl = copymsg(mpctl);
18630 
18631 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18632 	optp->level = MIB2_IP;
18633 	optp->name = MIB2_IP_TRAFFIC_STATS;
18634 	/* Include "unknown interface" ip_mib */
18635 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18636 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18637 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18638 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18639 	    (ipst->ips_ip_g_forward ? 1 : 2));
18640 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18641 	    (uint32_t)ipst->ips_ip_def_ttl);
18642 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18643 	    sizeof (mib2_ipIfStatsEntry_t));
18644 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18645 	    sizeof (mib2_ipAddrEntry_t));
18646 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18647 	    sizeof (mib2_ipRouteEntry_t));
18648 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18649 	    sizeof (mib2_ipNetToMediaEntry_t));
18650 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18651 	    sizeof (ip_member_t));
18652 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18653 	    sizeof (ip_grpsrc_t));
18654 
18655 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18656 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18657 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18658 		    "failed to allocate %u bytes\n",
18659 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18660 	}
18661 
18662 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18663 
18664 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18665 	ill = ILL_START_WALK_V4(&ctx, ipst);
18666 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18667 		ill->ill_ip_mib->ipIfStatsIfIndex =
18668 		    ill->ill_phyint->phyint_ifindex;
18669 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18670 		    (ipst->ips_ip_g_forward ? 1 : 2));
18671 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18672 		    (uint32_t)ipst->ips_ip_def_ttl);
18673 
18674 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18675 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18676 		    (char *)ill->ill_ip_mib,
18677 		    (int)sizeof (*ill->ill_ip_mib))) {
18678 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18679 			    "failed to allocate %u bytes\n",
18680 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18681 		}
18682 	}
18683 	rw_exit(&ipst->ips_ill_g_lock);
18684 
18685 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18686 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18687 	    "level %d, name %d, len %d\n",
18688 	    (int)optp->level, (int)optp->name, (int)optp->len));
18689 	qreply(q, mpctl);
18690 
18691 	if (mp2ctl == NULL)
18692 		return (NULL);
18693 
18694 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18695 }
18696 
18697 /* Global IPv4 ICMP statistics */
18698 static mblk_t *
18699 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18700 {
18701 	struct opthdr		*optp;
18702 	mblk_t			*mp2ctl;
18703 
18704 	/*
18705 	 * Make a copy of the original message
18706 	 */
18707 	mp2ctl = copymsg(mpctl);
18708 
18709 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18710 	optp->level = MIB2_ICMP;
18711 	optp->name = 0;
18712 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18713 	    (int)sizeof (ipst->ips_icmp_mib))) {
18714 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18715 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18716 	}
18717 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18718 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18719 	    (int)optp->level, (int)optp->name, (int)optp->len));
18720 	qreply(q, mpctl);
18721 	return (mp2ctl);
18722 }
18723 
18724 /* Global IPv4 IGMP statistics */
18725 static mblk_t *
18726 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18727 {
18728 	struct opthdr		*optp;
18729 	mblk_t			*mp2ctl;
18730 
18731 	/*
18732 	 * make a copy of the original message
18733 	 */
18734 	mp2ctl = copymsg(mpctl);
18735 
18736 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18737 	optp->level = EXPER_IGMP;
18738 	optp->name = 0;
18739 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18740 	    (int)sizeof (ipst->ips_igmpstat))) {
18741 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18742 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18743 	}
18744 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18745 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18746 	    (int)optp->level, (int)optp->name, (int)optp->len));
18747 	qreply(q, mpctl);
18748 	return (mp2ctl);
18749 }
18750 
18751 /* Global IPv4 Multicast Routing statistics */
18752 static mblk_t *
18753 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18754 {
18755 	struct opthdr		*optp;
18756 	mblk_t			*mp2ctl;
18757 
18758 	/*
18759 	 * make a copy of the original message
18760 	 */
18761 	mp2ctl = copymsg(mpctl);
18762 
18763 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18764 	optp->level = EXPER_DVMRP;
18765 	optp->name = 0;
18766 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18767 		ip0dbg(("ip_mroute_stats: failed\n"));
18768 	}
18769 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18770 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18771 	    (int)optp->level, (int)optp->name, (int)optp->len));
18772 	qreply(q, mpctl);
18773 	return (mp2ctl);
18774 }
18775 
18776 /* IPv4 address information */
18777 static mblk_t *
18778 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18779 {
18780 	struct opthdr		*optp;
18781 	mblk_t			*mp2ctl;
18782 	mblk_t			*mp_tail = NULL;
18783 	ill_t			*ill;
18784 	ipif_t			*ipif;
18785 	uint_t			bitval;
18786 	mib2_ipAddrEntry_t	mae;
18787 	zoneid_t		zoneid;
18788 	ill_walk_context_t ctx;
18789 
18790 	/*
18791 	 * make a copy of the original message
18792 	 */
18793 	mp2ctl = copymsg(mpctl);
18794 
18795 	/* ipAddrEntryTable */
18796 
18797 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18798 	optp->level = MIB2_IP;
18799 	optp->name = MIB2_IP_ADDR;
18800 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18801 
18802 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18803 	ill = ILL_START_WALK_V4(&ctx, ipst);
18804 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18805 		for (ipif = ill->ill_ipif; ipif != NULL;
18806 		    ipif = ipif->ipif_next) {
18807 			if (ipif->ipif_zoneid != zoneid &&
18808 			    ipif->ipif_zoneid != ALL_ZONES)
18809 				continue;
18810 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18811 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18812 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18813 
18814 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18815 			    OCTET_LENGTH);
18816 			mae.ipAdEntIfIndex.o_length =
18817 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18818 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18819 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18820 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18821 			mae.ipAdEntInfo.ae_subnet_len =
18822 			    ip_mask_to_plen(ipif->ipif_net_mask);
18823 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18824 			for (bitval = 1;
18825 			    bitval &&
18826 			    !(bitval & ipif->ipif_brd_addr);
18827 			    bitval <<= 1)
18828 				noop;
18829 			mae.ipAdEntBcastAddr = bitval;
18830 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18831 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18832 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18833 			mae.ipAdEntInfo.ae_broadcast_addr =
18834 			    ipif->ipif_brd_addr;
18835 			mae.ipAdEntInfo.ae_pp_dst_addr =
18836 			    ipif->ipif_pp_dst_addr;
18837 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18838 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18839 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18840 
18841 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18842 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18843 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18844 				    "allocate %u bytes\n",
18845 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18846 			}
18847 		}
18848 	}
18849 	rw_exit(&ipst->ips_ill_g_lock);
18850 
18851 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18852 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18853 	    (int)optp->level, (int)optp->name, (int)optp->len));
18854 	qreply(q, mpctl);
18855 	return (mp2ctl);
18856 }
18857 
18858 /* IPv6 address information */
18859 static mblk_t *
18860 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18861 {
18862 	struct opthdr		*optp;
18863 	mblk_t			*mp2ctl;
18864 	mblk_t			*mp_tail = NULL;
18865 	ill_t			*ill;
18866 	ipif_t			*ipif;
18867 	mib2_ipv6AddrEntry_t	mae6;
18868 	zoneid_t		zoneid;
18869 	ill_walk_context_t	ctx;
18870 
18871 	/*
18872 	 * make a copy of the original message
18873 	 */
18874 	mp2ctl = copymsg(mpctl);
18875 
18876 	/* ipv6AddrEntryTable */
18877 
18878 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18879 	optp->level = MIB2_IP6;
18880 	optp->name = MIB2_IP6_ADDR;
18881 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18882 
18883 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18884 	ill = ILL_START_WALK_V6(&ctx, ipst);
18885 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18886 		for (ipif = ill->ill_ipif; ipif != NULL;
18887 		    ipif = ipif->ipif_next) {
18888 			if (ipif->ipif_zoneid != zoneid &&
18889 			    ipif->ipif_zoneid != ALL_ZONES)
18890 				continue;
18891 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18892 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18893 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18894 
18895 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18896 			    OCTET_LENGTH);
18897 			mae6.ipv6AddrIfIndex.o_length =
18898 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18899 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18900 			mae6.ipv6AddrPfxLength =
18901 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18902 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18903 			mae6.ipv6AddrInfo.ae_subnet_len =
18904 			    mae6.ipv6AddrPfxLength;
18905 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18906 
18907 			/* Type: stateless(1), stateful(2), unknown(3) */
18908 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18909 				mae6.ipv6AddrType = 1;
18910 			else
18911 				mae6.ipv6AddrType = 2;
18912 			/* Anycast: true(1), false(2) */
18913 			if (ipif->ipif_flags & IPIF_ANYCAST)
18914 				mae6.ipv6AddrAnycastFlag = 1;
18915 			else
18916 				mae6.ipv6AddrAnycastFlag = 2;
18917 
18918 			/*
18919 			 * Address status: preferred(1), deprecated(2),
18920 			 * invalid(3), inaccessible(4), unknown(5)
18921 			 */
18922 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18923 				mae6.ipv6AddrStatus = 3;
18924 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18925 				mae6.ipv6AddrStatus = 2;
18926 			else
18927 				mae6.ipv6AddrStatus = 1;
18928 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18929 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18930 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18931 			    ipif->ipif_v6pp_dst_addr;
18932 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18933 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18934 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18935 			mae6.ipv6AddrIdentifier = ill->ill_token;
18936 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18937 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18938 			mae6.ipv6AddrRetransmitTime =
18939 			    ill->ill_reachable_retrans_time;
18940 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18941 			    (char *)&mae6,
18942 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18943 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18944 				    "allocate %u bytes\n",
18945 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18946 			}
18947 		}
18948 	}
18949 	rw_exit(&ipst->ips_ill_g_lock);
18950 
18951 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18952 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18953 	    (int)optp->level, (int)optp->name, (int)optp->len));
18954 	qreply(q, mpctl);
18955 	return (mp2ctl);
18956 }
18957 
18958 /* IPv4 multicast group membership. */
18959 static mblk_t *
18960 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18961 {
18962 	struct opthdr		*optp;
18963 	mblk_t			*mp2ctl;
18964 	ill_t			*ill;
18965 	ipif_t			*ipif;
18966 	ilm_t			*ilm;
18967 	ip_member_t		ipm;
18968 	mblk_t			*mp_tail = NULL;
18969 	ill_walk_context_t	ctx;
18970 	zoneid_t		zoneid;
18971 	ilm_walker_t		ilw;
18972 
18973 	/*
18974 	 * make a copy of the original message
18975 	 */
18976 	mp2ctl = copymsg(mpctl);
18977 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18978 
18979 	/* ipGroupMember table */
18980 	optp = (struct opthdr *)&mpctl->b_rptr[
18981 	    sizeof (struct T_optmgmt_ack)];
18982 	optp->level = MIB2_IP;
18983 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18984 
18985 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18986 	ill = ILL_START_WALK_V4(&ctx, ipst);
18987 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18988 		if (IS_UNDER_IPMP(ill))
18989 			continue;
18990 
18991 		ilm = ilm_walker_start(&ilw, ill);
18992 		for (ipif = ill->ill_ipif; ipif != NULL;
18993 		    ipif = ipif->ipif_next) {
18994 			if (ipif->ipif_zoneid != zoneid &&
18995 			    ipif->ipif_zoneid != ALL_ZONES)
18996 				continue;	/* not this zone */
18997 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18998 			    OCTET_LENGTH);
18999 			ipm.ipGroupMemberIfIndex.o_length =
19000 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
19001 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19002 				ASSERT(ilm->ilm_ipif != NULL);
19003 				ASSERT(ilm->ilm_ill == NULL);
19004 				if (ilm->ilm_ipif != ipif)
19005 					continue;
19006 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
19007 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
19008 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
19009 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19010 				    (char *)&ipm, (int)sizeof (ipm))) {
19011 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
19012 					    "failed to allocate %u bytes\n",
19013 					    (uint_t)sizeof (ipm)));
19014 				}
19015 			}
19016 		}
19017 		ilm_walker_finish(&ilw);
19018 	}
19019 	rw_exit(&ipst->ips_ill_g_lock);
19020 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19021 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19022 	    (int)optp->level, (int)optp->name, (int)optp->len));
19023 	qreply(q, mpctl);
19024 	return (mp2ctl);
19025 }
19026 
19027 /* IPv6 multicast group membership. */
19028 static mblk_t *
19029 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19030 {
19031 	struct opthdr		*optp;
19032 	mblk_t			*mp2ctl;
19033 	ill_t			*ill;
19034 	ilm_t			*ilm;
19035 	ipv6_member_t		ipm6;
19036 	mblk_t			*mp_tail = NULL;
19037 	ill_walk_context_t	ctx;
19038 	zoneid_t		zoneid;
19039 	ilm_walker_t		ilw;
19040 
19041 	/*
19042 	 * make a copy of the original message
19043 	 */
19044 	mp2ctl = copymsg(mpctl);
19045 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19046 
19047 	/* ip6GroupMember table */
19048 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19049 	optp->level = MIB2_IP6;
19050 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19051 
19052 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19053 	ill = ILL_START_WALK_V6(&ctx, ipst);
19054 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19055 		if (IS_UNDER_IPMP(ill))
19056 			continue;
19057 
19058 		ilm = ilm_walker_start(&ilw, ill);
19059 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19060 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19061 			ASSERT(ilm->ilm_ipif == NULL);
19062 			ASSERT(ilm->ilm_ill != NULL);
19063 			if (ilm->ilm_zoneid != zoneid)
19064 				continue;	/* not this zone */
19065 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19066 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19067 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19068 			if (!snmp_append_data2(mpctl->b_cont,
19069 			    &mp_tail,
19070 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19071 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19072 				    "failed to allocate %u bytes\n",
19073 				    (uint_t)sizeof (ipm6)));
19074 			}
19075 		}
19076 		ilm_walker_finish(&ilw);
19077 	}
19078 	rw_exit(&ipst->ips_ill_g_lock);
19079 
19080 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19081 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19082 	    (int)optp->level, (int)optp->name, (int)optp->len));
19083 	qreply(q, mpctl);
19084 	return (mp2ctl);
19085 }
19086 
19087 /* IP multicast filtered sources */
19088 static mblk_t *
19089 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19090 {
19091 	struct opthdr		*optp;
19092 	mblk_t			*mp2ctl;
19093 	ill_t			*ill;
19094 	ipif_t			*ipif;
19095 	ilm_t			*ilm;
19096 	ip_grpsrc_t		ips;
19097 	mblk_t			*mp_tail = NULL;
19098 	ill_walk_context_t	ctx;
19099 	zoneid_t		zoneid;
19100 	int			i;
19101 	slist_t			*sl;
19102 	ilm_walker_t		ilw;
19103 
19104 	/*
19105 	 * make a copy of the original message
19106 	 */
19107 	mp2ctl = copymsg(mpctl);
19108 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19109 
19110 	/* ipGroupSource table */
19111 	optp = (struct opthdr *)&mpctl->b_rptr[
19112 	    sizeof (struct T_optmgmt_ack)];
19113 	optp->level = MIB2_IP;
19114 	optp->name = EXPER_IP_GROUP_SOURCES;
19115 
19116 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19117 	ill = ILL_START_WALK_V4(&ctx, ipst);
19118 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19119 		if (IS_UNDER_IPMP(ill))
19120 			continue;
19121 
19122 		ilm = ilm_walker_start(&ilw, ill);
19123 		for (ipif = ill->ill_ipif; ipif != NULL;
19124 		    ipif = ipif->ipif_next) {
19125 			if (ipif->ipif_zoneid != zoneid)
19126 				continue;	/* not this zone */
19127 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19128 			    OCTET_LENGTH);
19129 			ips.ipGroupSourceIfIndex.o_length =
19130 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19131 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19132 				ASSERT(ilm->ilm_ipif != NULL);
19133 				ASSERT(ilm->ilm_ill == NULL);
19134 				sl = ilm->ilm_filter;
19135 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19136 					continue;
19137 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19138 				for (i = 0; i < sl->sl_numsrc; i++) {
19139 					if (!IN6_IS_ADDR_V4MAPPED(
19140 					    &sl->sl_addr[i]))
19141 						continue;
19142 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19143 					    ips.ipGroupSourceAddress);
19144 					if (snmp_append_data2(mpctl->b_cont,
19145 					    &mp_tail, (char *)&ips,
19146 					    (int)sizeof (ips)) == 0) {
19147 						ip1dbg(("ip_snmp_get_mib2_"
19148 						    "ip_group_src: failed to "
19149 						    "allocate %u bytes\n",
19150 						    (uint_t)sizeof (ips)));
19151 					}
19152 				}
19153 			}
19154 		}
19155 		ilm_walker_finish(&ilw);
19156 	}
19157 	rw_exit(&ipst->ips_ill_g_lock);
19158 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19159 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19160 	    (int)optp->level, (int)optp->name, (int)optp->len));
19161 	qreply(q, mpctl);
19162 	return (mp2ctl);
19163 }
19164 
19165 /* IPv6 multicast filtered sources. */
19166 static mblk_t *
19167 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19168 {
19169 	struct opthdr		*optp;
19170 	mblk_t			*mp2ctl;
19171 	ill_t			*ill;
19172 	ilm_t			*ilm;
19173 	ipv6_grpsrc_t		ips6;
19174 	mblk_t			*mp_tail = NULL;
19175 	ill_walk_context_t	ctx;
19176 	zoneid_t		zoneid;
19177 	int			i;
19178 	slist_t			*sl;
19179 	ilm_walker_t		ilw;
19180 
19181 	/*
19182 	 * make a copy of the original message
19183 	 */
19184 	mp2ctl = copymsg(mpctl);
19185 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19186 
19187 	/* ip6GroupMember table */
19188 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19189 	optp->level = MIB2_IP6;
19190 	optp->name = EXPER_IP6_GROUP_SOURCES;
19191 
19192 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19193 	ill = ILL_START_WALK_V6(&ctx, ipst);
19194 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19195 		if (IS_UNDER_IPMP(ill))
19196 			continue;
19197 
19198 		ilm = ilm_walker_start(&ilw, ill);
19199 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19200 		for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
19201 			ASSERT(ilm->ilm_ipif == NULL);
19202 			ASSERT(ilm->ilm_ill != NULL);
19203 			sl = ilm->ilm_filter;
19204 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19205 				continue;
19206 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19207 			for (i = 0; i < sl->sl_numsrc; i++) {
19208 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19209 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19210 				    (char *)&ips6, (int)sizeof (ips6))) {
19211 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19212 					    "group_src: failed to allocate "
19213 					    "%u bytes\n",
19214 					    (uint_t)sizeof (ips6)));
19215 				}
19216 			}
19217 		}
19218 		ilm_walker_finish(&ilw);
19219 	}
19220 	rw_exit(&ipst->ips_ill_g_lock);
19221 
19222 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19223 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19224 	    (int)optp->level, (int)optp->name, (int)optp->len));
19225 	qreply(q, mpctl);
19226 	return (mp2ctl);
19227 }
19228 
19229 /* Multicast routing virtual interface table. */
19230 static mblk_t *
19231 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19232 {
19233 	struct opthdr		*optp;
19234 	mblk_t			*mp2ctl;
19235 
19236 	/*
19237 	 * make a copy of the original message
19238 	 */
19239 	mp2ctl = copymsg(mpctl);
19240 
19241 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19242 	optp->level = EXPER_DVMRP;
19243 	optp->name = EXPER_DVMRP_VIF;
19244 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19245 		ip0dbg(("ip_mroute_vif: failed\n"));
19246 	}
19247 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19248 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19249 	    (int)optp->level, (int)optp->name, (int)optp->len));
19250 	qreply(q, mpctl);
19251 	return (mp2ctl);
19252 }
19253 
19254 /* Multicast routing table. */
19255 static mblk_t *
19256 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19257 {
19258 	struct opthdr		*optp;
19259 	mblk_t			*mp2ctl;
19260 
19261 	/*
19262 	 * make a copy of the original message
19263 	 */
19264 	mp2ctl = copymsg(mpctl);
19265 
19266 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19267 	optp->level = EXPER_DVMRP;
19268 	optp->name = EXPER_DVMRP_MRT;
19269 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19270 		ip0dbg(("ip_mroute_mrt: failed\n"));
19271 	}
19272 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19273 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19274 	    (int)optp->level, (int)optp->name, (int)optp->len));
19275 	qreply(q, mpctl);
19276 	return (mp2ctl);
19277 }
19278 
19279 /*
19280  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19281  * in one IRE walk.
19282  */
19283 static mblk_t *
19284 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
19285     ip_stack_t *ipst)
19286 {
19287 	struct opthdr	*optp;
19288 	mblk_t		*mp2ctl;	/* Returned */
19289 	mblk_t		*mp3ctl;	/* nettomedia */
19290 	mblk_t		*mp4ctl;	/* routeattrs */
19291 	iproutedata_t	ird;
19292 	zoneid_t	zoneid;
19293 
19294 	/*
19295 	 * make copies of the original message
19296 	 *	- mp2ctl is returned unchanged to the caller for his use
19297 	 *	- mpctl is sent upstream as ipRouteEntryTable
19298 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19299 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19300 	 */
19301 	mp2ctl = copymsg(mpctl);
19302 	mp3ctl = copymsg(mpctl);
19303 	mp4ctl = copymsg(mpctl);
19304 	if (mp3ctl == NULL || mp4ctl == NULL) {
19305 		freemsg(mp4ctl);
19306 		freemsg(mp3ctl);
19307 		freemsg(mp2ctl);
19308 		freemsg(mpctl);
19309 		return (NULL);
19310 	}
19311 
19312 	bzero(&ird, sizeof (ird));
19313 
19314 	ird.ird_route.lp_head = mpctl->b_cont;
19315 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19316 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19317 	/*
19318 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19319 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19320 	 * intended a temporary solution until a proper MIB API is provided
19321 	 * that provides complete filtering/caller-opt-in.
19322 	 */
19323 	if (level == EXPER_IP_AND_TESTHIDDEN)
19324 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19325 
19326 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19327 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19328 
19329 	/* ipRouteEntryTable in mpctl */
19330 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19331 	optp->level = MIB2_IP;
19332 	optp->name = MIB2_IP_ROUTE;
19333 	optp->len = msgdsize(ird.ird_route.lp_head);
19334 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19335 	    (int)optp->level, (int)optp->name, (int)optp->len));
19336 	qreply(q, mpctl);
19337 
19338 	/* ipNetToMediaEntryTable in mp3ctl */
19339 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19340 	optp->level = MIB2_IP;
19341 	optp->name = MIB2_IP_MEDIA;
19342 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19343 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19344 	    (int)optp->level, (int)optp->name, (int)optp->len));
19345 	qreply(q, mp3ctl);
19346 
19347 	/* ipRouteAttributeTable in mp4ctl */
19348 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19349 	optp->level = MIB2_IP;
19350 	optp->name = EXPER_IP_RTATTR;
19351 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19352 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19353 	    (int)optp->level, (int)optp->name, (int)optp->len));
19354 	if (optp->len == 0)
19355 		freemsg(mp4ctl);
19356 	else
19357 		qreply(q, mp4ctl);
19358 
19359 	return (mp2ctl);
19360 }
19361 
19362 /*
19363  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19364  * ipv6NetToMediaEntryTable in an NDP walk.
19365  */
19366 static mblk_t *
19367 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
19368     ip_stack_t *ipst)
19369 {
19370 	struct opthdr	*optp;
19371 	mblk_t		*mp2ctl;	/* Returned */
19372 	mblk_t		*mp3ctl;	/* nettomedia */
19373 	mblk_t		*mp4ctl;	/* routeattrs */
19374 	iproutedata_t	ird;
19375 	zoneid_t	zoneid;
19376 
19377 	/*
19378 	 * make copies of the original message
19379 	 *	- mp2ctl is returned unchanged to the caller for his use
19380 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19381 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19382 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19383 	 */
19384 	mp2ctl = copymsg(mpctl);
19385 	mp3ctl = copymsg(mpctl);
19386 	mp4ctl = copymsg(mpctl);
19387 	if (mp3ctl == NULL || mp4ctl == NULL) {
19388 		freemsg(mp4ctl);
19389 		freemsg(mp3ctl);
19390 		freemsg(mp2ctl);
19391 		freemsg(mpctl);
19392 		return (NULL);
19393 	}
19394 
19395 	bzero(&ird, sizeof (ird));
19396 
19397 	ird.ird_route.lp_head = mpctl->b_cont;
19398 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19399 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19400 	/*
19401 	 * If the level has been set the special EXPER_IP_AND_TESTHIDDEN
19402 	 * value, then also include IRE_MARK_TESTHIDDEN IREs.  This is
19403 	 * intended a temporary solution until a proper MIB API is provided
19404 	 * that provides complete filtering/caller-opt-in.
19405 	 */
19406 	if (level == EXPER_IP_AND_TESTHIDDEN)
19407 		ird.ird_flags |= IRD_REPORT_TESTHIDDEN;
19408 
19409 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19410 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19411 
19412 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19413 	optp->level = MIB2_IP6;
19414 	optp->name = MIB2_IP6_ROUTE;
19415 	optp->len = msgdsize(ird.ird_route.lp_head);
19416 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19417 	    (int)optp->level, (int)optp->name, (int)optp->len));
19418 	qreply(q, mpctl);
19419 
19420 	/* ipv6NetToMediaEntryTable in mp3ctl */
19421 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19422 
19423 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19424 	optp->level = MIB2_IP6;
19425 	optp->name = MIB2_IP6_MEDIA;
19426 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19427 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19428 	    (int)optp->level, (int)optp->name, (int)optp->len));
19429 	qreply(q, mp3ctl);
19430 
19431 	/* ipv6RouteAttributeTable in mp4ctl */
19432 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19433 	optp->level = MIB2_IP6;
19434 	optp->name = EXPER_IP_RTATTR;
19435 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19436 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19437 	    (int)optp->level, (int)optp->name, (int)optp->len));
19438 	if (optp->len == 0)
19439 		freemsg(mp4ctl);
19440 	else
19441 		qreply(q, mp4ctl);
19442 
19443 	return (mp2ctl);
19444 }
19445 
19446 /*
19447  * IPv6 mib: One per ill
19448  */
19449 static mblk_t *
19450 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19451 {
19452 	struct opthdr		*optp;
19453 	mblk_t			*mp2ctl;
19454 	ill_t			*ill;
19455 	ill_walk_context_t	ctx;
19456 	mblk_t			*mp_tail = NULL;
19457 
19458 	/*
19459 	 * Make a copy of the original message
19460 	 */
19461 	mp2ctl = copymsg(mpctl);
19462 
19463 	/* fixed length IPv6 structure ... */
19464 
19465 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19466 	optp->level = MIB2_IP6;
19467 	optp->name = 0;
19468 	/* Include "unknown interface" ip6_mib */
19469 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19470 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19471 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19472 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19473 	    ipst->ips_ipv6_forward ? 1 : 2);
19474 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19475 	    ipst->ips_ipv6_def_hops);
19476 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19477 	    sizeof (mib2_ipIfStatsEntry_t));
19478 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19479 	    sizeof (mib2_ipv6AddrEntry_t));
19480 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19481 	    sizeof (mib2_ipv6RouteEntry_t));
19482 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19483 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19484 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19485 	    sizeof (ipv6_member_t));
19486 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19487 	    sizeof (ipv6_grpsrc_t));
19488 
19489 	/*
19490 	 * Synchronize 64- and 32-bit counters
19491 	 */
19492 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19493 	    ipIfStatsHCInReceives);
19494 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19495 	    ipIfStatsHCInDelivers);
19496 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19497 	    ipIfStatsHCOutRequests);
19498 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19499 	    ipIfStatsHCOutForwDatagrams);
19500 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19501 	    ipIfStatsHCOutMcastPkts);
19502 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19503 	    ipIfStatsHCInMcastPkts);
19504 
19505 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19506 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19507 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19508 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19509 	}
19510 
19511 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19512 	ill = ILL_START_WALK_V6(&ctx, ipst);
19513 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19514 		ill->ill_ip_mib->ipIfStatsIfIndex =
19515 		    ill->ill_phyint->phyint_ifindex;
19516 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19517 		    ipst->ips_ipv6_forward ? 1 : 2);
19518 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19519 		    ill->ill_max_hops);
19520 
19521 		/*
19522 		 * Synchronize 64- and 32-bit counters
19523 		 */
19524 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19525 		    ipIfStatsHCInReceives);
19526 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19527 		    ipIfStatsHCInDelivers);
19528 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19529 		    ipIfStatsHCOutRequests);
19530 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19531 		    ipIfStatsHCOutForwDatagrams);
19532 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19533 		    ipIfStatsHCOutMcastPkts);
19534 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19535 		    ipIfStatsHCInMcastPkts);
19536 
19537 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19538 		    (char *)ill->ill_ip_mib,
19539 		    (int)sizeof (*ill->ill_ip_mib))) {
19540 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19541 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19542 		}
19543 	}
19544 	rw_exit(&ipst->ips_ill_g_lock);
19545 
19546 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19547 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19548 	    (int)optp->level, (int)optp->name, (int)optp->len));
19549 	qreply(q, mpctl);
19550 	return (mp2ctl);
19551 }
19552 
19553 /*
19554  * ICMPv6 mib: One per ill
19555  */
19556 static mblk_t *
19557 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19558 {
19559 	struct opthdr		*optp;
19560 	mblk_t			*mp2ctl;
19561 	ill_t			*ill;
19562 	ill_walk_context_t	ctx;
19563 	mblk_t			*mp_tail = NULL;
19564 	/*
19565 	 * Make a copy of the original message
19566 	 */
19567 	mp2ctl = copymsg(mpctl);
19568 
19569 	/* fixed length ICMPv6 structure ... */
19570 
19571 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19572 	optp->level = MIB2_ICMP6;
19573 	optp->name = 0;
19574 	/* Include "unknown interface" icmp6_mib */
19575 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19576 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19577 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19578 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19579 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19580 	    (char *)&ipst->ips_icmp6_mib,
19581 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19582 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19583 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19584 	}
19585 
19586 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19587 	ill = ILL_START_WALK_V6(&ctx, ipst);
19588 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19589 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19590 		    ill->ill_phyint->phyint_ifindex;
19591 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19592 		    (char *)ill->ill_icmp6_mib,
19593 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19594 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19595 			    "%u bytes\n",
19596 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19597 		}
19598 	}
19599 	rw_exit(&ipst->ips_ill_g_lock);
19600 
19601 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19602 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19603 	    (int)optp->level, (int)optp->name, (int)optp->len));
19604 	qreply(q, mpctl);
19605 	return (mp2ctl);
19606 }
19607 
19608 /*
19609  * ire_walk routine to create both ipRouteEntryTable and
19610  * ipRouteAttributeTable in one IRE walk
19611  */
19612 static void
19613 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19614 {
19615 	ill_t				*ill;
19616 	ipif_t				*ipif;
19617 	mib2_ipRouteEntry_t		*re;
19618 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19619 	ipaddr_t			gw_addr;
19620 	tsol_ire_gw_secattr_t		*attrp;
19621 	tsol_gc_t			*gc = NULL;
19622 	tsol_gcgrp_t			*gcgrp = NULL;
19623 	uint_t				sacnt = 0;
19624 	int				i;
19625 
19626 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19627 
19628 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19629 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19630 		return;
19631 	}
19632 
19633 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19634 		return;
19635 
19636 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19637 		mutex_enter(&attrp->igsa_lock);
19638 		if ((gc = attrp->igsa_gc) != NULL) {
19639 			gcgrp = gc->gc_grp;
19640 			ASSERT(gcgrp != NULL);
19641 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19642 			sacnt = 1;
19643 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19644 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19645 			gc = gcgrp->gcgrp_head;
19646 			sacnt = gcgrp->gcgrp_count;
19647 		}
19648 		mutex_exit(&attrp->igsa_lock);
19649 
19650 		/* do nothing if there's no gc to report */
19651 		if (gc == NULL) {
19652 			ASSERT(sacnt == 0);
19653 			if (gcgrp != NULL) {
19654 				/* we might as well drop the lock now */
19655 				rw_exit(&gcgrp->gcgrp_rwlock);
19656 				gcgrp = NULL;
19657 			}
19658 			attrp = NULL;
19659 		}
19660 
19661 		ASSERT(gc == NULL || (gcgrp != NULL &&
19662 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19663 	}
19664 	ASSERT(sacnt == 0 || gc != NULL);
19665 
19666 	if (sacnt != 0 &&
19667 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19668 		kmem_free(re, sizeof (*re));
19669 		rw_exit(&gcgrp->gcgrp_rwlock);
19670 		return;
19671 	}
19672 
19673 	/*
19674 	 * Return all IRE types for route table... let caller pick and choose
19675 	 */
19676 	re->ipRouteDest = ire->ire_addr;
19677 	ipif = ire->ire_ipif;
19678 	re->ipRouteIfIndex.o_length = 0;
19679 	if (ire->ire_type == IRE_CACHE) {
19680 		ill = (ill_t *)ire->ire_stq->q_ptr;
19681 		re->ipRouteIfIndex.o_length =
19682 		    ill->ill_name_length == 0 ? 0 :
19683 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19684 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19685 		    re->ipRouteIfIndex.o_length);
19686 	} else if (ipif != NULL) {
19687 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19688 		re->ipRouteIfIndex.o_length =
19689 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19690 	}
19691 	re->ipRouteMetric1 = -1;
19692 	re->ipRouteMetric2 = -1;
19693 	re->ipRouteMetric3 = -1;
19694 	re->ipRouteMetric4 = -1;
19695 
19696 	gw_addr = ire->ire_gateway_addr;
19697 
19698 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19699 		re->ipRouteNextHop = ire->ire_src_addr;
19700 	else
19701 		re->ipRouteNextHop = gw_addr;
19702 	/* indirect(4), direct(3), or invalid(2) */
19703 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19704 		re->ipRouteType = 2;
19705 	else
19706 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19707 	re->ipRouteProto = -1;
19708 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19709 	re->ipRouteMask = ire->ire_mask;
19710 	re->ipRouteMetric5 = -1;
19711 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19712 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19713 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19714 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19715 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19716 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19717 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19718 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19719 
19720 	if (ire->ire_flags & RTF_DYNAMIC) {
19721 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19722 	} else {
19723 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19724 	}
19725 
19726 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19727 	    (char *)re, (int)sizeof (*re))) {
19728 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19729 		    (uint_t)sizeof (*re)));
19730 	}
19731 
19732 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19733 		iaeptr->iae_routeidx = ird->ird_idx;
19734 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19735 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19736 	}
19737 
19738 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19739 	    (char *)iae, sacnt * sizeof (*iae))) {
19740 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19741 		    (unsigned)(sacnt * sizeof (*iae))));
19742 	}
19743 
19744 	/* bump route index for next pass */
19745 	ird->ird_idx++;
19746 
19747 	kmem_free(re, sizeof (*re));
19748 	if (sacnt != 0)
19749 		kmem_free(iae, sacnt * sizeof (*iae));
19750 
19751 	if (gcgrp != NULL)
19752 		rw_exit(&gcgrp->gcgrp_rwlock);
19753 }
19754 
19755 /*
19756  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19757  */
19758 static void
19759 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19760 {
19761 	ill_t				*ill;
19762 	ipif_t				*ipif;
19763 	mib2_ipv6RouteEntry_t		*re;
19764 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19765 	in6_addr_t			gw_addr_v6;
19766 	tsol_ire_gw_secattr_t		*attrp;
19767 	tsol_gc_t			*gc = NULL;
19768 	tsol_gcgrp_t			*gcgrp = NULL;
19769 	uint_t				sacnt = 0;
19770 	int				i;
19771 
19772 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19773 
19774 	if (!(ird->ird_flags & IRD_REPORT_TESTHIDDEN) &&
19775 	    ire->ire_marks & IRE_MARK_TESTHIDDEN) {
19776 		return;
19777 	}
19778 
19779 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19780 		return;
19781 
19782 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19783 		mutex_enter(&attrp->igsa_lock);
19784 		if ((gc = attrp->igsa_gc) != NULL) {
19785 			gcgrp = gc->gc_grp;
19786 			ASSERT(gcgrp != NULL);
19787 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19788 			sacnt = 1;
19789 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19790 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19791 			gc = gcgrp->gcgrp_head;
19792 			sacnt = gcgrp->gcgrp_count;
19793 		}
19794 		mutex_exit(&attrp->igsa_lock);
19795 
19796 		/* do nothing if there's no gc to report */
19797 		if (gc == NULL) {
19798 			ASSERT(sacnt == 0);
19799 			if (gcgrp != NULL) {
19800 				/* we might as well drop the lock now */
19801 				rw_exit(&gcgrp->gcgrp_rwlock);
19802 				gcgrp = NULL;
19803 			}
19804 			attrp = NULL;
19805 		}
19806 
19807 		ASSERT(gc == NULL || (gcgrp != NULL &&
19808 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19809 	}
19810 	ASSERT(sacnt == 0 || gc != NULL);
19811 
19812 	if (sacnt != 0 &&
19813 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19814 		kmem_free(re, sizeof (*re));
19815 		rw_exit(&gcgrp->gcgrp_rwlock);
19816 		return;
19817 	}
19818 
19819 	/*
19820 	 * Return all IRE types for route table... let caller pick and choose
19821 	 */
19822 	re->ipv6RouteDest = ire->ire_addr_v6;
19823 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19824 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19825 	re->ipv6RouteIfIndex.o_length = 0;
19826 	ipif = ire->ire_ipif;
19827 	if (ire->ire_type == IRE_CACHE) {
19828 		ill = (ill_t *)ire->ire_stq->q_ptr;
19829 		re->ipv6RouteIfIndex.o_length =
19830 		    ill->ill_name_length == 0 ? 0 :
19831 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19832 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19833 		    re->ipv6RouteIfIndex.o_length);
19834 	} else if (ipif != NULL) {
19835 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19836 		re->ipv6RouteIfIndex.o_length =
19837 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19838 	}
19839 
19840 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19841 
19842 	mutex_enter(&ire->ire_lock);
19843 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19844 	mutex_exit(&ire->ire_lock);
19845 
19846 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19847 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19848 	else
19849 		re->ipv6RouteNextHop = gw_addr_v6;
19850 
19851 	/* remote(4), local(3), or discard(2) */
19852 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19853 		re->ipv6RouteType = 2;
19854 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19855 		re->ipv6RouteType = 3;
19856 	else
19857 		re->ipv6RouteType = 4;
19858 
19859 	re->ipv6RouteProtocol	= -1;
19860 	re->ipv6RoutePolicy	= 0;
19861 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19862 	re->ipv6RouteNextHopRDI	= 0;
19863 	re->ipv6RouteWeight	= 0;
19864 	re->ipv6RouteMetric	= 0;
19865 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19866 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19867 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19868 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19869 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19870 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19871 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19872 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19873 
19874 	if (ire->ire_flags & RTF_DYNAMIC) {
19875 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19876 	} else {
19877 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19878 	}
19879 
19880 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19881 	    (char *)re, (int)sizeof (*re))) {
19882 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19883 		    (uint_t)sizeof (*re)));
19884 	}
19885 
19886 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19887 		iaeptr->iae_routeidx = ird->ird_idx;
19888 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19889 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19890 	}
19891 
19892 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19893 	    (char *)iae, sacnt * sizeof (*iae))) {
19894 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19895 		    (unsigned)(sacnt * sizeof (*iae))));
19896 	}
19897 
19898 	/* bump route index for next pass */
19899 	ird->ird_idx++;
19900 
19901 	kmem_free(re, sizeof (*re));
19902 	if (sacnt != 0)
19903 		kmem_free(iae, sacnt * sizeof (*iae));
19904 
19905 	if (gcgrp != NULL)
19906 		rw_exit(&gcgrp->gcgrp_rwlock);
19907 }
19908 
19909 /*
19910  * ndp_walk routine to create ipv6NetToMediaEntryTable
19911  */
19912 static int
19913 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19914 {
19915 	ill_t				*ill;
19916 	mib2_ipv6NetToMediaEntry_t	ntme;
19917 	dl_unitdata_req_t		*dl;
19918 
19919 	ill = nce->nce_ill;
19920 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19921 		return (0);
19922 
19923 	/*
19924 	 * Neighbor cache entry attached to IRE with on-link
19925 	 * destination.
19926 	 */
19927 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19928 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19929 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19930 	    (nce->nce_res_mp != NULL)) {
19931 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19932 		ntme.ipv6NetToMediaPhysAddress.o_length =
19933 		    dl->dl_dest_addr_length;
19934 	} else {
19935 		ntme.ipv6NetToMediaPhysAddress.o_length =
19936 		    ill->ill_phys_addr_length;
19937 	}
19938 	if (nce->nce_res_mp != NULL) {
19939 		bcopy((char *)nce->nce_res_mp->b_rptr +
19940 		    NCE_LL_ADDR_OFFSET(ill),
19941 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19942 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19943 	} else {
19944 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19945 		    ill->ill_phys_addr_length);
19946 	}
19947 	/*
19948 	 * Note: Returns ND_* states. Should be:
19949 	 * reachable(1), stale(2), delay(3), probe(4),
19950 	 * invalid(5), unknown(6)
19951 	 */
19952 	ntme.ipv6NetToMediaState = nce->nce_state;
19953 	ntme.ipv6NetToMediaLastUpdated = 0;
19954 
19955 	/* other(1), dynamic(2), static(3), local(4) */
19956 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19957 		ntme.ipv6NetToMediaType = 4;
19958 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19959 		ntme.ipv6NetToMediaType = 1;
19960 	} else {
19961 		ntme.ipv6NetToMediaType = 2;
19962 	}
19963 
19964 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19965 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19966 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19967 		    (uint_t)sizeof (ntme)));
19968 	}
19969 	return (0);
19970 }
19971 
19972 /*
19973  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19974  */
19975 /* ARGSUSED */
19976 int
19977 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19978 {
19979 	switch (level) {
19980 	case MIB2_IP:
19981 	case MIB2_ICMP:
19982 		switch (name) {
19983 		default:
19984 			break;
19985 		}
19986 		return (1);
19987 	default:
19988 		return (1);
19989 	}
19990 }
19991 
19992 /*
19993  * When there exists both a 64- and 32-bit counter of a particular type
19994  * (i.e., InReceives), only the 64-bit counters are added.
19995  */
19996 void
19997 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19998 {
19999 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
20000 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
20001 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
20002 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
20003 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
20004 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
20005 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
20006 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
20007 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
20008 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
20009 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
20010 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
20011 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
20012 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
20013 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
20014 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
20015 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
20016 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
20017 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
20018 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
20019 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
20020 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
20021 	    o2->ipIfStatsInWrongIPVersion);
20022 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
20023 	    o2->ipIfStatsInWrongIPVersion);
20024 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
20025 	    o2->ipIfStatsOutSwitchIPVersion);
20026 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
20027 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
20028 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
20029 	    o2->ipIfStatsHCInForwDatagrams);
20030 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
20031 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
20032 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
20033 	    o2->ipIfStatsHCOutForwDatagrams);
20034 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
20035 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
20036 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
20037 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
20038 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
20039 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
20040 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
20041 	    o2->ipIfStatsHCOutMcastOctets);
20042 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
20043 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
20044 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
20045 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
20046 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
20047 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
20048 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
20049 }
20050 
20051 void
20052 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
20053 {
20054 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
20055 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
20056 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
20057 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
20058 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
20059 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
20060 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20061 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20062 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20063 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20064 	    o2->ipv6IfIcmpInRouterSolicits);
20065 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20066 	    o2->ipv6IfIcmpInRouterAdvertisements);
20067 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20068 	    o2->ipv6IfIcmpInNeighborSolicits);
20069 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20070 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20071 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20072 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20073 	    o2->ipv6IfIcmpInGroupMembQueries);
20074 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20075 	    o2->ipv6IfIcmpInGroupMembResponses);
20076 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20077 	    o2->ipv6IfIcmpInGroupMembReductions);
20078 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20079 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20080 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20081 	    o2->ipv6IfIcmpOutDestUnreachs);
20082 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20083 	    o2->ipv6IfIcmpOutAdminProhibs);
20084 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20085 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20086 	    o2->ipv6IfIcmpOutParmProblems);
20087 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20088 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20089 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20090 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20091 	    o2->ipv6IfIcmpOutRouterSolicits);
20092 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20093 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20094 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20095 	    o2->ipv6IfIcmpOutNeighborSolicits);
20096 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20097 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20098 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20099 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20100 	    o2->ipv6IfIcmpOutGroupMembQueries);
20101 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20102 	    o2->ipv6IfIcmpOutGroupMembResponses);
20103 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20104 	    o2->ipv6IfIcmpOutGroupMembReductions);
20105 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20106 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20107 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20108 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20109 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20110 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20111 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20112 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20113 	    o2->ipv6IfIcmpInGroupMembTotal);
20114 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20115 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20116 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20117 	    o2->ipv6IfIcmpInGroupMembBadReports);
20118 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20119 	    o2->ipv6IfIcmpInGroupMembOurReports);
20120 }
20121 
20122 /*
20123  * Called before the options are updated to check if this packet will
20124  * be source routed from here.
20125  * This routine assumes that the options are well formed i.e. that they
20126  * have already been checked.
20127  */
20128 static boolean_t
20129 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20130 {
20131 	ipoptp_t	opts;
20132 	uchar_t		*opt;
20133 	uint8_t		optval;
20134 	uint8_t		optlen;
20135 	ipaddr_t	dst;
20136 	ire_t		*ire;
20137 
20138 	if (IS_SIMPLE_IPH(ipha)) {
20139 		ip2dbg(("not source routed\n"));
20140 		return (B_FALSE);
20141 	}
20142 	dst = ipha->ipha_dst;
20143 	for (optval = ipoptp_first(&opts, ipha);
20144 	    optval != IPOPT_EOL;
20145 	    optval = ipoptp_next(&opts)) {
20146 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20147 		opt = opts.ipoptp_cur;
20148 		optlen = opts.ipoptp_len;
20149 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20150 		    optval, optlen));
20151 		switch (optval) {
20152 			uint32_t off;
20153 		case IPOPT_SSRR:
20154 		case IPOPT_LSRR:
20155 			/*
20156 			 * If dst is one of our addresses and there are some
20157 			 * entries left in the source route return (true).
20158 			 */
20159 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20160 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20161 			if (ire == NULL) {
20162 				ip2dbg(("ip_source_routed: not next"
20163 				    " source route 0x%x\n",
20164 				    ntohl(dst)));
20165 				return (B_FALSE);
20166 			}
20167 			ire_refrele(ire);
20168 			off = opt[IPOPT_OFFSET];
20169 			off--;
20170 			if (optlen < IP_ADDR_LEN ||
20171 			    off > optlen - IP_ADDR_LEN) {
20172 				/* End of source route */
20173 				ip1dbg(("ip_source_routed: end of SR\n"));
20174 				return (B_FALSE);
20175 			}
20176 			return (B_TRUE);
20177 		}
20178 	}
20179 	ip2dbg(("not source routed\n"));
20180 	return (B_FALSE);
20181 }
20182 
20183 /*
20184  * Check if the packet contains any source route.
20185  */
20186 static boolean_t
20187 ip_source_route_included(ipha_t *ipha)
20188 {
20189 	ipoptp_t	opts;
20190 	uint8_t		optval;
20191 
20192 	if (IS_SIMPLE_IPH(ipha))
20193 		return (B_FALSE);
20194 	for (optval = ipoptp_first(&opts, ipha);
20195 	    optval != IPOPT_EOL;
20196 	    optval = ipoptp_next(&opts)) {
20197 		switch (optval) {
20198 		case IPOPT_SSRR:
20199 		case IPOPT_LSRR:
20200 			return (B_TRUE);
20201 		}
20202 	}
20203 	return (B_FALSE);
20204 }
20205 
20206 /*
20207  * Called when the IRE expiration timer fires.
20208  */
20209 void
20210 ip_trash_timer_expire(void *args)
20211 {
20212 	int			flush_flag = 0;
20213 	ire_expire_arg_t	iea;
20214 	ip_stack_t		*ipst = (ip_stack_t *)args;
20215 
20216 	iea.iea_ipst = ipst;	/* No netstack_hold */
20217 
20218 	/*
20219 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20220 	 * This lock makes sure that a new invocation of this function
20221 	 * that occurs due to an almost immediate timer firing will not
20222 	 * progress beyond this point until the current invocation is done
20223 	 */
20224 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20225 	ipst->ips_ip_ire_expire_id = 0;
20226 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20227 
20228 	/* Periodic timer */
20229 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20230 	    ipst->ips_ip_ire_arp_interval) {
20231 		/*
20232 		 * Remove all IRE_CACHE entries since they might
20233 		 * contain arp information.
20234 		 */
20235 		flush_flag |= FLUSH_ARP_TIME;
20236 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20237 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20238 	}
20239 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20240 	    ipst->ips_ip_ire_redir_interval) {
20241 		/* Remove all redirects */
20242 		flush_flag |= FLUSH_REDIRECT_TIME;
20243 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20244 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20245 	}
20246 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20247 	    ipst->ips_ip_ire_pathmtu_interval) {
20248 		/* Increase path mtu */
20249 		flush_flag |= FLUSH_MTU_TIME;
20250 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20251 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20252 	}
20253 
20254 	/*
20255 	 * Optimize for the case when there are no redirects in the
20256 	 * ftable, that is, no need to walk the ftable in that case.
20257 	 */
20258 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20259 		iea.iea_flush_flag = flush_flag;
20260 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20261 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20262 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20263 		    NULL, ALL_ZONES, ipst);
20264 	}
20265 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20266 	    ipst->ips_ip_redirect_cnt > 0) {
20267 		iea.iea_flush_flag = flush_flag;
20268 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20269 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20270 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20271 	}
20272 	if (flush_flag & FLUSH_MTU_TIME) {
20273 		/*
20274 		 * Walk all IPv6 IRE's and update them
20275 		 * Note that ARP and redirect timers are not
20276 		 * needed since NUD handles stale entries.
20277 		 */
20278 		flush_flag = FLUSH_MTU_TIME;
20279 		iea.iea_flush_flag = flush_flag;
20280 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20281 		    ALL_ZONES, ipst);
20282 	}
20283 
20284 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20285 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20286 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20287 
20288 	/*
20289 	 * Hold the lock to serialize timeout calls and prevent
20290 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20291 	 * for the timer to fire and a new invocation of this function
20292 	 * to start before the return value of timeout has been stored
20293 	 * in ip_ire_expire_id by the current invocation.
20294 	 */
20295 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20296 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20297 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20298 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20299 }
20300 
20301 /*
20302  * Called by the memory allocator subsystem directly, when the system
20303  * is running low on memory.
20304  */
20305 /* ARGSUSED */
20306 void
20307 ip_trash_ire_reclaim(void *args)
20308 {
20309 	netstack_handle_t nh;
20310 	netstack_t *ns;
20311 
20312 	netstack_next_init(&nh);
20313 	while ((ns = netstack_next(&nh)) != NULL) {
20314 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20315 		netstack_rele(ns);
20316 	}
20317 	netstack_next_fini(&nh);
20318 }
20319 
20320 static void
20321 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20322 {
20323 	ire_cache_count_t icc;
20324 	ire_cache_reclaim_t icr;
20325 	ncc_cache_count_t ncc;
20326 	nce_cache_reclaim_t ncr;
20327 	uint_t delete_cnt;
20328 	/*
20329 	 * Memory reclaim call back.
20330 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20331 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20332 	 * entries, determine what fraction to free for
20333 	 * each category of IRE_CACHE entries giving absolute priority
20334 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20335 	 * entry will be freed unless all offlink entries are freed).
20336 	 */
20337 	icc.icc_total = 0;
20338 	icc.icc_unused = 0;
20339 	icc.icc_offlink = 0;
20340 	icc.icc_pmtu = 0;
20341 	icc.icc_onlink = 0;
20342 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20343 
20344 	/*
20345 	 * Free NCEs for IPv6 like the onlink ires.
20346 	 */
20347 	ncc.ncc_total = 0;
20348 	ncc.ncc_host = 0;
20349 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20350 
20351 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20352 	    icc.icc_pmtu + icc.icc_onlink);
20353 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20354 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20355 	if (delete_cnt == 0)
20356 		return;
20357 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20358 	/* Always delete all unused offlink entries */
20359 	icr.icr_ipst = ipst;
20360 	icr.icr_unused = 1;
20361 	if (delete_cnt <= icc.icc_unused) {
20362 		/*
20363 		 * Only need to free unused entries.  In other words,
20364 		 * there are enough unused entries to free to meet our
20365 		 * target number of freed ire cache entries.
20366 		 */
20367 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20368 		ncr.ncr_host = 0;
20369 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20370 		/*
20371 		 * Only need to free unused entries, plus a fraction of offlink
20372 		 * entries.  It follows from the first if statement that
20373 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20374 		 */
20375 		delete_cnt -= icc.icc_unused;
20376 		/* Round up # deleted by truncating fraction */
20377 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20378 		icr.icr_pmtu = icr.icr_onlink = 0;
20379 		ncr.ncr_host = 0;
20380 	} else if (delete_cnt <=
20381 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20382 		/*
20383 		 * Free all unused and offlink entries, plus a fraction of
20384 		 * pmtu entries.  It follows from the previous if statement
20385 		 * that icc_pmtu is non-zero, and that
20386 		 * delete_cnt != icc_unused + icc_offlink.
20387 		 */
20388 		icr.icr_offlink = 1;
20389 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20390 		/* Round up # deleted by truncating fraction */
20391 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20392 		icr.icr_onlink = 0;
20393 		ncr.ncr_host = 0;
20394 	} else {
20395 		/*
20396 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20397 		 * of onlink entries.  If we're here, then we know that
20398 		 * icc_onlink is non-zero, and that
20399 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20400 		 */
20401 		icr.icr_offlink = icr.icr_pmtu = 1;
20402 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20403 		    icc.icc_pmtu;
20404 		/* Round up # deleted by truncating fraction */
20405 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20406 		/* Using the same delete fraction as for onlink IREs */
20407 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20408 	}
20409 #ifdef DEBUG
20410 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20411 	    "fractions %d/%d/%d/%d\n",
20412 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20413 	    icc.icc_unused, icc.icc_offlink,
20414 	    icc.icc_pmtu, icc.icc_onlink,
20415 	    icr.icr_unused, icr.icr_offlink,
20416 	    icr.icr_pmtu, icr.icr_onlink));
20417 #endif
20418 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20419 	if (ncr.ncr_host != 0)
20420 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20421 		    (uchar_t *)&ncr, ipst);
20422 #ifdef DEBUG
20423 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20424 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20425 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20426 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20427 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20428 	    icc.icc_pmtu, icc.icc_onlink));
20429 #endif
20430 }
20431 
20432 /*
20433  * ip_unbind is called when a copy of an unbind request is received from the
20434  * upper level protocol.  We remove this conn from any fanout hash list it is
20435  * on, and zero out the bind information.  No reply is expected up above.
20436  */
20437 void
20438 ip_unbind(conn_t *connp)
20439 {
20440 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20441 
20442 	if (is_system_labeled() && connp->conn_anon_port) {
20443 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20444 		    connp->conn_mlp_type, connp->conn_ulp,
20445 		    ntohs(connp->conn_lport), B_FALSE);
20446 		connp->conn_anon_port = 0;
20447 	}
20448 	connp->conn_mlp_type = mlptSingle;
20449 
20450 	ipcl_hash_remove(connp);
20451 
20452 }
20453 
20454 /*
20455  * Write side put procedure.  Outbound data, IOCTLs, responses from
20456  * resolvers, etc, come down through here.
20457  *
20458  * arg2 is always a queue_t *.
20459  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20460  * the zoneid.
20461  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20462  */
20463 void
20464 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20465 {
20466 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20467 }
20468 
20469 void
20470 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20471     ip_opt_info_t *infop)
20472 {
20473 	conn_t		*connp = NULL;
20474 	queue_t		*q = (queue_t *)arg2;
20475 	ipha_t		*ipha;
20476 #define	rptr	((uchar_t *)ipha)
20477 	ire_t		*ire = NULL;
20478 	ire_t		*sctp_ire = NULL;
20479 	uint32_t	v_hlen_tos_len;
20480 	ipaddr_t	dst;
20481 	mblk_t		*first_mp = NULL;
20482 	boolean_t	mctl_present;
20483 	ipsec_out_t	*io;
20484 	int		match_flags;
20485 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20486 	ipif_t		*dst_ipif;
20487 	boolean_t	multirt_need_resolve = B_FALSE;
20488 	mblk_t		*copy_mp = NULL;
20489 	int		err = 0;
20490 	zoneid_t	zoneid;
20491 	boolean_t	need_decref = B_FALSE;
20492 	boolean_t	ignore_dontroute = B_FALSE;
20493 	boolean_t	ignore_nexthop = B_FALSE;
20494 	boolean_t	ip_nexthop = B_FALSE;
20495 	ipaddr_t	nexthop_addr;
20496 	ip_stack_t	*ipst;
20497 
20498 #ifdef	_BIG_ENDIAN
20499 #define	V_HLEN	(v_hlen_tos_len >> 24)
20500 #else
20501 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20502 #endif
20503 
20504 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20505 	    "ip_wput_start: q %p", q);
20506 
20507 	/*
20508 	 * ip_wput fast path
20509 	 */
20510 
20511 	/* is packet from ARP ? */
20512 	if (q->q_next != NULL) {
20513 		zoneid = (zoneid_t)(uintptr_t)arg;
20514 		goto qnext;
20515 	}
20516 
20517 	connp = (conn_t *)arg;
20518 	ASSERT(connp != NULL);
20519 	zoneid = connp->conn_zoneid;
20520 	ipst = connp->conn_netstack->netstack_ip;
20521 	ASSERT(ipst != NULL);
20522 
20523 	/* is queue flow controlled? */
20524 	if ((q->q_first != NULL || connp->conn_draining) &&
20525 	    (caller == IP_WPUT)) {
20526 		ASSERT(!need_decref);
20527 		ASSERT(!IP_FLOW_CONTROLLED_ULP(connp->conn_ulp));
20528 		(void) putq(q, mp);
20529 		return;
20530 	}
20531 
20532 	/* Multidata transmit? */
20533 	if (DB_TYPE(mp) == M_MULTIDATA) {
20534 		/*
20535 		 * We should never get here, since all Multidata messages
20536 		 * originating from tcp should have been directed over to
20537 		 * tcp_multisend() in the first place.
20538 		 */
20539 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20540 		freemsg(mp);
20541 		return;
20542 	} else if (DB_TYPE(mp) != M_DATA)
20543 		goto notdata;
20544 
20545 	if (mp->b_flag & MSGHASREF) {
20546 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20547 		mp->b_flag &= ~MSGHASREF;
20548 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20549 		need_decref = B_TRUE;
20550 	}
20551 	ipha = (ipha_t *)mp->b_rptr;
20552 
20553 	/* is IP header non-aligned or mblk smaller than basic IP header */
20554 #ifndef SAFETY_BEFORE_SPEED
20555 	if (!OK_32PTR(rptr) ||
20556 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20557 		goto hdrtoosmall;
20558 #endif
20559 
20560 	ASSERT(OK_32PTR(ipha));
20561 
20562 	/*
20563 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20564 	 * wrong version, we'll catch it again in ip_output_v6.
20565 	 *
20566 	 * Note that this is *only* locally-generated output here, and never
20567 	 * forwarded data, and that we need to deal only with transports that
20568 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20569 	 * label.)
20570 	 */
20571 	if (is_system_labeled() &&
20572 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20573 	    !connp->conn_ulp_labeled) {
20574 		cred_t	*credp;
20575 		pid_t	pid;
20576 
20577 		credp = BEST_CRED(mp, connp, &pid);
20578 		err = tsol_check_label(credp, &mp,
20579 		    connp->conn_mac_exempt, ipst, pid);
20580 		ipha = (ipha_t *)mp->b_rptr;
20581 		if (err != 0) {
20582 			first_mp = mp;
20583 			if (err == EINVAL)
20584 				goto icmp_parameter_problem;
20585 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20586 			goto discard_pkt;
20587 		}
20588 	}
20589 
20590 	ASSERT(infop != NULL);
20591 
20592 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20593 		/*
20594 		 * IP_PKTINFO ancillary option is present.
20595 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20596 		 * allows using address of any zone as the source address.
20597 		 */
20598 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20599 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20600 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20601 		if (ire == NULL)
20602 			goto drop_pkt;
20603 		ire_refrele(ire);
20604 		ire = NULL;
20605 	}
20606 
20607 	/*
20608 	 * IP_BOUND_IF has precedence over the ill index passed in IP_PKTINFO.
20609 	 */
20610 	if (infop->ip_opt_ill_index != 0 && connp->conn_outgoing_ill == NULL) {
20611 		xmit_ill = ill_lookup_on_ifindex(infop->ip_opt_ill_index,
20612 		    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20613 
20614 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20615 			goto drop_pkt;
20616 		/*
20617 		 * check that there is an ipif belonging
20618 		 * to our zone. IPCL_ZONEID is not used because
20619 		 * IP_ALLZONES option is valid only when the ill is
20620 		 * accessible from all zones i.e has a valid ipif in
20621 		 * all zones.
20622 		 */
20623 		if (!ipif_lookup_zoneid(xmit_ill, zoneid, 0, NULL)) {
20624 			goto drop_pkt;
20625 		}
20626 	}
20627 
20628 	/*
20629 	 * If there is a policy, try to attach an ipsec_out in
20630 	 * the front. At the end, first_mp either points to a
20631 	 * M_DATA message or IPSEC_OUT message linked to a
20632 	 * M_DATA message. We have to do it now as we might
20633 	 * lose the "conn" if we go through ip_newroute.
20634 	 */
20635 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20636 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20637 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20638 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20639 			if (need_decref)
20640 				CONN_DEC_REF(connp);
20641 			return;
20642 		} else {
20643 			ASSERT(mp->b_datap->db_type == M_CTL);
20644 			first_mp = mp;
20645 			mp = mp->b_cont;
20646 			mctl_present = B_TRUE;
20647 		}
20648 	} else {
20649 		first_mp = mp;
20650 		mctl_present = B_FALSE;
20651 	}
20652 
20653 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20654 
20655 	/* is wrong version or IP options present */
20656 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20657 		goto version_hdrlen_check;
20658 	dst = ipha->ipha_dst;
20659 
20660 	/* If IP_BOUND_IF has been set, use that ill. */
20661 	if (connp->conn_outgoing_ill != NULL) {
20662 		xmit_ill = conn_get_held_ill(connp,
20663 		    &connp->conn_outgoing_ill, &err);
20664 		if (err == ILL_LOOKUP_FAILED)
20665 			goto drop_pkt;
20666 
20667 		goto send_from_ill;
20668 	}
20669 
20670 	/* is packet multicast? */
20671 	if (CLASSD(dst))
20672 		goto multicast;
20673 
20674 	/*
20675 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20676 	 * takes precedence over conn_dontroute and conn_nexthop_set
20677 	 */
20678 	if (xmit_ill != NULL)
20679 		goto send_from_ill;
20680 
20681 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20682 		/*
20683 		 * If the destination is a broadcast, local, or loopback
20684 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20685 		 * standard path.
20686 		 */
20687 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20688 		if ((ire == NULL) || (ire->ire_type &
20689 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20690 			if (ire != NULL) {
20691 				ire_refrele(ire);
20692 				/* No more access to ire */
20693 				ire = NULL;
20694 			}
20695 			/*
20696 			 * bypass routing checks and go directly to interface.
20697 			 */
20698 			if (connp->conn_dontroute)
20699 				goto dontroute;
20700 
20701 			ASSERT(connp->conn_nexthop_set);
20702 			ip_nexthop = B_TRUE;
20703 			nexthop_addr = connp->conn_nexthop_v4;
20704 			goto send_from_ill;
20705 		}
20706 
20707 		/* Must be a broadcast, a loopback or a local ire */
20708 		ire_refrele(ire);
20709 		/* No more access to ire */
20710 		ire = NULL;
20711 	}
20712 
20713 	/*
20714 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20715 	 * this for the tcp global queue and listen end point
20716 	 * as it does not really have a real destination to
20717 	 * talk to.  This is also true for SCTP.
20718 	 */
20719 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20720 	    !connp->conn_fully_bound) {
20721 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20722 		if (ire == NULL)
20723 			goto noirefound;
20724 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20725 		    "ip_wput_end: q %p (%S)", q, "end");
20726 
20727 		/*
20728 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20729 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20730 		 */
20731 		if (ire->ire_flags & RTF_MULTIRT) {
20732 
20733 			/*
20734 			 * Force the TTL of multirouted packets if required.
20735 			 * The TTL of such packets is bounded by the
20736 			 * ip_multirt_ttl ndd variable.
20737 			 */
20738 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20739 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20740 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20741 				    "(was %d), dst 0x%08x\n",
20742 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20743 				    ntohl(ire->ire_addr)));
20744 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20745 			}
20746 			/*
20747 			 * We look at this point if there are pending
20748 			 * unresolved routes. ire_multirt_resolvable()
20749 			 * checks in O(n) that all IRE_OFFSUBNET ire
20750 			 * entries for the packet's destination and
20751 			 * flagged RTF_MULTIRT are currently resolved.
20752 			 * If some remain unresolved, we make a copy
20753 			 * of the current message. It will be used
20754 			 * to initiate additional route resolutions.
20755 			 */
20756 			multirt_need_resolve =
20757 			    ire_multirt_need_resolve(ire->ire_addr,
20758 			    msg_getlabel(first_mp), ipst);
20759 			ip2dbg(("ip_wput[TCP]: ire %p, "
20760 			    "multirt_need_resolve %d, first_mp %p\n",
20761 			    (void *)ire, multirt_need_resolve,
20762 			    (void *)first_mp));
20763 			if (multirt_need_resolve) {
20764 				copy_mp = copymsg(first_mp);
20765 				if (copy_mp != NULL) {
20766 					MULTIRT_DEBUG_TAG(copy_mp);
20767 				}
20768 			}
20769 		}
20770 
20771 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20772 
20773 		/*
20774 		 * Try to resolve another multiroute if
20775 		 * ire_multirt_need_resolve() deemed it necessary.
20776 		 */
20777 		if (copy_mp != NULL)
20778 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20779 		if (need_decref)
20780 			CONN_DEC_REF(connp);
20781 		return;
20782 	}
20783 
20784 	/*
20785 	 * Access to conn_ire_cache. (protected by conn_lock)
20786 	 *
20787 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20788 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20789 	 * send a packet or two with the IRE_CACHE that is going away.
20790 	 * Access to the ire requires an ire refhold on the ire prior to
20791 	 * its use since an interface unplumb thread may delete the cached
20792 	 * ire and release the refhold at any time.
20793 	 *
20794 	 * Caching an ire in the conn_ire_cache
20795 	 *
20796 	 * o Caching an ire pointer in the conn requires a strict check for
20797 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20798 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20799 	 * in the conn is done after making sure under the bucket lock that the
20800 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20801 	 * caching an ire after the unplumb thread has cleaned up the conn.
20802 	 * If the conn does not send a packet subsequently the unplumb thread
20803 	 * will be hanging waiting for the ire count to drop to zero.
20804 	 *
20805 	 * o We also need to atomically test for a null conn_ire_cache and
20806 	 * set the conn_ire_cache under the the protection of the conn_lock
20807 	 * to avoid races among concurrent threads trying to simultaneously
20808 	 * cache an ire in the conn_ire_cache.
20809 	 */
20810 	mutex_enter(&connp->conn_lock);
20811 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20812 
20813 	if (ire != NULL && ire->ire_addr == dst &&
20814 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20815 
20816 		IRE_REFHOLD(ire);
20817 		mutex_exit(&connp->conn_lock);
20818 
20819 	} else {
20820 		boolean_t cached = B_FALSE;
20821 		connp->conn_ire_cache = NULL;
20822 		mutex_exit(&connp->conn_lock);
20823 		/* Release the old ire */
20824 		if (ire != NULL && sctp_ire == NULL)
20825 			IRE_REFRELE_NOTR(ire);
20826 
20827 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
20828 		if (ire == NULL)
20829 			goto noirefound;
20830 		IRE_REFHOLD_NOTR(ire);
20831 
20832 		mutex_enter(&connp->conn_lock);
20833 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20834 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20835 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20836 				if (connp->conn_ulp == IPPROTO_TCP)
20837 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20838 				connp->conn_ire_cache = ire;
20839 				cached = B_TRUE;
20840 			}
20841 			rw_exit(&ire->ire_bucket->irb_lock);
20842 		}
20843 		mutex_exit(&connp->conn_lock);
20844 
20845 		/*
20846 		 * We can continue to use the ire but since it was
20847 		 * not cached, we should drop the extra reference.
20848 		 */
20849 		if (!cached)
20850 			IRE_REFRELE_NOTR(ire);
20851 	}
20852 
20853 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20854 	    "ip_wput_end: q %p (%S)", q, "end");
20855 
20856 	/*
20857 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20858 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20859 	 */
20860 	if (ire->ire_flags & RTF_MULTIRT) {
20861 		/*
20862 		 * Force the TTL of multirouted packets if required.
20863 		 * The TTL of such packets is bounded by the
20864 		 * ip_multirt_ttl ndd variable.
20865 		 */
20866 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20867 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20868 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20869 			    "(was %d), dst 0x%08x\n",
20870 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20871 			    ntohl(ire->ire_addr)));
20872 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20873 		}
20874 
20875 		/*
20876 		 * At this point, we check to see if there are any pending
20877 		 * unresolved routes. ire_multirt_resolvable()
20878 		 * checks in O(n) that all IRE_OFFSUBNET ire
20879 		 * entries for the packet's destination and
20880 		 * flagged RTF_MULTIRT are currently resolved.
20881 		 * If some remain unresolved, we make a copy
20882 		 * of the current message. It will be used
20883 		 * to initiate additional route resolutions.
20884 		 */
20885 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20886 		    msg_getlabel(first_mp), ipst);
20887 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20888 		    "multirt_need_resolve %d, first_mp %p\n",
20889 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20890 		if (multirt_need_resolve) {
20891 			copy_mp = copymsg(first_mp);
20892 			if (copy_mp != NULL) {
20893 				MULTIRT_DEBUG_TAG(copy_mp);
20894 			}
20895 		}
20896 	}
20897 
20898 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20899 
20900 	/*
20901 	 * Try to resolve another multiroute if
20902 	 * ire_multirt_resolvable() deemed it necessary
20903 	 */
20904 	if (copy_mp != NULL)
20905 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20906 	if (need_decref)
20907 		CONN_DEC_REF(connp);
20908 	return;
20909 
20910 qnext:
20911 	/*
20912 	 * Upper Level Protocols pass down complete IP datagrams
20913 	 * as M_DATA messages.	Everything else is a sideshow.
20914 	 *
20915 	 * 1) We could be re-entering ip_wput because of ip_neworute
20916 	 *    in which case we could have a IPSEC_OUT message. We
20917 	 *    need to pass through ip_wput like other datagrams and
20918 	 *    hence cannot branch to ip_wput_nondata.
20919 	 *
20920 	 * 2) ARP, AH, ESP, and other clients who are on the module
20921 	 *    instance of IP stream, give us something to deal with.
20922 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20923 	 *
20924 	 * 3) ICMP replies also could come here.
20925 	 */
20926 	ipst = ILLQ_TO_IPST(q);
20927 
20928 	if (DB_TYPE(mp) != M_DATA) {
20929 notdata:
20930 		if (DB_TYPE(mp) == M_CTL) {
20931 			/*
20932 			 * M_CTL messages are used by ARP, AH and ESP to
20933 			 * communicate with IP. We deal with IPSEC_IN and
20934 			 * IPSEC_OUT here. ip_wput_nondata handles other
20935 			 * cases.
20936 			 */
20937 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20938 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20939 				first_mp = mp->b_cont;
20940 				first_mp->b_flag &= ~MSGHASREF;
20941 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20942 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20943 				CONN_DEC_REF(connp);
20944 				connp = NULL;
20945 			}
20946 			if (ii->ipsec_info_type == IPSEC_IN) {
20947 				/*
20948 				 * Either this message goes back to
20949 				 * IPsec for further processing or to
20950 				 * ULP after policy checks.
20951 				 */
20952 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20953 				return;
20954 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20955 				io = (ipsec_out_t *)ii;
20956 				if (io->ipsec_out_proc_begin) {
20957 					/*
20958 					 * IPsec processing has already started.
20959 					 * Complete it.
20960 					 * IPQoS notes: We don't care what is
20961 					 * in ipsec_out_ill_index since this
20962 					 * won't be processed for IPQoS policies
20963 					 * in ipsec_out_process.
20964 					 */
20965 					ipsec_out_process(q, mp, NULL,
20966 					    io->ipsec_out_ill_index);
20967 					return;
20968 				} else {
20969 					connp = (q->q_next != NULL) ?
20970 					    NULL : Q_TO_CONN(q);
20971 					first_mp = mp;
20972 					mp = mp->b_cont;
20973 					mctl_present = B_TRUE;
20974 				}
20975 				zoneid = io->ipsec_out_zoneid;
20976 				ASSERT(zoneid != ALL_ZONES);
20977 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20978 				/*
20979 				 * It's an IPsec control message requesting
20980 				 * an SADB update to be sent to the IPsec
20981 				 * hardware acceleration capable ills.
20982 				 */
20983 				ipsec_ctl_t *ipsec_ctl =
20984 				    (ipsec_ctl_t *)mp->b_rptr;
20985 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20986 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20987 				mblk_t *cmp = mp->b_cont;
20988 
20989 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20990 				ASSERT(cmp != NULL);
20991 
20992 				freeb(mp);
20993 				ill_ipsec_capab_send_all(satype, cmp, sa,
20994 				    ipst->ips_netstack);
20995 				return;
20996 			} else {
20997 				/*
20998 				 * This must be ARP or special TSOL signaling.
20999 				 */
21000 				ip_wput_nondata(NULL, q, mp, NULL);
21001 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21002 				    "ip_wput_end: q %p (%S)", q, "nondata");
21003 				return;
21004 			}
21005 		} else {
21006 			/*
21007 			 * This must be non-(ARP/AH/ESP) messages.
21008 			 */
21009 			ASSERT(!need_decref);
21010 			ip_wput_nondata(NULL, q, mp, NULL);
21011 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21012 			    "ip_wput_end: q %p (%S)", q, "nondata");
21013 			return;
21014 		}
21015 	} else {
21016 		first_mp = mp;
21017 		mctl_present = B_FALSE;
21018 	}
21019 
21020 	ASSERT(first_mp != NULL);
21021 
21022 	if (mctl_present) {
21023 		io = (ipsec_out_t *)first_mp->b_rptr;
21024 		if (io->ipsec_out_ip_nexthop) {
21025 			/*
21026 			 * We may have lost the conn context if we are
21027 			 * coming here from ip_newroute(). Copy the
21028 			 * nexthop information.
21029 			 */
21030 			ip_nexthop = B_TRUE;
21031 			nexthop_addr = io->ipsec_out_nexthop_addr;
21032 
21033 			ipha = (ipha_t *)mp->b_rptr;
21034 			dst = ipha->ipha_dst;
21035 			goto send_from_ill;
21036 		}
21037 	}
21038 
21039 	ASSERT(xmit_ill == NULL);
21040 
21041 	/* We have a complete IP datagram heading outbound. */
21042 	ipha = (ipha_t *)mp->b_rptr;
21043 
21044 #ifndef SPEED_BEFORE_SAFETY
21045 	/*
21046 	 * Make sure we have a full-word aligned message and that at least
21047 	 * a simple IP header is accessible in the first message.  If not,
21048 	 * try a pullup.  For labeled systems we need to always take this
21049 	 * path as M_CTLs are "notdata" but have trailing data to process.
21050 	 */
21051 	if (!OK_32PTR(rptr) ||
21052 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21053 hdrtoosmall:
21054 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21055 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21056 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21057 			if (first_mp == NULL)
21058 				first_mp = mp;
21059 			goto discard_pkt;
21060 		}
21061 
21062 		/* This function assumes that mp points to an IPv4 packet. */
21063 		if (is_system_labeled() &&
21064 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21065 		    (connp == NULL || !connp->conn_ulp_labeled)) {
21066 			cred_t	*credp;
21067 			pid_t	pid;
21068 
21069 			if (connp != NULL) {
21070 				credp = BEST_CRED(mp, connp, &pid);
21071 				err = tsol_check_label(credp, &mp,
21072 				    connp->conn_mac_exempt, ipst, pid);
21073 			} else if ((credp = msg_getcred(mp, &pid)) != NULL) {
21074 				err = tsol_check_label(credp, &mp,
21075 				    B_FALSE, ipst, pid);
21076 			}
21077 			ipha = (ipha_t *)mp->b_rptr;
21078 			if (mctl_present)
21079 				first_mp->b_cont = mp;
21080 			else
21081 				first_mp = mp;
21082 			if (err != 0) {
21083 				if (err == EINVAL)
21084 					goto icmp_parameter_problem;
21085 				ip2dbg(("ip_wput: label check failed (%d)\n",
21086 				    err));
21087 				goto discard_pkt;
21088 			}
21089 		}
21090 
21091 		ipha = (ipha_t *)mp->b_rptr;
21092 		if (first_mp == NULL) {
21093 			ASSERT(xmit_ill == NULL);
21094 			/*
21095 			 * If we got here because of "goto hdrtoosmall"
21096 			 * We need to attach a IPSEC_OUT.
21097 			 */
21098 			if (connp->conn_out_enforce_policy) {
21099 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21100 				    NULL, ipha->ipha_protocol,
21101 				    ipst->ips_netstack)) == NULL)) {
21102 					BUMP_MIB(&ipst->ips_ip_mib,
21103 					    ipIfStatsOutDiscards);
21104 					if (need_decref)
21105 						CONN_DEC_REF(connp);
21106 					return;
21107 				} else {
21108 					ASSERT(mp->b_datap->db_type == M_CTL);
21109 					first_mp = mp;
21110 					mp = mp->b_cont;
21111 					mctl_present = B_TRUE;
21112 				}
21113 			} else {
21114 				first_mp = mp;
21115 				mctl_present = B_FALSE;
21116 			}
21117 		}
21118 	}
21119 #endif
21120 
21121 	/* Most of the code below is written for speed, not readability */
21122 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21123 
21124 	/*
21125 	 * If ip_newroute() fails, we're going to need a full
21126 	 * header for the icmp wraparound.
21127 	 */
21128 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21129 		uint_t	v_hlen;
21130 version_hdrlen_check:
21131 		ASSERT(first_mp != NULL);
21132 		v_hlen = V_HLEN;
21133 		/*
21134 		 * siphon off IPv6 packets coming down from transport
21135 		 * layer modules here.
21136 		 * Note: high-order bit carries NUD reachability confirmation
21137 		 */
21138 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21139 			/*
21140 			 * FIXME: assume that callers of ip_output* call
21141 			 * the right version?
21142 			 */
21143 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21144 			ASSERT(xmit_ill == NULL);
21145 			if (need_decref)
21146 				mp->b_flag |= MSGHASREF;
21147 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21148 			return;
21149 		}
21150 
21151 		if ((v_hlen >> 4) != IP_VERSION) {
21152 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21153 			    "ip_wput_end: q %p (%S)", q, "badvers");
21154 			goto discard_pkt;
21155 		}
21156 		/*
21157 		 * Is the header length at least 20 bytes?
21158 		 *
21159 		 * Are there enough bytes accessible in the header?  If
21160 		 * not, try a pullup.
21161 		 */
21162 		v_hlen &= 0xF;
21163 		v_hlen <<= 2;
21164 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21165 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21166 			    "ip_wput_end: q %p (%S)", q, "badlen");
21167 			goto discard_pkt;
21168 		}
21169 		if (v_hlen > (mp->b_wptr - rptr)) {
21170 			if (!pullupmsg(mp, v_hlen)) {
21171 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21172 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21173 				goto discard_pkt;
21174 			}
21175 			ipha = (ipha_t *)mp->b_rptr;
21176 		}
21177 		/*
21178 		 * Move first entry from any source route into ipha_dst and
21179 		 * verify the options
21180 		 */
21181 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21182 		    zoneid, ipst)) {
21183 			ASSERT(xmit_ill == NULL);
21184 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21185 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21186 			    "ip_wput_end: q %p (%S)", q, "badopts");
21187 			if (need_decref)
21188 				CONN_DEC_REF(connp);
21189 			return;
21190 		}
21191 	}
21192 	dst = ipha->ipha_dst;
21193 
21194 	/*
21195 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21196 	 * we have to run the packet through ip_newroute which will take
21197 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21198 	 * a resolver, or assigning a default gateway, etc.
21199 	 */
21200 	if (CLASSD(dst)) {
21201 		ipif_t	*ipif;
21202 		uint32_t setsrc = 0;
21203 
21204 multicast:
21205 		ASSERT(first_mp != NULL);
21206 		ip2dbg(("ip_wput: CLASSD\n"));
21207 		if (connp == NULL) {
21208 			/*
21209 			 * Use the first good ipif on the ill.
21210 			 * XXX Should this ever happen? (Appears
21211 			 * to show up with just ppp and no ethernet due
21212 			 * to in.rdisc.)
21213 			 * However, ire_send should be able to
21214 			 * call ip_wput_ire directly.
21215 			 *
21216 			 * XXX Also, this can happen for ICMP and other packets
21217 			 * with multicast source addresses.  Perhaps we should
21218 			 * fix things so that we drop the packet in question,
21219 			 * but for now, just run with it.
21220 			 */
21221 			ill_t *ill = (ill_t *)q->q_ptr;
21222 
21223 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21224 			if (ipif == NULL) {
21225 				if (need_decref)
21226 					CONN_DEC_REF(connp);
21227 				freemsg(first_mp);
21228 				return;
21229 			}
21230 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21231 			    ntohl(dst), ill->ill_name));
21232 		} else {
21233 			/*
21234 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21235 			 * and IP_MULTICAST_IF.  The block comment above this
21236 			 * function explains the locking mechanism used here.
21237 			 */
21238 			if (xmit_ill == NULL) {
21239 				xmit_ill = conn_get_held_ill(connp,
21240 				    &connp->conn_outgoing_ill, &err);
21241 				if (err == ILL_LOOKUP_FAILED) {
21242 					ip1dbg(("ip_wput: No ill for "
21243 					    "IP_BOUND_IF\n"));
21244 					BUMP_MIB(&ipst->ips_ip_mib,
21245 					    ipIfStatsOutNoRoutes);
21246 					goto drop_pkt;
21247 				}
21248 			}
21249 
21250 			if (xmit_ill == NULL) {
21251 				ipif = conn_get_held_ipif(connp,
21252 				    &connp->conn_multicast_ipif, &err);
21253 				if (err == IPIF_LOOKUP_FAILED) {
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 			if (xmit_ill != NULL) {
21262 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21263 				if (ipif == NULL) {
21264 					ip1dbg(("ip_wput: No ipif for "
21265 					    "xmit_ill\n"));
21266 					BUMP_MIB(&ipst->ips_ip_mib,
21267 					    ipIfStatsOutNoRoutes);
21268 					goto drop_pkt;
21269 				}
21270 			} else if (ipif == NULL || ipif->ipif_isv6) {
21271 				/*
21272 				 * We must do this ipif determination here
21273 				 * else we could pass through ip_newroute
21274 				 * and come back here without the conn context.
21275 				 *
21276 				 * Note: we do late binding i.e. we bind to
21277 				 * the interface when the first packet is sent.
21278 				 * For performance reasons we do not rebind on
21279 				 * each packet but keep the binding until the
21280 				 * next IP_MULTICAST_IF option.
21281 				 *
21282 				 * conn_multicast_{ipif,ill} are shared between
21283 				 * IPv4 and IPv6 and AF_INET6 sockets can
21284 				 * send both IPv4 and IPv6 packets. Hence
21285 				 * we have to check that "isv6" matches above.
21286 				 */
21287 				if (ipif != NULL)
21288 					ipif_refrele(ipif);
21289 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21290 				if (ipif == NULL) {
21291 					ip1dbg(("ip_wput: No ipif for "
21292 					    "multicast\n"));
21293 					BUMP_MIB(&ipst->ips_ip_mib,
21294 					    ipIfStatsOutNoRoutes);
21295 					goto drop_pkt;
21296 				}
21297 				err = conn_set_held_ipif(connp,
21298 				    &connp->conn_multicast_ipif, ipif);
21299 				if (err == IPIF_LOOKUP_FAILED) {
21300 					ipif_refrele(ipif);
21301 					ip1dbg(("ip_wput: No ipif for "
21302 					    "multicast\n"));
21303 					BUMP_MIB(&ipst->ips_ip_mib,
21304 					    ipIfStatsOutNoRoutes);
21305 					goto drop_pkt;
21306 				}
21307 			}
21308 		}
21309 		ASSERT(!ipif->ipif_isv6);
21310 		/*
21311 		 * As we may lose the conn by the time we reach ip_wput_ire,
21312 		 * we copy conn_multicast_loop and conn_dontroute on to an
21313 		 * ipsec_out. In case if this datagram goes out secure,
21314 		 * we need the ill_index also. Copy that also into the
21315 		 * ipsec_out.
21316 		 */
21317 		if (mctl_present) {
21318 			io = (ipsec_out_t *)first_mp->b_rptr;
21319 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21320 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21321 		} else {
21322 			ASSERT(mp == first_mp);
21323 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21324 			    BPRI_HI)) == NULL) {
21325 				ipif_refrele(ipif);
21326 				first_mp = mp;
21327 				goto discard_pkt;
21328 			}
21329 			first_mp->b_datap->db_type = M_CTL;
21330 			first_mp->b_wptr += sizeof (ipsec_info_t);
21331 			/* ipsec_out_secure is B_FALSE now */
21332 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21333 			io = (ipsec_out_t *)first_mp->b_rptr;
21334 			io->ipsec_out_type = IPSEC_OUT;
21335 			io->ipsec_out_len = sizeof (ipsec_out_t);
21336 			io->ipsec_out_use_global_policy = B_TRUE;
21337 			io->ipsec_out_ns = ipst->ips_netstack;
21338 			first_mp->b_cont = mp;
21339 			mctl_present = B_TRUE;
21340 		}
21341 
21342 		match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21343 		io->ipsec_out_ill_index =
21344 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21345 
21346 		if (connp != NULL) {
21347 			io->ipsec_out_multicast_loop =
21348 			    connp->conn_multicast_loop;
21349 			io->ipsec_out_dontroute = connp->conn_dontroute;
21350 			io->ipsec_out_zoneid = connp->conn_zoneid;
21351 		}
21352 		/*
21353 		 * If the application uses IP_MULTICAST_IF with
21354 		 * different logical addresses of the same ILL, we
21355 		 * need to make sure that the soruce address of
21356 		 * the packet matches the logical IP address used
21357 		 * in the option. We do it by initializing ipha_src
21358 		 * here. This should keep IPsec also happy as
21359 		 * when we return from IPsec processing, we don't
21360 		 * have to worry about getting the right address on
21361 		 * the packet. Thus it is sufficient to look for
21362 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21363 		 * MATCH_IRE_IPIF.
21364 		 *
21365 		 * NOTE : We need to do it for non-secure case also as
21366 		 * this might go out secure if there is a global policy
21367 		 * match in ip_wput_ire.
21368 		 *
21369 		 * As we do not have the ire yet, it is possible that
21370 		 * we set the source address here and then later discover
21371 		 * that the ire implies the source address to be assigned
21372 		 * through the RTF_SETSRC flag.
21373 		 * In that case, the setsrc variable will remind us
21374 		 * that overwritting the source address by the one
21375 		 * of the RTF_SETSRC-flagged ire is allowed.
21376 		 */
21377 		if (ipha->ipha_src == INADDR_ANY &&
21378 		    (connp == NULL || !connp->conn_unspec_src)) {
21379 			ipha->ipha_src = ipif->ipif_src_addr;
21380 			setsrc = RTF_SETSRC;
21381 		}
21382 		/*
21383 		 * Find an IRE which matches the destination and the outgoing
21384 		 * queue (i.e. the outgoing interface.)
21385 		 * For loopback use a unicast IP address for
21386 		 * the ire lookup.
21387 		 */
21388 		if (IS_LOOPBACK(ipif->ipif_ill))
21389 			dst = ipif->ipif_lcl_addr;
21390 
21391 		/*
21392 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21393 		 * We don't need to lookup ire in ctable as the packet
21394 		 * needs to be sent to the destination through the specified
21395 		 * ill irrespective of ires in the cache table.
21396 		 */
21397 		ire = NULL;
21398 		if (xmit_ill == NULL) {
21399 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21400 			    zoneid, msg_getlabel(mp), match_flags, ipst);
21401 		}
21402 
21403 		if (ire == NULL) {
21404 			/*
21405 			 * Multicast loopback and multicast forwarding is
21406 			 * done in ip_wput_ire.
21407 			 *
21408 			 * Mark this packet to make it be delivered to
21409 			 * ip_wput_ire after the new ire has been
21410 			 * created.
21411 			 *
21412 			 * The call to ip_newroute_ipif takes into account
21413 			 * the setsrc reminder. In any case, we take care
21414 			 * of the RTF_MULTIRT flag.
21415 			 */
21416 			mp->b_prev = mp->b_next = NULL;
21417 			if (xmit_ill == NULL ||
21418 			    xmit_ill->ill_ipif_up_count > 0) {
21419 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21420 				    setsrc | RTF_MULTIRT, zoneid, infop);
21421 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21422 				    "ip_wput_end: q %p (%S)", q, "noire");
21423 			} else {
21424 				freemsg(first_mp);
21425 			}
21426 			ipif_refrele(ipif);
21427 			if (xmit_ill != NULL)
21428 				ill_refrele(xmit_ill);
21429 			if (need_decref)
21430 				CONN_DEC_REF(connp);
21431 			return;
21432 		}
21433 
21434 		ipif_refrele(ipif);
21435 		ipif = NULL;
21436 		ASSERT(xmit_ill == NULL);
21437 
21438 		/*
21439 		 * Honor the RTF_SETSRC flag for multicast packets,
21440 		 * if allowed by the setsrc reminder.
21441 		 */
21442 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21443 			ipha->ipha_src = ire->ire_src_addr;
21444 		}
21445 
21446 		/*
21447 		 * Unconditionally force the TTL to 1 for
21448 		 * multirouted multicast packets:
21449 		 * multirouted multicast should not cross
21450 		 * multicast routers.
21451 		 */
21452 		if (ire->ire_flags & RTF_MULTIRT) {
21453 			if (ipha->ipha_ttl > 1) {
21454 				ip2dbg(("ip_wput: forcing multicast "
21455 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21456 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21457 				ipha->ipha_ttl = 1;
21458 			}
21459 		}
21460 	} else {
21461 		ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp), ipst);
21462 		if ((ire != NULL) && (ire->ire_type &
21463 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21464 			ignore_dontroute = B_TRUE;
21465 			ignore_nexthop = B_TRUE;
21466 		}
21467 		if (ire != NULL) {
21468 			ire_refrele(ire);
21469 			ire = NULL;
21470 		}
21471 		/*
21472 		 * Guard against coming in from arp in which case conn is NULL.
21473 		 * Also guard against non M_DATA with dontroute set but
21474 		 * destined to local, loopback or broadcast addresses.
21475 		 */
21476 		if (connp != NULL && connp->conn_dontroute &&
21477 		    !ignore_dontroute) {
21478 dontroute:
21479 			/*
21480 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21481 			 * routing protocols from seeing false direct
21482 			 * connectivity.
21483 			 */
21484 			ipha->ipha_ttl = 1;
21485 			/* If suitable ipif not found, drop packet */
21486 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21487 			if (dst_ipif == NULL) {
21488 noroute:
21489 				ip1dbg(("ip_wput: no route for dst using"
21490 				    " SO_DONTROUTE\n"));
21491 				BUMP_MIB(&ipst->ips_ip_mib,
21492 				    ipIfStatsOutNoRoutes);
21493 				mp->b_prev = mp->b_next = NULL;
21494 				if (first_mp == NULL)
21495 					first_mp = mp;
21496 				goto drop_pkt;
21497 			} else {
21498 				/*
21499 				 * If suitable ipif has been found, set
21500 				 * xmit_ill to the corresponding
21501 				 * ipif_ill because we'll be using the
21502 				 * send_from_ill logic below.
21503 				 */
21504 				ASSERT(xmit_ill == NULL);
21505 				xmit_ill = dst_ipif->ipif_ill;
21506 				mutex_enter(&xmit_ill->ill_lock);
21507 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21508 					mutex_exit(&xmit_ill->ill_lock);
21509 					xmit_ill = NULL;
21510 					ipif_refrele(dst_ipif);
21511 					goto noroute;
21512 				}
21513 				ill_refhold_locked(xmit_ill);
21514 				mutex_exit(&xmit_ill->ill_lock);
21515 				ipif_refrele(dst_ipif);
21516 			}
21517 		}
21518 
21519 send_from_ill:
21520 		if (xmit_ill != NULL) {
21521 			ipif_t *ipif;
21522 
21523 			/*
21524 			 * Mark this packet as originated locally
21525 			 */
21526 			mp->b_prev = mp->b_next = NULL;
21527 
21528 			/*
21529 			 * Could be SO_DONTROUTE case also.
21530 			 * Verify that at least one ipif is up on the ill.
21531 			 */
21532 			if (xmit_ill->ill_ipif_up_count == 0) {
21533 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21534 				    xmit_ill->ill_name));
21535 				goto drop_pkt;
21536 			}
21537 
21538 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21539 			if (ipif == NULL) {
21540 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21541 				    xmit_ill->ill_name));
21542 				goto drop_pkt;
21543 			}
21544 
21545 			match_flags = 0;
21546 			if (IS_UNDER_IPMP(xmit_ill))
21547 				match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
21548 
21549 			/*
21550 			 * Look for a ire that is part of the group,
21551 			 * if found use it else call ip_newroute_ipif.
21552 			 * IPCL_ZONEID is not used for matching because
21553 			 * IP_ALLZONES option is valid only when the
21554 			 * ill is accessible from all zones i.e has a
21555 			 * valid ipif in all zones.
21556 			 */
21557 			match_flags |= MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21558 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21559 			    msg_getlabel(mp), match_flags, ipst);
21560 			/*
21561 			 * If an ire exists use it or else create
21562 			 * an ire but don't add it to the cache.
21563 			 * Adding an ire may cause issues with
21564 			 * asymmetric routing.
21565 			 * In case of multiroute always act as if
21566 			 * ire does not exist.
21567 			 */
21568 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21569 				if (ire != NULL)
21570 					ire_refrele(ire);
21571 				ip_newroute_ipif(q, first_mp, ipif,
21572 				    dst, connp, 0, zoneid, infop);
21573 				ipif_refrele(ipif);
21574 				ip1dbg(("ip_output: xmit_ill via %s\n",
21575 				    xmit_ill->ill_name));
21576 				ill_refrele(xmit_ill);
21577 				if (need_decref)
21578 					CONN_DEC_REF(connp);
21579 				return;
21580 			}
21581 			ipif_refrele(ipif);
21582 		} else if (ip_nexthop || (connp != NULL &&
21583 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21584 			if (!ip_nexthop) {
21585 				ip_nexthop = B_TRUE;
21586 				nexthop_addr = connp->conn_nexthop_v4;
21587 			}
21588 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21589 			    MATCH_IRE_GW;
21590 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21591 			    NULL, zoneid, msg_getlabel(mp), match_flags, ipst);
21592 		} else {
21593 			ire = ire_cache_lookup(dst, zoneid, msg_getlabel(mp),
21594 			    ipst);
21595 		}
21596 		if (!ire) {
21597 			if (ip_nexthop && !ignore_nexthop) {
21598 				if (mctl_present) {
21599 					io = (ipsec_out_t *)first_mp->b_rptr;
21600 					ASSERT(first_mp->b_datap->db_type ==
21601 					    M_CTL);
21602 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21603 				} else {
21604 					ASSERT(mp == first_mp);
21605 					first_mp = allocb(
21606 					    sizeof (ipsec_info_t), BPRI_HI);
21607 					if (first_mp == NULL) {
21608 						first_mp = mp;
21609 						goto discard_pkt;
21610 					}
21611 					first_mp->b_datap->db_type = M_CTL;
21612 					first_mp->b_wptr +=
21613 					    sizeof (ipsec_info_t);
21614 					/* ipsec_out_secure is B_FALSE now */
21615 					bzero(first_mp->b_rptr,
21616 					    sizeof (ipsec_info_t));
21617 					io = (ipsec_out_t *)first_mp->b_rptr;
21618 					io->ipsec_out_type = IPSEC_OUT;
21619 					io->ipsec_out_len =
21620 					    sizeof (ipsec_out_t);
21621 					io->ipsec_out_use_global_policy =
21622 					    B_TRUE;
21623 					io->ipsec_out_ns = ipst->ips_netstack;
21624 					first_mp->b_cont = mp;
21625 					mctl_present = B_TRUE;
21626 				}
21627 				io->ipsec_out_ip_nexthop = ip_nexthop;
21628 				io->ipsec_out_nexthop_addr = nexthop_addr;
21629 			}
21630 noirefound:
21631 			/*
21632 			 * Mark this packet as having originated on
21633 			 * this machine.  This will be noted in
21634 			 * ire_add_then_send, which needs to know
21635 			 * whether to run it back through ip_wput or
21636 			 * ip_rput following successful resolution.
21637 			 */
21638 			mp->b_prev = NULL;
21639 			mp->b_next = NULL;
21640 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21641 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21642 			    "ip_wput_end: q %p (%S)", q, "newroute");
21643 			if (xmit_ill != NULL)
21644 				ill_refrele(xmit_ill);
21645 			if (need_decref)
21646 				CONN_DEC_REF(connp);
21647 			return;
21648 		}
21649 	}
21650 
21651 	/* We now know where we are going with it. */
21652 
21653 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21654 	    "ip_wput_end: q %p (%S)", q, "end");
21655 
21656 	/*
21657 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21658 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21659 	 */
21660 	if (ire->ire_flags & RTF_MULTIRT) {
21661 		/*
21662 		 * Force the TTL of multirouted packets if required.
21663 		 * The TTL of such packets is bounded by the
21664 		 * ip_multirt_ttl ndd variable.
21665 		 */
21666 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21667 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21668 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21669 			    "(was %d), dst 0x%08x\n",
21670 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21671 			    ntohl(ire->ire_addr)));
21672 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21673 		}
21674 		/*
21675 		 * At this point, we check to see if there are any pending
21676 		 * unresolved routes. ire_multirt_resolvable()
21677 		 * checks in O(n) that all IRE_OFFSUBNET ire
21678 		 * entries for the packet's destination and
21679 		 * flagged RTF_MULTIRT are currently resolved.
21680 		 * If some remain unresolved, we make a copy
21681 		 * of the current message. It will be used
21682 		 * to initiate additional route resolutions.
21683 		 */
21684 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21685 		    msg_getlabel(first_mp), ipst);
21686 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21687 		    "multirt_need_resolve %d, first_mp %p\n",
21688 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21689 		if (multirt_need_resolve) {
21690 			copy_mp = copymsg(first_mp);
21691 			if (copy_mp != NULL) {
21692 				MULTIRT_DEBUG_TAG(copy_mp);
21693 			}
21694 		}
21695 	}
21696 
21697 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21698 	/*
21699 	 * Try to resolve another multiroute if
21700 	 * ire_multirt_resolvable() deemed it necessary.
21701 	 * At this point, we need to distinguish
21702 	 * multicasts from other packets. For multicasts,
21703 	 * we call ip_newroute_ipif() and request that both
21704 	 * multirouting and setsrc flags are checked.
21705 	 */
21706 	if (copy_mp != NULL) {
21707 		if (CLASSD(dst)) {
21708 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21709 			if (ipif) {
21710 				ASSERT(infop->ip_opt_ill_index == 0);
21711 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21712 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21713 				ipif_refrele(ipif);
21714 			} else {
21715 				MULTIRT_DEBUG_UNTAG(copy_mp);
21716 				freemsg(copy_mp);
21717 				copy_mp = NULL;
21718 			}
21719 		} else {
21720 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21721 		}
21722 	}
21723 	if (xmit_ill != NULL)
21724 		ill_refrele(xmit_ill);
21725 	if (need_decref)
21726 		CONN_DEC_REF(connp);
21727 	return;
21728 
21729 icmp_parameter_problem:
21730 	/* could not have originated externally */
21731 	ASSERT(mp->b_prev == NULL);
21732 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21733 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21734 		/* it's the IP header length that's in trouble */
21735 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21736 		first_mp = NULL;
21737 	}
21738 
21739 discard_pkt:
21740 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21741 drop_pkt:
21742 	ip1dbg(("ip_wput: dropped packet\n"));
21743 	if (ire != NULL)
21744 		ire_refrele(ire);
21745 	if (need_decref)
21746 		CONN_DEC_REF(connp);
21747 	freemsg(first_mp);
21748 	if (xmit_ill != NULL)
21749 		ill_refrele(xmit_ill);
21750 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21751 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21752 }
21753 
21754 /*
21755  * If this is a conn_t queue, then we pass in the conn. This includes the
21756  * zoneid.
21757  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21758  * in which case we use the global zoneid since those are all part of
21759  * the global zone.
21760  */
21761 void
21762 ip_wput(queue_t *q, mblk_t *mp)
21763 {
21764 	if (CONN_Q(q))
21765 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21766 	else
21767 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21768 }
21769 
21770 /*
21771  *
21772  * The following rules must be observed when accessing any ipif or ill
21773  * that has been cached in the conn. Typically conn_outgoing_ill,
21774  * conn_multicast_ipif and conn_multicast_ill.
21775  *
21776  * Access: The ipif or ill pointed to from the conn can be accessed under
21777  * the protection of the conn_lock or after it has been refheld under the
21778  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21779  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21780  * The reason for this is that a concurrent unplumb could actually be
21781  * cleaning up these cached pointers by walking the conns and might have
21782  * finished cleaning up the conn in question. The macros check that an
21783  * unplumb has not yet started on the ipif or ill.
21784  *
21785  * Caching: An ipif or ill pointer may be cached in the conn only after
21786  * making sure that an unplumb has not started. So the caching is done
21787  * while holding both the conn_lock and the ill_lock and after using the
21788  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21789  * flag before starting the cleanup of conns.
21790  *
21791  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21792  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21793  * or a reference to the ipif or a reference to an ire that references the
21794  * ipif. An ipif only changes its ill when migrating from an underlying ill
21795  * to an IPMP ill in ipif_up().
21796  */
21797 ipif_t *
21798 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21799 {
21800 	ipif_t	*ipif;
21801 	ill_t	*ill;
21802 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21803 
21804 	*err = 0;
21805 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21806 	mutex_enter(&connp->conn_lock);
21807 	ipif = *ipifp;
21808 	if (ipif != NULL) {
21809 		ill = ipif->ipif_ill;
21810 		mutex_enter(&ill->ill_lock);
21811 		if (IPIF_CAN_LOOKUP(ipif)) {
21812 			ipif_refhold_locked(ipif);
21813 			mutex_exit(&ill->ill_lock);
21814 			mutex_exit(&connp->conn_lock);
21815 			rw_exit(&ipst->ips_ill_g_lock);
21816 			return (ipif);
21817 		} else {
21818 			*err = IPIF_LOOKUP_FAILED;
21819 		}
21820 		mutex_exit(&ill->ill_lock);
21821 	}
21822 	mutex_exit(&connp->conn_lock);
21823 	rw_exit(&ipst->ips_ill_g_lock);
21824 	return (NULL);
21825 }
21826 
21827 ill_t *
21828 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21829 {
21830 	ill_t	*ill;
21831 
21832 	*err = 0;
21833 	mutex_enter(&connp->conn_lock);
21834 	ill = *illp;
21835 	if (ill != NULL) {
21836 		mutex_enter(&ill->ill_lock);
21837 		if (ILL_CAN_LOOKUP(ill)) {
21838 			ill_refhold_locked(ill);
21839 			mutex_exit(&ill->ill_lock);
21840 			mutex_exit(&connp->conn_lock);
21841 			return (ill);
21842 		} else {
21843 			*err = ILL_LOOKUP_FAILED;
21844 		}
21845 		mutex_exit(&ill->ill_lock);
21846 	}
21847 	mutex_exit(&connp->conn_lock);
21848 	return (NULL);
21849 }
21850 
21851 static int
21852 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21853 {
21854 	ill_t	*ill;
21855 
21856 	ill = ipif->ipif_ill;
21857 	mutex_enter(&connp->conn_lock);
21858 	mutex_enter(&ill->ill_lock);
21859 	if (IPIF_CAN_LOOKUP(ipif)) {
21860 		*ipifp = ipif;
21861 		mutex_exit(&ill->ill_lock);
21862 		mutex_exit(&connp->conn_lock);
21863 		return (0);
21864 	}
21865 	mutex_exit(&ill->ill_lock);
21866 	mutex_exit(&connp->conn_lock);
21867 	return (IPIF_LOOKUP_FAILED);
21868 }
21869 
21870 /*
21871  * This is called if the outbound datagram needs fragmentation.
21872  *
21873  * NOTE : This function does not ire_refrele the ire argument passed in.
21874  */
21875 static void
21876 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21877     ip_stack_t *ipst, conn_t *connp)
21878 {
21879 	ipha_t		*ipha;
21880 	mblk_t		*mp;
21881 	uint32_t	v_hlen_tos_len;
21882 	uint32_t	max_frag;
21883 	uint32_t	frag_flag;
21884 	boolean_t	dont_use;
21885 
21886 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21887 		mp = ipsec_mp->b_cont;
21888 	} else {
21889 		mp = ipsec_mp;
21890 	}
21891 
21892 	ipha = (ipha_t *)mp->b_rptr;
21893 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21894 
21895 #ifdef	_BIG_ENDIAN
21896 #define	V_HLEN	(v_hlen_tos_len >> 24)
21897 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21898 #else
21899 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21900 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21901 #endif
21902 
21903 #ifndef SPEED_BEFORE_SAFETY
21904 	/*
21905 	 * Check that ipha_length is consistent with
21906 	 * the mblk length
21907 	 */
21908 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21909 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21910 		    LENGTH, msgdsize(mp)));
21911 		freemsg(ipsec_mp);
21912 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21913 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21914 		    "packet length mismatch");
21915 		return;
21916 	}
21917 #endif
21918 	/*
21919 	 * Don't use frag_flag if pre-built packet or source
21920 	 * routed or if multicast (since multicast packets do not solicit
21921 	 * ICMP "packet too big" messages). Get the values of
21922 	 * max_frag and frag_flag atomically by acquiring the
21923 	 * ire_lock.
21924 	 */
21925 	mutex_enter(&ire->ire_lock);
21926 	max_frag = ire->ire_max_frag;
21927 	frag_flag = ire->ire_frag_flag;
21928 	mutex_exit(&ire->ire_lock);
21929 
21930 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21931 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21932 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21933 
21934 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21935 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
21936 }
21937 
21938 /*
21939  * Used for deciding the MSS size for the upper layer. Thus
21940  * we need to check the outbound policy values in the conn.
21941  */
21942 int
21943 conn_ipsec_length(conn_t *connp)
21944 {
21945 	ipsec_latch_t *ipl;
21946 
21947 	ipl = connp->conn_latch;
21948 	if (ipl == NULL)
21949 		return (0);
21950 
21951 	if (ipl->ipl_out_policy == NULL)
21952 		return (0);
21953 
21954 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21955 }
21956 
21957 /*
21958  * Returns an estimate of the IPsec headers size. This is used if
21959  * we don't want to call into IPsec to get the exact size.
21960  */
21961 int
21962 ipsec_out_extra_length(mblk_t *ipsec_mp)
21963 {
21964 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21965 	ipsec_action_t *a;
21966 
21967 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21968 	if (!io->ipsec_out_secure)
21969 		return (0);
21970 
21971 	a = io->ipsec_out_act;
21972 
21973 	if (a == NULL) {
21974 		ASSERT(io->ipsec_out_policy != NULL);
21975 		a = io->ipsec_out_policy->ipsp_act;
21976 	}
21977 	ASSERT(a != NULL);
21978 
21979 	return (a->ipa_ovhd);
21980 }
21981 
21982 /*
21983  * Returns an estimate of the IPsec headers size. This is used if
21984  * we don't want to call into IPsec to get the exact size.
21985  */
21986 int
21987 ipsec_in_extra_length(mblk_t *ipsec_mp)
21988 {
21989 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21990 	ipsec_action_t *a;
21991 
21992 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21993 
21994 	a = ii->ipsec_in_action;
21995 	return (a == NULL ? 0 : a->ipa_ovhd);
21996 }
21997 
21998 /*
21999  * If there are any source route options, return the true final
22000  * destination. Otherwise, return the destination.
22001  */
22002 ipaddr_t
22003 ip_get_dst(ipha_t *ipha)
22004 {
22005 	ipoptp_t	opts;
22006 	uchar_t		*opt;
22007 	uint8_t		optval;
22008 	uint8_t		optlen;
22009 	ipaddr_t	dst;
22010 	uint32_t off;
22011 
22012 	dst = ipha->ipha_dst;
22013 
22014 	if (IS_SIMPLE_IPH(ipha))
22015 		return (dst);
22016 
22017 	for (optval = ipoptp_first(&opts, ipha);
22018 	    optval != IPOPT_EOL;
22019 	    optval = ipoptp_next(&opts)) {
22020 		opt = opts.ipoptp_cur;
22021 		optlen = opts.ipoptp_len;
22022 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22023 		switch (optval) {
22024 		case IPOPT_SSRR:
22025 		case IPOPT_LSRR:
22026 			off = opt[IPOPT_OFFSET];
22027 			/*
22028 			 * If one of the conditions is true, it means
22029 			 * end of options and dst already has the right
22030 			 * value.
22031 			 */
22032 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22033 				off = optlen - IP_ADDR_LEN;
22034 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22035 			}
22036 			return (dst);
22037 		default:
22038 			break;
22039 		}
22040 	}
22041 
22042 	return (dst);
22043 }
22044 
22045 mblk_t *
22046 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22047     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22048 {
22049 	ipsec_out_t	*io;
22050 	mblk_t		*first_mp;
22051 	boolean_t policy_present;
22052 	ip_stack_t	*ipst;
22053 	ipsec_stack_t	*ipss;
22054 
22055 	ASSERT(ire != NULL);
22056 	ipst = ire->ire_ipst;
22057 	ipss = ipst->ips_netstack->netstack_ipsec;
22058 
22059 	first_mp = mp;
22060 	if (mp->b_datap->db_type == M_CTL) {
22061 		io = (ipsec_out_t *)first_mp->b_rptr;
22062 		/*
22063 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22064 		 *
22065 		 * 1) There is per-socket policy (including cached global
22066 		 *    policy) or a policy on the IP-in-IP tunnel.
22067 		 * 2) There is no per-socket policy, but it is
22068 		 *    a multicast packet that needs to go out
22069 		 *    on a specific interface. This is the case
22070 		 *    where (ip_wput and ip_wput_multicast) attaches
22071 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22072 		 *
22073 		 * In case (2) we check with global policy to
22074 		 * see if there is a match and set the ill_index
22075 		 * appropriately so that we can lookup the ire
22076 		 * properly in ip_wput_ipsec_out.
22077 		 */
22078 
22079 		/*
22080 		 * ipsec_out_use_global_policy is set to B_FALSE
22081 		 * in ipsec_in_to_out(). Refer to that function for
22082 		 * details.
22083 		 */
22084 		if ((io->ipsec_out_latch == NULL) &&
22085 		    (io->ipsec_out_use_global_policy)) {
22086 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22087 			    ire, connp, unspec_src, zoneid));
22088 		}
22089 		if (!io->ipsec_out_secure) {
22090 			/*
22091 			 * If this is not a secure packet, drop
22092 			 * the IPSEC_OUT mp and treat it as a clear
22093 			 * packet. This happens when we are sending
22094 			 * a ICMP reply back to a clear packet. See
22095 			 * ipsec_in_to_out() for details.
22096 			 */
22097 			mp = first_mp->b_cont;
22098 			freeb(first_mp);
22099 		}
22100 		return (mp);
22101 	}
22102 	/*
22103 	 * See whether we need to attach a global policy here. We
22104 	 * don't depend on the conn (as it could be null) for deciding
22105 	 * what policy this datagram should go through because it
22106 	 * should have happened in ip_wput if there was some
22107 	 * policy. This normally happens for connections which are not
22108 	 * fully bound preventing us from caching policies in
22109 	 * ip_bind. Packets coming from the TCP listener/global queue
22110 	 * - which are non-hard_bound - could also be affected by
22111 	 * applying policy here.
22112 	 *
22113 	 * If this packet is coming from tcp global queue or listener,
22114 	 * we will be applying policy here.  This may not be *right*
22115 	 * if these packets are coming from the detached connection as
22116 	 * it could have gone in clear before. This happens only if a
22117 	 * TCP connection started when there is no policy and somebody
22118 	 * added policy before it became detached. Thus packets of the
22119 	 * detached connection could go out secure and the other end
22120 	 * would drop it because it will be expecting in clear. The
22121 	 * converse is not true i.e if somebody starts a TCP
22122 	 * connection and deletes the policy, all the packets will
22123 	 * still go out with the policy that existed before deleting
22124 	 * because ip_unbind sends up policy information which is used
22125 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22126 	 * TCP to attach a dummy IPSEC_OUT and set
22127 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22128 	 * affect performance for normal cases, we are not doing it.
22129 	 * Thus, set policy before starting any TCP connections.
22130 	 *
22131 	 * NOTE - We might apply policy even for a hard bound connection
22132 	 * - for which we cached policy in ip_bind - if somebody added
22133 	 * global policy after we inherited the policy in ip_bind.
22134 	 * This means that the packets that were going out in clear
22135 	 * previously would start going secure and hence get dropped
22136 	 * on the other side. To fix this, TCP attaches a dummy
22137 	 * ipsec_out and make sure that we don't apply global policy.
22138 	 */
22139 	if (ipha != NULL)
22140 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22141 	else
22142 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22143 	if (!policy_present)
22144 		return (mp);
22145 
22146 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22147 	    zoneid));
22148 }
22149 
22150 /*
22151  * This function does the ire_refrele of the ire passed in as the
22152  * argument. As this function looks up more ires i.e broadcast ires,
22153  * it needs to REFRELE them. Currently, for simplicity we don't
22154  * differentiate the one passed in and looked up here. We always
22155  * REFRELE.
22156  * IPQoS Notes:
22157  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22158  * IPsec packets are done in ipsec_out_process.
22159  */
22160 void
22161 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22162     zoneid_t zoneid)
22163 {
22164 	ipha_t		*ipha;
22165 #define	rptr	((uchar_t *)ipha)
22166 	queue_t		*stq;
22167 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22168 	uint32_t	v_hlen_tos_len;
22169 	uint32_t	ttl_protocol;
22170 	ipaddr_t	src;
22171 	ipaddr_t	dst;
22172 	uint32_t	cksum;
22173 	ipaddr_t	orig_src;
22174 	ire_t		*ire1;
22175 	mblk_t		*next_mp;
22176 	uint_t		hlen;
22177 	uint16_t	*up;
22178 	uint32_t	max_frag = ire->ire_max_frag;
22179 	ill_t		*ill = ire_to_ill(ire);
22180 	int		clusterwide;
22181 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22182 	int		ipsec_len;
22183 	mblk_t		*first_mp;
22184 	ipsec_out_t	*io;
22185 	boolean_t	conn_dontroute;		/* conn value for multicast */
22186 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22187 	boolean_t	multicast_forward;	/* Should we forward ? */
22188 	boolean_t	unspec_src;
22189 	ill_t		*conn_outgoing_ill = NULL;
22190 	ill_t		*ire_ill;
22191 	ill_t		*ire1_ill;
22192 	ill_t		*out_ill;
22193 	uint32_t 	ill_index = 0;
22194 	boolean_t	multirt_send = B_FALSE;
22195 	int		err;
22196 	ipxmit_state_t	pktxmit_state;
22197 	ip_stack_t	*ipst = ire->ire_ipst;
22198 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22199 
22200 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22201 	    "ip_wput_ire_start: q %p", q);
22202 
22203 	multicast_forward = B_FALSE;
22204 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22205 
22206 	if (ire->ire_flags & RTF_MULTIRT) {
22207 		/*
22208 		 * Multirouting case. The bucket where ire is stored
22209 		 * probably holds other RTF_MULTIRT flagged ire
22210 		 * to the destination. In this call to ip_wput_ire,
22211 		 * we attempt to send the packet through all
22212 		 * those ires. Thus, we first ensure that ire is the
22213 		 * first RTF_MULTIRT ire in the bucket,
22214 		 * before walking the ire list.
22215 		 */
22216 		ire_t *first_ire;
22217 		irb_t *irb = ire->ire_bucket;
22218 		ASSERT(irb != NULL);
22219 
22220 		/* Make sure we do not omit any multiroute ire. */
22221 		IRB_REFHOLD(irb);
22222 		for (first_ire = irb->irb_ire;
22223 		    first_ire != NULL;
22224 		    first_ire = first_ire->ire_next) {
22225 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22226 			    (first_ire->ire_addr == ire->ire_addr) &&
22227 			    !(first_ire->ire_marks &
22228 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
22229 				break;
22230 		}
22231 
22232 		if ((first_ire != NULL) && (first_ire != ire)) {
22233 			IRE_REFHOLD(first_ire);
22234 			ire_refrele(ire);
22235 			ire = first_ire;
22236 			ill = ire_to_ill(ire);
22237 		}
22238 		IRB_REFRELE(irb);
22239 	}
22240 
22241 	/*
22242 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22243 	 * for performance we don't grab the mutexs in the fastpath
22244 	 */
22245 	if (ire->ire_type == IRE_BROADCAST && connp != NULL &&
22246 	    connp->conn_outgoing_ill != NULL) {
22247 		conn_outgoing_ill = conn_get_held_ill(connp,
22248 		    &connp->conn_outgoing_ill, &err);
22249 		if (err == ILL_LOOKUP_FAILED) {
22250 			ire_refrele(ire);
22251 			freemsg(mp);
22252 			return;
22253 		}
22254 	}
22255 
22256 	if (mp->b_datap->db_type != M_CTL) {
22257 		ipha = (ipha_t *)mp->b_rptr;
22258 	} else {
22259 		io = (ipsec_out_t *)mp->b_rptr;
22260 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22261 		ASSERT(zoneid == io->ipsec_out_zoneid);
22262 		ASSERT(zoneid != ALL_ZONES);
22263 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22264 		dst = ipha->ipha_dst;
22265 		/*
22266 		 * For the multicast case, ipsec_out carries conn_dontroute and
22267 		 * conn_multicast_loop as conn may not be available here. We
22268 		 * need this for multicast loopback and forwarding which is done
22269 		 * later in the code.
22270 		 */
22271 		if (CLASSD(dst)) {
22272 			conn_dontroute = io->ipsec_out_dontroute;
22273 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22274 			/*
22275 			 * If conn_dontroute is not set or conn_multicast_loop
22276 			 * is set, we need to do forwarding/loopback. For
22277 			 * datagrams from ip_wput_multicast, conn_dontroute is
22278 			 * set to B_TRUE and conn_multicast_loop is set to
22279 			 * B_FALSE so that we neither do forwarding nor
22280 			 * loopback.
22281 			 */
22282 			if (!conn_dontroute || conn_multicast_loop)
22283 				multicast_forward = B_TRUE;
22284 		}
22285 	}
22286 
22287 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22288 	    ire->ire_zoneid != ALL_ZONES) {
22289 		/*
22290 		 * When a zone sends a packet to another zone, we try to deliver
22291 		 * the packet under the same conditions as if the destination
22292 		 * was a real node on the network. To do so, we look for a
22293 		 * matching route in the forwarding table.
22294 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22295 		 * ip_newroute() does.
22296 		 * Note that IRE_LOCAL are special, since they are used
22297 		 * when the zoneid doesn't match in some cases. This means that
22298 		 * we need to handle ipha_src differently since ire_src_addr
22299 		 * belongs to the receiving zone instead of the sending zone.
22300 		 * When ip_restrict_interzone_loopback is set, then
22301 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22302 		 * for loopback between zones when the logical "Ethernet" would
22303 		 * have looped them back.
22304 		 */
22305 		ire_t *src_ire;
22306 
22307 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22308 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22309 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22310 		if (src_ire != NULL &&
22311 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22312 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22313 		    ire_local_same_lan(ire, src_ire))) {
22314 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22315 				ipha->ipha_src = src_ire->ire_src_addr;
22316 			ire_refrele(src_ire);
22317 		} else {
22318 			ire_refrele(ire);
22319 			if (conn_outgoing_ill != NULL)
22320 				ill_refrele(conn_outgoing_ill);
22321 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22322 			if (src_ire != NULL) {
22323 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22324 					ire_refrele(src_ire);
22325 					freemsg(mp);
22326 					return;
22327 				}
22328 				ire_refrele(src_ire);
22329 			}
22330 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22331 				/* Failed */
22332 				freemsg(mp);
22333 				return;
22334 			}
22335 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22336 			    ipst);
22337 			return;
22338 		}
22339 	}
22340 
22341 	if (mp->b_datap->db_type == M_CTL ||
22342 	    ipss->ipsec_outbound_v4_policy_present) {
22343 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22344 		    unspec_src, zoneid);
22345 		if (mp == NULL) {
22346 			ire_refrele(ire);
22347 			if (conn_outgoing_ill != NULL)
22348 				ill_refrele(conn_outgoing_ill);
22349 			return;
22350 		}
22351 		/*
22352 		 * Trusted Extensions supports all-zones interfaces, so
22353 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22354 		 * the global zone.
22355 		 */
22356 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22357 			io = (ipsec_out_t *)mp->b_rptr;
22358 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22359 			zoneid = io->ipsec_out_zoneid;
22360 		}
22361 	}
22362 
22363 	first_mp = mp;
22364 	ipsec_len = 0;
22365 
22366 	if (first_mp->b_datap->db_type == M_CTL) {
22367 		io = (ipsec_out_t *)first_mp->b_rptr;
22368 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22369 		mp = first_mp->b_cont;
22370 		ipsec_len = ipsec_out_extra_length(first_mp);
22371 		ASSERT(ipsec_len >= 0);
22372 		/* We already picked up the zoneid from the M_CTL above */
22373 		ASSERT(zoneid == io->ipsec_out_zoneid);
22374 		ASSERT(zoneid != ALL_ZONES);
22375 
22376 		/*
22377 		 * Drop M_CTL here if IPsec processing is not needed.
22378 		 * (Non-IPsec use of M_CTL extracted any information it
22379 		 * needed above).
22380 		 */
22381 		if (ipsec_len == 0) {
22382 			freeb(first_mp);
22383 			first_mp = mp;
22384 		}
22385 	}
22386 
22387 	/*
22388 	 * Fast path for ip_wput_ire
22389 	 */
22390 
22391 	ipha = (ipha_t *)mp->b_rptr;
22392 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22393 	dst = ipha->ipha_dst;
22394 
22395 	/*
22396 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22397 	 * if the socket is a SOCK_RAW type. The transport checksum should
22398 	 * be provided in the pre-built packet, so we don't need to compute it.
22399 	 * Also, other application set flags, like DF, should not be altered.
22400 	 * Other transport MUST pass down zero.
22401 	 */
22402 	ip_hdr_included = ipha->ipha_ident;
22403 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22404 
22405 	if (CLASSD(dst)) {
22406 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22407 		    ntohl(dst),
22408 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22409 		    ntohl(ire->ire_addr)));
22410 	}
22411 
22412 /* Macros to extract header fields from data already in registers */
22413 #ifdef	_BIG_ENDIAN
22414 #define	V_HLEN	(v_hlen_tos_len >> 24)
22415 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22416 #define	PROTO	(ttl_protocol & 0xFF)
22417 #else
22418 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22419 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22420 #define	PROTO	(ttl_protocol >> 8)
22421 #endif
22422 
22423 	orig_src = src = ipha->ipha_src;
22424 	/* (The loop back to "another" is explained down below.) */
22425 another:;
22426 	/*
22427 	 * Assign an ident value for this packet.  We assign idents on
22428 	 * a per destination basis out of the IRE.  There could be
22429 	 * other threads targeting the same destination, so we have to
22430 	 * arrange for a atomic increment.  Note that we use a 32-bit
22431 	 * atomic add because it has better performance than its
22432 	 * 16-bit sibling.
22433 	 *
22434 	 * If running in cluster mode and if the source address
22435 	 * belongs to a replicated service then vector through
22436 	 * cl_inet_ipident vector to allocate ip identifier
22437 	 * NOTE: This is a contract private interface with the
22438 	 * clustering group.
22439 	 */
22440 	clusterwide = 0;
22441 	if (cl_inet_ipident) {
22442 		ASSERT(cl_inet_isclusterwide);
22443 		netstackid_t stack_id = ipst->ips_netstack->netstack_stackid;
22444 
22445 		if ((*cl_inet_isclusterwide)(stack_id, IPPROTO_IP,
22446 		    AF_INET, (uint8_t *)(uintptr_t)src, NULL)) {
22447 			ipha->ipha_ident = (*cl_inet_ipident)(stack_id,
22448 			    IPPROTO_IP, AF_INET, (uint8_t *)(uintptr_t)src,
22449 			    (uint8_t *)(uintptr_t)dst, NULL);
22450 			clusterwide = 1;
22451 		}
22452 	}
22453 	if (!clusterwide) {
22454 		ipha->ipha_ident =
22455 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22456 	}
22457 
22458 #ifndef _BIG_ENDIAN
22459 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22460 #endif
22461 
22462 	/*
22463 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22464 	 * This is needed to obey conn_unspec_src when packets go through
22465 	 * ip_newroute + arp.
22466 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22467 	 */
22468 	if (src == INADDR_ANY && !unspec_src) {
22469 		/*
22470 		 * Assign the appropriate source address from the IRE if none
22471 		 * was specified.
22472 		 */
22473 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22474 
22475 		src = ire->ire_src_addr;
22476 		if (connp == NULL) {
22477 			ip1dbg(("ip_wput_ire: no connp and no src "
22478 			    "address for dst 0x%x, using src 0x%x\n",
22479 			    ntohl(dst),
22480 			    ntohl(src)));
22481 		}
22482 		ipha->ipha_src = src;
22483 	}
22484 	stq = ire->ire_stq;
22485 
22486 	/*
22487 	 * We only allow ire chains for broadcasts since there will
22488 	 * be multiple IRE_CACHE entries for the same multicast
22489 	 * address (one per ipif).
22490 	 */
22491 	next_mp = NULL;
22492 
22493 	/* broadcast packet */
22494 	if (ire->ire_type == IRE_BROADCAST)
22495 		goto broadcast;
22496 
22497 	/* loopback ? */
22498 	if (stq == NULL)
22499 		goto nullstq;
22500 
22501 	/* The ill_index for outbound ILL */
22502 	ill_index = Q_TO_INDEX(stq);
22503 
22504 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22505 	ttl_protocol = ((uint16_t *)ipha)[4];
22506 
22507 	/* pseudo checksum (do it in parts for IP header checksum) */
22508 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22509 
22510 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22511 		queue_t *dev_q = stq->q_next;
22512 
22513 		/*
22514 		 * For DIRECT_CAPABLE, we do flow control at
22515 		 * the time of sending the packet. See
22516 		 * ILL_SEND_TX().
22517 		 */
22518 		if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22519 		    (DEV_Q_FLOW_BLOCKED(dev_q)))
22520 			goto blocked;
22521 
22522 		if ((PROTO == IPPROTO_UDP) &&
22523 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22524 			hlen = (V_HLEN & 0xF) << 2;
22525 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22526 			if (*up != 0) {
22527 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22528 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22529 				/* Software checksum? */
22530 				if (DB_CKSUMFLAGS(mp) == 0) {
22531 					IP_STAT(ipst, ip_out_sw_cksum);
22532 					IP_STAT_UPDATE(ipst,
22533 					    ip_udp_out_sw_cksum_bytes,
22534 					    LENGTH - hlen);
22535 				}
22536 			}
22537 		}
22538 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22539 		hlen = (V_HLEN & 0xF) << 2;
22540 		if (PROTO == IPPROTO_TCP) {
22541 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22542 			/*
22543 			 * The packet header is processed once and for all, even
22544 			 * in the multirouting case. We disable hardware
22545 			 * checksum if the packet is multirouted, as it will be
22546 			 * replicated via several interfaces, and not all of
22547 			 * them may have this capability.
22548 			 */
22549 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22550 			    LENGTH, max_frag, ipsec_len, cksum);
22551 			/* Software checksum? */
22552 			if (DB_CKSUMFLAGS(mp) == 0) {
22553 				IP_STAT(ipst, ip_out_sw_cksum);
22554 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22555 				    LENGTH - hlen);
22556 			}
22557 		} else {
22558 			sctp_hdr_t	*sctph;
22559 
22560 			ASSERT(PROTO == IPPROTO_SCTP);
22561 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22562 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22563 			/*
22564 			 * Zero out the checksum field to ensure proper
22565 			 * checksum calculation.
22566 			 */
22567 			sctph->sh_chksum = 0;
22568 #ifdef	DEBUG
22569 			if (!skip_sctp_cksum)
22570 #endif
22571 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22572 		}
22573 	}
22574 
22575 	/*
22576 	 * If this is a multicast packet and originated from ip_wput
22577 	 * we need to do loopback and forwarding checks. If it comes
22578 	 * from ip_wput_multicast, we SHOULD not do this.
22579 	 */
22580 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22581 
22582 	/* checksum */
22583 	cksum += ttl_protocol;
22584 
22585 	/* fragment the packet */
22586 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22587 		goto fragmentit;
22588 	/*
22589 	 * Don't use frag_flag if packet is pre-built or source
22590 	 * routed or if multicast (since multicast packets do
22591 	 * not solicit ICMP "packet too big" messages).
22592 	 */
22593 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22594 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22595 	    !ip_source_route_included(ipha)) &&
22596 	    !CLASSD(ipha->ipha_dst))
22597 		ipha->ipha_fragment_offset_and_flags |=
22598 		    htons(ire->ire_frag_flag);
22599 
22600 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22601 		/* calculate IP header checksum */
22602 		cksum += ipha->ipha_ident;
22603 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22604 		cksum += ipha->ipha_fragment_offset_and_flags;
22605 
22606 		/* IP options present */
22607 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22608 		if (hlen)
22609 			goto checksumoptions;
22610 
22611 		/* calculate hdr checksum */
22612 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22613 		cksum = ~(cksum + (cksum >> 16));
22614 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22615 	}
22616 	if (ipsec_len != 0) {
22617 		/*
22618 		 * We will do the rest of the processing after
22619 		 * we come back from IPsec in ip_wput_ipsec_out().
22620 		 */
22621 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22622 
22623 		io = (ipsec_out_t *)first_mp->b_rptr;
22624 		io->ipsec_out_ill_index =
22625 		    ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
22626 		ipsec_out_process(q, first_mp, ire, 0);
22627 		ire_refrele(ire);
22628 		if (conn_outgoing_ill != NULL)
22629 			ill_refrele(conn_outgoing_ill);
22630 		return;
22631 	}
22632 
22633 	/*
22634 	 * In most cases, the emission loop below is entered only
22635 	 * once. Only in the case where the ire holds the
22636 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22637 	 * flagged ires in the bucket, and send the packet
22638 	 * through all crossed RTF_MULTIRT routes.
22639 	 */
22640 	if (ire->ire_flags & RTF_MULTIRT) {
22641 		multirt_send = B_TRUE;
22642 	}
22643 	do {
22644 		if (multirt_send) {
22645 			irb_t *irb;
22646 			/*
22647 			 * We are in a multiple send case, need to get
22648 			 * the next ire and make a duplicate of the packet.
22649 			 * ire1 holds here the next ire to process in the
22650 			 * bucket. If multirouting is expected,
22651 			 * any non-RTF_MULTIRT ire that has the
22652 			 * right destination address is ignored.
22653 			 */
22654 			irb = ire->ire_bucket;
22655 			ASSERT(irb != NULL);
22656 
22657 			IRB_REFHOLD(irb);
22658 			for (ire1 = ire->ire_next;
22659 			    ire1 != NULL;
22660 			    ire1 = ire1->ire_next) {
22661 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22662 					continue;
22663 				if (ire1->ire_addr != ire->ire_addr)
22664 					continue;
22665 				if (ire1->ire_marks &
22666 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
22667 					continue;
22668 
22669 				/* Got one */
22670 				IRE_REFHOLD(ire1);
22671 				break;
22672 			}
22673 			IRB_REFRELE(irb);
22674 
22675 			if (ire1 != NULL) {
22676 				next_mp = copyb(mp);
22677 				if ((next_mp == NULL) ||
22678 				    ((mp->b_cont != NULL) &&
22679 				    ((next_mp->b_cont =
22680 				    dupmsg(mp->b_cont)) == NULL))) {
22681 					freemsg(next_mp);
22682 					next_mp = NULL;
22683 					ire_refrele(ire1);
22684 					ire1 = NULL;
22685 				}
22686 			}
22687 
22688 			/* Last multiroute ire; don't loop anymore. */
22689 			if (ire1 == NULL) {
22690 				multirt_send = B_FALSE;
22691 			}
22692 		}
22693 
22694 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22695 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22696 		    mblk_t *, mp);
22697 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22698 		    ipst->ips_ipv4firewall_physical_out,
22699 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22700 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22701 
22702 		if (mp == NULL)
22703 			goto release_ire_and_ill;
22704 
22705 		if (ipst->ips_ipobs_enabled) {
22706 			zoneid_t szone;
22707 
22708 			/*
22709 			 * On the outbound path the destination zone will be
22710 			 * unknown as we're sending this packet out on the
22711 			 * wire.
22712 			 */
22713 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22714 			    ALL_ZONES);
22715 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22716 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22717 		}
22718 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22719 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22720 
22721 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22722 
22723 		if ((pktxmit_state == SEND_FAILED) ||
22724 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22725 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22726 			    "- packet dropped\n"));
22727 release_ire_and_ill:
22728 			ire_refrele(ire);
22729 			if (next_mp != NULL) {
22730 				freemsg(next_mp);
22731 				ire_refrele(ire1);
22732 			}
22733 			if (conn_outgoing_ill != NULL)
22734 				ill_refrele(conn_outgoing_ill);
22735 			return;
22736 		}
22737 
22738 		if (CLASSD(dst)) {
22739 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22740 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22741 			    LENGTH);
22742 		}
22743 
22744 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22745 		    "ip_wput_ire_end: q %p (%S)",
22746 		    q, "last copy out");
22747 		IRE_REFRELE(ire);
22748 
22749 		if (multirt_send) {
22750 			ASSERT(ire1);
22751 			/*
22752 			 * Proceed with the next RTF_MULTIRT ire,
22753 			 * Also set up the send-to queue accordingly.
22754 			 */
22755 			ire = ire1;
22756 			ire1 = NULL;
22757 			stq = ire->ire_stq;
22758 			mp = next_mp;
22759 			next_mp = NULL;
22760 			ipha = (ipha_t *)mp->b_rptr;
22761 			ill_index = Q_TO_INDEX(stq);
22762 			ill = (ill_t *)stq->q_ptr;
22763 		}
22764 	} while (multirt_send);
22765 	if (conn_outgoing_ill != NULL)
22766 		ill_refrele(conn_outgoing_ill);
22767 	return;
22768 
22769 	/*
22770 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22771 	 */
22772 broadcast:
22773 	{
22774 		/*
22775 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22776 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22777 		 * can be overridden stack-wide through the ip_broadcast_ttl
22778 		 * ndd tunable, or on a per-connection basis through the
22779 		 * IP_BROADCAST_TTL socket option.
22780 		 *
22781 		 * In the event that we are replying to incoming ICMP packets,
22782 		 * connp could be NULL.
22783 		 */
22784 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22785 		if (connp != NULL) {
22786 			if (connp->conn_dontroute)
22787 				ipha->ipha_ttl = 1;
22788 			else if (connp->conn_broadcast_ttl != 0)
22789 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22790 		}
22791 
22792 		/*
22793 		 * Note that we are not doing a IRB_REFHOLD here.
22794 		 * Actually we don't care if the list changes i.e
22795 		 * if somebody deletes an IRE from the list while
22796 		 * we drop the lock, the next time we come around
22797 		 * ire_next will be NULL and hence we won't send
22798 		 * out multiple copies which is fine.
22799 		 */
22800 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22801 		ire1 = ire->ire_next;
22802 		if (conn_outgoing_ill != NULL) {
22803 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22804 				ASSERT(ire1 == ire->ire_next);
22805 				if (ire1 != NULL && ire1->ire_addr == dst) {
22806 					ire_refrele(ire);
22807 					ire = ire1;
22808 					IRE_REFHOLD(ire);
22809 					ire1 = ire->ire_next;
22810 					continue;
22811 				}
22812 				rw_exit(&ire->ire_bucket->irb_lock);
22813 				/* Did not find a matching ill */
22814 				ip1dbg(("ip_wput_ire: broadcast with no "
22815 				    "matching IP_BOUND_IF ill %s dst %x\n",
22816 				    conn_outgoing_ill->ill_name, dst));
22817 				freemsg(first_mp);
22818 				if (ire != NULL)
22819 					ire_refrele(ire);
22820 				ill_refrele(conn_outgoing_ill);
22821 				return;
22822 			}
22823 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22824 			/*
22825 			 * If the next IRE has the same address and is not one
22826 			 * of the two copies that we need to send, try to see
22827 			 * whether this copy should be sent at all. This
22828 			 * assumes that we insert loopbacks first and then
22829 			 * non-loopbacks. This is acheived by inserting the
22830 			 * loopback always before non-loopback.
22831 			 * This is used to send a single copy of a broadcast
22832 			 * packet out all physical interfaces that have an
22833 			 * matching IRE_BROADCAST while also looping
22834 			 * back one copy (to ip_wput_local) for each
22835 			 * matching physical interface. However, we avoid
22836 			 * sending packets out different logical that match by
22837 			 * having ipif_up/ipif_down supress duplicate
22838 			 * IRE_BROADCASTS.
22839 			 *
22840 			 * This feature is currently used to get broadcasts
22841 			 * sent to multiple interfaces, when the broadcast
22842 			 * address being used applies to multiple interfaces.
22843 			 * For example, a whole net broadcast will be
22844 			 * replicated on every connected subnet of
22845 			 * the target net.
22846 			 *
22847 			 * Each zone has its own set of IRE_BROADCASTs, so that
22848 			 * we're able to distribute inbound packets to multiple
22849 			 * zones who share a broadcast address. We avoid looping
22850 			 * back outbound packets in different zones but on the
22851 			 * same ill, as the application would see duplicates.
22852 			 *
22853 			 * This logic assumes that ire_add_v4() groups the
22854 			 * IRE_BROADCAST entries so that those with the same
22855 			 * ire_addr are kept together.
22856 			 */
22857 			ire_ill = ire->ire_ipif->ipif_ill;
22858 			if (ire->ire_stq != NULL || ire1->ire_stq == NULL) {
22859 				while (ire1 != NULL && ire1->ire_addr == dst) {
22860 					ire1_ill = ire1->ire_ipif->ipif_ill;
22861 					if (ire1_ill != ire_ill)
22862 						break;
22863 					ire1 = ire1->ire_next;
22864 				}
22865 			}
22866 		}
22867 		ASSERT(multirt_send == B_FALSE);
22868 		if (ire1 != NULL && ire1->ire_addr == dst) {
22869 			if ((ire->ire_flags & RTF_MULTIRT) &&
22870 			    (ire1->ire_flags & RTF_MULTIRT)) {
22871 				/*
22872 				 * We are in the multirouting case.
22873 				 * The message must be sent at least
22874 				 * on both ires. These ires have been
22875 				 * inserted AFTER the standard ones
22876 				 * in ip_rt_add(). There are thus no
22877 				 * other ire entries for the destination
22878 				 * address in the rest of the bucket
22879 				 * that do not have the RTF_MULTIRT
22880 				 * flag. We don't process a copy
22881 				 * of the message here. This will be
22882 				 * done in the final sending loop.
22883 				 */
22884 				multirt_send = B_TRUE;
22885 			} else {
22886 				next_mp = ip_copymsg(first_mp);
22887 				if (next_mp != NULL)
22888 					IRE_REFHOLD(ire1);
22889 			}
22890 		}
22891 		rw_exit(&ire->ire_bucket->irb_lock);
22892 	}
22893 
22894 	if (stq) {
22895 		/*
22896 		 * A non-NULL send-to queue means this packet is going
22897 		 * out of this machine.
22898 		 */
22899 		out_ill = (ill_t *)stq->q_ptr;
22900 
22901 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22902 		ttl_protocol = ((uint16_t *)ipha)[4];
22903 		/*
22904 		 * We accumulate the pseudo header checksum in cksum.
22905 		 * This is pretty hairy code, so watch close.  One
22906 		 * thing to keep in mind is that UDP and TCP have
22907 		 * stored their respective datagram lengths in their
22908 		 * checksum fields.  This lines things up real nice.
22909 		 */
22910 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22911 		    (src >> 16) + (src & 0xFFFF);
22912 		/*
22913 		 * We assume the udp checksum field contains the
22914 		 * length, so to compute the pseudo header checksum,
22915 		 * all we need is the protocol number and src/dst.
22916 		 */
22917 		/* Provide the checksums for UDP and TCP. */
22918 		if ((PROTO == IPPROTO_TCP) &&
22919 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22920 			/* hlen gets the number of uchar_ts in the IP header */
22921 			hlen = (V_HLEN & 0xF) << 2;
22922 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22923 			IP_STAT(ipst, ip_out_sw_cksum);
22924 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22925 			    LENGTH - hlen);
22926 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22927 		} else if (PROTO == IPPROTO_SCTP &&
22928 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22929 			sctp_hdr_t	*sctph;
22930 
22931 			hlen = (V_HLEN & 0xF) << 2;
22932 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22933 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22934 			sctph->sh_chksum = 0;
22935 #ifdef	DEBUG
22936 			if (!skip_sctp_cksum)
22937 #endif
22938 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22939 		} else {
22940 			queue_t	*dev_q = stq->q_next;
22941 
22942 			if (!ILL_DIRECT_CAPABLE((ill_t *)stq->q_ptr) &&
22943 			    (DEV_Q_FLOW_BLOCKED(dev_q))) {
22944 blocked:
22945 				ipha->ipha_ident = ip_hdr_included;
22946 				/*
22947 				 * If we don't have a conn to apply
22948 				 * backpressure, free the message.
22949 				 * In the ire_send path, we don't know
22950 				 * the position to requeue the packet. Rather
22951 				 * than reorder packets, we just drop this
22952 				 * packet.
22953 				 */
22954 				if (ipst->ips_ip_output_queue &&
22955 				    connp != NULL &&
22956 				    caller != IRE_SEND) {
22957 					if (caller == IP_WSRV) {
22958 						idl_tx_list_t *idl_txl;
22959 
22960 						idl_txl =
22961 						    &ipst->ips_idl_tx_list[0];
22962 						connp->conn_did_putbq = 1;
22963 						(void) putbq(connp->conn_wq,
22964 						    first_mp);
22965 						conn_drain_insert(connp,
22966 						    idl_txl);
22967 						/*
22968 						 * This is the service thread,
22969 						 * and the queue is already
22970 						 * noenabled. The check for
22971 						 * canput and the putbq is not
22972 						 * atomic. So we need to check
22973 						 * again.
22974 						 */
22975 						if (canput(stq->q_next))
22976 							connp->conn_did_putbq
22977 							    = 0;
22978 						IP_STAT(ipst, ip_conn_flputbq);
22979 					} else {
22980 						/*
22981 						 * We are not the service proc.
22982 						 * ip_wsrv will be scheduled or
22983 						 * is already running.
22984 						 */
22985 
22986 						(void) putq(connp->conn_wq,
22987 						    first_mp);
22988 					}
22989 				} else {
22990 					out_ill = (ill_t *)stq->q_ptr;
22991 					BUMP_MIB(out_ill->ill_ip_mib,
22992 					    ipIfStatsOutDiscards);
22993 					freemsg(first_mp);
22994 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22995 					    "ip_wput_ire_end: q %p (%S)",
22996 					    q, "discard");
22997 				}
22998 				ire_refrele(ire);
22999 				if (next_mp) {
23000 					ire_refrele(ire1);
23001 					freemsg(next_mp);
23002 				}
23003 				if (conn_outgoing_ill != NULL)
23004 					ill_refrele(conn_outgoing_ill);
23005 				return;
23006 			}
23007 			if ((PROTO == IPPROTO_UDP) &&
23008 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23009 				/*
23010 				 * hlen gets the number of uchar_ts in the
23011 				 * IP header
23012 				 */
23013 				hlen = (V_HLEN & 0xF) << 2;
23014 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23015 				max_frag = ire->ire_max_frag;
23016 				if (*up != 0) {
23017 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
23018 					    up, PROTO, hlen, LENGTH, max_frag,
23019 					    ipsec_len, cksum);
23020 					/* Software checksum? */
23021 					if (DB_CKSUMFLAGS(mp) == 0) {
23022 						IP_STAT(ipst, ip_out_sw_cksum);
23023 						IP_STAT_UPDATE(ipst,
23024 						    ip_udp_out_sw_cksum_bytes,
23025 						    LENGTH - hlen);
23026 					}
23027 				}
23028 			}
23029 		}
23030 		/*
23031 		 * Need to do this even when fragmenting. The local
23032 		 * loopback can be done without computing checksums
23033 		 * but forwarding out other interface must be done
23034 		 * after the IP checksum (and ULP checksums) have been
23035 		 * computed.
23036 		 *
23037 		 * NOTE : multicast_forward is set only if this packet
23038 		 * originated from ip_wput. For packets originating from
23039 		 * ip_wput_multicast, it is not set.
23040 		 */
23041 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23042 multi_loopback:
23043 			ip2dbg(("ip_wput: multicast, loop %d\n",
23044 			    conn_multicast_loop));
23045 
23046 			/*  Forget header checksum offload */
23047 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23048 
23049 			/*
23050 			 * Local loopback of multicasts?  Check the
23051 			 * ill.
23052 			 *
23053 			 * Note that the loopback function will not come
23054 			 * in through ip_rput - it will only do the
23055 			 * client fanout thus we need to do an mforward
23056 			 * as well.  The is different from the BSD
23057 			 * logic.
23058 			 */
23059 			if (ill != NULL) {
23060 				if (ilm_lookup_ill(ill, ipha->ipha_dst,
23061 				    ALL_ZONES) != NULL) {
23062 					/*
23063 					 * Pass along the virtual output q.
23064 					 * ip_wput_local() will distribute the
23065 					 * packet to all the matching zones,
23066 					 * except the sending zone when
23067 					 * IP_MULTICAST_LOOP is false.
23068 					 */
23069 					ip_multicast_loopback(q, ill, first_mp,
23070 					    conn_multicast_loop ? 0 :
23071 					    IP_FF_NO_MCAST_LOOP, zoneid);
23072 				}
23073 			}
23074 			if (ipha->ipha_ttl == 0) {
23075 				/*
23076 				 * 0 => only to this host i.e. we are
23077 				 * done. We are also done if this was the
23078 				 * loopback interface since it is sufficient
23079 				 * to loopback one copy of a multicast packet.
23080 				 */
23081 				freemsg(first_mp);
23082 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23083 				    "ip_wput_ire_end: q %p (%S)",
23084 				    q, "loopback");
23085 				ire_refrele(ire);
23086 				if (conn_outgoing_ill != NULL)
23087 					ill_refrele(conn_outgoing_ill);
23088 				return;
23089 			}
23090 			/*
23091 			 * ILLF_MULTICAST is checked in ip_newroute
23092 			 * i.e. we don't need to check it here since
23093 			 * all IRE_CACHEs come from ip_newroute.
23094 			 * For multicast traffic, SO_DONTROUTE is interpreted
23095 			 * to mean only send the packet out the interface
23096 			 * (optionally specified with IP_MULTICAST_IF)
23097 			 * and do not forward it out additional interfaces.
23098 			 * RSVP and the rsvp daemon is an example of a
23099 			 * protocol and user level process that
23100 			 * handles it's own routing. Hence, it uses the
23101 			 * SO_DONTROUTE option to accomplish this.
23102 			 */
23103 
23104 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23105 			    ill != NULL) {
23106 				/* Unconditionally redo the checksum */
23107 				ipha->ipha_hdr_checksum = 0;
23108 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23109 
23110 				/*
23111 				 * If this needs to go out secure, we need
23112 				 * to wait till we finish the IPsec
23113 				 * processing.
23114 				 */
23115 				if (ipsec_len == 0 &&
23116 				    ip_mforward(ill, ipha, mp)) {
23117 					freemsg(first_mp);
23118 					ip1dbg(("ip_wput: mforward failed\n"));
23119 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23120 					    "ip_wput_ire_end: q %p (%S)",
23121 					    q, "mforward failed");
23122 					ire_refrele(ire);
23123 					if (conn_outgoing_ill != NULL)
23124 						ill_refrele(conn_outgoing_ill);
23125 					return;
23126 				}
23127 			}
23128 		}
23129 		max_frag = ire->ire_max_frag;
23130 		cksum += ttl_protocol;
23131 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23132 			/* No fragmentation required for this one. */
23133 			/*
23134 			 * Don't use frag_flag if packet is pre-built or source
23135 			 * routed or if multicast (since multicast packets do
23136 			 * not solicit ICMP "packet too big" messages).
23137 			 */
23138 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23139 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23140 			    !ip_source_route_included(ipha)) &&
23141 			    !CLASSD(ipha->ipha_dst))
23142 				ipha->ipha_fragment_offset_and_flags |=
23143 				    htons(ire->ire_frag_flag);
23144 
23145 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23146 				/* Complete the IP header checksum. */
23147 				cksum += ipha->ipha_ident;
23148 				cksum += (v_hlen_tos_len >> 16)+
23149 				    (v_hlen_tos_len & 0xFFFF);
23150 				cksum += ipha->ipha_fragment_offset_and_flags;
23151 				hlen = (V_HLEN & 0xF) -
23152 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23153 				if (hlen) {
23154 checksumoptions:
23155 					/*
23156 					 * Account for the IP Options in the IP
23157 					 * header checksum.
23158 					 */
23159 					up = (uint16_t *)(rptr+
23160 					    IP_SIMPLE_HDR_LENGTH);
23161 					do {
23162 						cksum += up[0];
23163 						cksum += up[1];
23164 						up += 2;
23165 					} while (--hlen);
23166 				}
23167 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23168 				cksum = ~(cksum + (cksum >> 16));
23169 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23170 			}
23171 			if (ipsec_len != 0) {
23172 				ipsec_out_process(q, first_mp, ire, ill_index);
23173 				if (!next_mp) {
23174 					ire_refrele(ire);
23175 					if (conn_outgoing_ill != NULL)
23176 						ill_refrele(conn_outgoing_ill);
23177 					return;
23178 				}
23179 				goto next;
23180 			}
23181 
23182 			/*
23183 			 * multirt_send has already been handled
23184 			 * for broadcast, but not yet for multicast
23185 			 * or IP options.
23186 			 */
23187 			if (next_mp == NULL) {
23188 				if (ire->ire_flags & RTF_MULTIRT) {
23189 					multirt_send = B_TRUE;
23190 				}
23191 			}
23192 
23193 			/*
23194 			 * In most cases, the emission loop below is
23195 			 * entered only once. Only in the case where
23196 			 * the ire holds the RTF_MULTIRT flag, do we loop
23197 			 * to process all RTF_MULTIRT ires in the bucket,
23198 			 * and send the packet through all crossed
23199 			 * RTF_MULTIRT routes.
23200 			 */
23201 			do {
23202 				if (multirt_send) {
23203 					irb_t *irb;
23204 
23205 					irb = ire->ire_bucket;
23206 					ASSERT(irb != NULL);
23207 					/*
23208 					 * We are in a multiple send case,
23209 					 * need to get the next IRE and make
23210 					 * a duplicate of the packet.
23211 					 */
23212 					IRB_REFHOLD(irb);
23213 					for (ire1 = ire->ire_next;
23214 					    ire1 != NULL;
23215 					    ire1 = ire1->ire_next) {
23216 						if (!(ire1->ire_flags &
23217 						    RTF_MULTIRT))
23218 							continue;
23219 
23220 						if (ire1->ire_addr !=
23221 						    ire->ire_addr)
23222 							continue;
23223 
23224 						if (ire1->ire_marks &
23225 						    (IRE_MARK_CONDEMNED |
23226 						    IRE_MARK_TESTHIDDEN))
23227 							continue;
23228 
23229 						/* Got one */
23230 						IRE_REFHOLD(ire1);
23231 						break;
23232 					}
23233 					IRB_REFRELE(irb);
23234 
23235 					if (ire1 != NULL) {
23236 						next_mp = copyb(mp);
23237 						if ((next_mp == NULL) ||
23238 						    ((mp->b_cont != NULL) &&
23239 						    ((next_mp->b_cont =
23240 						    dupmsg(mp->b_cont))
23241 						    == NULL))) {
23242 							freemsg(next_mp);
23243 							next_mp = NULL;
23244 							ire_refrele(ire1);
23245 							ire1 = NULL;
23246 						}
23247 					}
23248 
23249 					/*
23250 					 * Last multiroute ire; don't loop
23251 					 * anymore. The emission is over
23252 					 * and next_mp is NULL.
23253 					 */
23254 					if (ire1 == NULL) {
23255 						multirt_send = B_FALSE;
23256 					}
23257 				}
23258 
23259 				out_ill = ire_to_ill(ire);
23260 				DTRACE_PROBE4(ip4__physical__out__start,
23261 				    ill_t *, NULL,
23262 				    ill_t *, out_ill,
23263 				    ipha_t *, ipha, mblk_t *, mp);
23264 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23265 				    ipst->ips_ipv4firewall_physical_out,
23266 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23267 				DTRACE_PROBE1(ip4__physical__out__end,
23268 				    mblk_t *, mp);
23269 				if (mp == NULL)
23270 					goto release_ire_and_ill_2;
23271 
23272 				ASSERT(ipsec_len == 0);
23273 				mp->b_prev =
23274 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23275 				DTRACE_PROBE2(ip__xmit__2,
23276 				    mblk_t *, mp, ire_t *, ire);
23277 				pktxmit_state = ip_xmit_v4(mp, ire,
23278 				    NULL, B_TRUE, connp);
23279 				if ((pktxmit_state == SEND_FAILED) ||
23280 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23281 release_ire_and_ill_2:
23282 					if (next_mp) {
23283 						freemsg(next_mp);
23284 						ire_refrele(ire1);
23285 					}
23286 					ire_refrele(ire);
23287 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23288 					    "ip_wput_ire_end: q %p (%S)",
23289 					    q, "discard MDATA");
23290 					if (conn_outgoing_ill != NULL)
23291 						ill_refrele(conn_outgoing_ill);
23292 					return;
23293 				}
23294 
23295 				if (CLASSD(dst)) {
23296 					BUMP_MIB(out_ill->ill_ip_mib,
23297 					    ipIfStatsHCOutMcastPkts);
23298 					UPDATE_MIB(out_ill->ill_ip_mib,
23299 					    ipIfStatsHCOutMcastOctets,
23300 					    LENGTH);
23301 				} else if (ire->ire_type == IRE_BROADCAST) {
23302 					BUMP_MIB(out_ill->ill_ip_mib,
23303 					    ipIfStatsHCOutBcastPkts);
23304 				}
23305 
23306 				if (multirt_send) {
23307 					/*
23308 					 * We are in a multiple send case,
23309 					 * need to re-enter the sending loop
23310 					 * using the next ire.
23311 					 */
23312 					ire_refrele(ire);
23313 					ire = ire1;
23314 					stq = ire->ire_stq;
23315 					mp = next_mp;
23316 					next_mp = NULL;
23317 					ipha = (ipha_t *)mp->b_rptr;
23318 					ill_index = Q_TO_INDEX(stq);
23319 				}
23320 			} while (multirt_send);
23321 
23322 			if (!next_mp) {
23323 				/*
23324 				 * Last copy going out (the ultra-common
23325 				 * case).  Note that we intentionally replicate
23326 				 * the putnext rather than calling it before
23327 				 * the next_mp check in hopes of a little
23328 				 * tail-call action out of the compiler.
23329 				 */
23330 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23331 				    "ip_wput_ire_end: q %p (%S)",
23332 				    q, "last copy out(1)");
23333 				ire_refrele(ire);
23334 				if (conn_outgoing_ill != NULL)
23335 					ill_refrele(conn_outgoing_ill);
23336 				return;
23337 			}
23338 			/* More copies going out below. */
23339 		} else {
23340 			int offset;
23341 fragmentit:
23342 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23343 			/*
23344 			 * If this would generate a icmp_frag_needed message,
23345 			 * we need to handle it before we do the IPsec
23346 			 * processing. Otherwise, we need to strip the IPsec
23347 			 * headers before we send up the message to the ULPs
23348 			 * which becomes messy and difficult.
23349 			 */
23350 			if (ipsec_len != 0) {
23351 				if ((max_frag < (unsigned int)(LENGTH +
23352 				    ipsec_len)) && (offset & IPH_DF)) {
23353 					out_ill = (ill_t *)stq->q_ptr;
23354 					BUMP_MIB(out_ill->ill_ip_mib,
23355 					    ipIfStatsOutFragFails);
23356 					BUMP_MIB(out_ill->ill_ip_mib,
23357 					    ipIfStatsOutFragReqds);
23358 					ipha->ipha_hdr_checksum = 0;
23359 					ipha->ipha_hdr_checksum =
23360 					    (uint16_t)ip_csum_hdr(ipha);
23361 					icmp_frag_needed(ire->ire_stq, first_mp,
23362 					    max_frag, zoneid, ipst);
23363 					if (!next_mp) {
23364 						ire_refrele(ire);
23365 						if (conn_outgoing_ill != NULL) {
23366 							ill_refrele(
23367 							    conn_outgoing_ill);
23368 						}
23369 						return;
23370 					}
23371 				} else {
23372 					/*
23373 					 * This won't cause a icmp_frag_needed
23374 					 * message. to be generated. Send it on
23375 					 * the wire. Note that this could still
23376 					 * cause fragmentation and all we
23377 					 * do is the generation of the message
23378 					 * to the ULP if needed before IPsec.
23379 					 */
23380 					if (!next_mp) {
23381 						ipsec_out_process(q, first_mp,
23382 						    ire, ill_index);
23383 						TRACE_2(TR_FAC_IP,
23384 						    TR_IP_WPUT_IRE_END,
23385 						    "ip_wput_ire_end: q %p "
23386 						    "(%S)", q,
23387 						    "last ipsec_out_process");
23388 						ire_refrele(ire);
23389 						if (conn_outgoing_ill != NULL) {
23390 							ill_refrele(
23391 							    conn_outgoing_ill);
23392 						}
23393 						return;
23394 					}
23395 					ipsec_out_process(q, first_mp,
23396 					    ire, ill_index);
23397 				}
23398 			} else {
23399 				/*
23400 				 * Initiate IPPF processing. For
23401 				 * fragmentable packets we finish
23402 				 * all QOS packet processing before
23403 				 * calling:
23404 				 * ip_wput_ire_fragmentit->ip_wput_frag
23405 				 */
23406 
23407 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23408 					ip_process(IPP_LOCAL_OUT, &mp,
23409 					    ill_index);
23410 					if (mp == NULL) {
23411 						out_ill = (ill_t *)stq->q_ptr;
23412 						BUMP_MIB(out_ill->ill_ip_mib,
23413 						    ipIfStatsOutDiscards);
23414 						if (next_mp != NULL) {
23415 							freemsg(next_mp);
23416 							ire_refrele(ire1);
23417 						}
23418 						ire_refrele(ire);
23419 						TRACE_2(TR_FAC_IP,
23420 						    TR_IP_WPUT_IRE_END,
23421 						    "ip_wput_ire: q %p (%S)",
23422 						    q, "discard MDATA");
23423 						if (conn_outgoing_ill != NULL) {
23424 							ill_refrele(
23425 							    conn_outgoing_ill);
23426 						}
23427 						return;
23428 					}
23429 				}
23430 				if (!next_mp) {
23431 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23432 					    "ip_wput_ire_end: q %p (%S)",
23433 					    q, "last fragmentation");
23434 					ip_wput_ire_fragmentit(mp, ire,
23435 					    zoneid, ipst, connp);
23436 					ire_refrele(ire);
23437 					if (conn_outgoing_ill != NULL)
23438 						ill_refrele(conn_outgoing_ill);
23439 					return;
23440 				}
23441 				ip_wput_ire_fragmentit(mp, ire,
23442 				    zoneid, ipst, connp);
23443 			}
23444 		}
23445 	} else {
23446 nullstq:
23447 		/* A NULL stq means the destination address is local. */
23448 		UPDATE_OB_PKT_COUNT(ire);
23449 		ire->ire_last_used_time = lbolt;
23450 		ASSERT(ire->ire_ipif != NULL);
23451 		if (!next_mp) {
23452 			/*
23453 			 * Is there an "in" and "out" for traffic local
23454 			 * to a host (loopback)?  The code in Solaris doesn't
23455 			 * explicitly draw a line in its code for in vs out,
23456 			 * so we've had to draw a line in the sand: ip_wput_ire
23457 			 * is considered to be the "output" side and
23458 			 * ip_wput_local to be the "input" side.
23459 			 */
23460 			out_ill = ire_to_ill(ire);
23461 
23462 			/*
23463 			 * DTrace this as ip:::send.  A blocked packet will
23464 			 * fire the send probe, but not the receive probe.
23465 			 */
23466 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23467 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23468 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23469 
23470 			DTRACE_PROBE4(ip4__loopback__out__start,
23471 			    ill_t *, NULL, ill_t *, out_ill,
23472 			    ipha_t *, ipha, mblk_t *, first_mp);
23473 
23474 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23475 			    ipst->ips_ipv4firewall_loopback_out,
23476 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23477 
23478 			DTRACE_PROBE1(ip4__loopback__out_end,
23479 			    mblk_t *, first_mp);
23480 
23481 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23482 			    "ip_wput_ire_end: q %p (%S)",
23483 			    q, "local address");
23484 
23485 			if (first_mp != NULL)
23486 				ip_wput_local(q, out_ill, ipha,
23487 				    first_mp, ire, 0, ire->ire_zoneid);
23488 			ire_refrele(ire);
23489 			if (conn_outgoing_ill != NULL)
23490 				ill_refrele(conn_outgoing_ill);
23491 			return;
23492 		}
23493 
23494 		out_ill = ire_to_ill(ire);
23495 
23496 		/*
23497 		 * DTrace this as ip:::send.  A blocked packet will fire the
23498 		 * send probe, but not the receive probe.
23499 		 */
23500 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23501 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23502 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23503 
23504 		DTRACE_PROBE4(ip4__loopback__out__start,
23505 		    ill_t *, NULL, ill_t *, out_ill,
23506 		    ipha_t *, ipha, mblk_t *, first_mp);
23507 
23508 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23509 		    ipst->ips_ipv4firewall_loopback_out,
23510 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23511 
23512 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23513 
23514 		if (first_mp != NULL)
23515 			ip_wput_local(q, out_ill, ipha,
23516 			    first_mp, ire, 0, ire->ire_zoneid);
23517 	}
23518 next:
23519 	/*
23520 	 * More copies going out to additional interfaces.
23521 	 * ire1 has already been held. We don't need the
23522 	 * "ire" anymore.
23523 	 */
23524 	ire_refrele(ire);
23525 	ire = ire1;
23526 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23527 	mp = next_mp;
23528 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23529 	ill = ire_to_ill(ire);
23530 	first_mp = mp;
23531 	if (ipsec_len != 0) {
23532 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23533 		mp = mp->b_cont;
23534 	}
23535 	dst = ire->ire_addr;
23536 	ipha = (ipha_t *)mp->b_rptr;
23537 	/*
23538 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23539 	 * Restore ipha_ident "no checksum" flag.
23540 	 */
23541 	src = orig_src;
23542 	ipha->ipha_ident = ip_hdr_included;
23543 	goto another;
23544 
23545 #undef	rptr
23546 #undef	Q_TO_INDEX
23547 }
23548 
23549 /*
23550  * Routine to allocate a message that is used to notify the ULP about MDT.
23551  * The caller may provide a pointer to the link-layer MDT capabilities,
23552  * or NULL if MDT is to be disabled on the stream.
23553  */
23554 mblk_t *
23555 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23556 {
23557 	mblk_t *mp;
23558 	ip_mdt_info_t *mdti;
23559 	ill_mdt_capab_t *idst;
23560 
23561 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23562 		DB_TYPE(mp) = M_CTL;
23563 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23564 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23565 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23566 		idst = &(mdti->mdt_capab);
23567 
23568 		/*
23569 		 * If the caller provides us with the capability, copy
23570 		 * it over into our notification message; otherwise
23571 		 * we zero out the capability portion.
23572 		 */
23573 		if (isrc != NULL)
23574 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23575 		else
23576 			bzero((caddr_t)idst, sizeof (*idst));
23577 	}
23578 	return (mp);
23579 }
23580 
23581 /*
23582  * Routine which determines whether MDT can be enabled on the destination
23583  * IRE and IPC combination, and if so, allocates and returns the MDT
23584  * notification mblk that may be used by ULP.  We also check if we need to
23585  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23586  * MDT usage in the past have been lifted.  This gets called during IP
23587  * and ULP binding.
23588  */
23589 mblk_t *
23590 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23591     ill_mdt_capab_t *mdt_cap)
23592 {
23593 	mblk_t *mp;
23594 	boolean_t rc = B_FALSE;
23595 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23596 
23597 	ASSERT(dst_ire != NULL);
23598 	ASSERT(connp != NULL);
23599 	ASSERT(mdt_cap != NULL);
23600 
23601 	/*
23602 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23603 	 * Multidata, which is handled in tcp_multisend().  This
23604 	 * is the reason why we do all these checks here, to ensure
23605 	 * that we don't enable Multidata for the cases which we
23606 	 * can't handle at the moment.
23607 	 */
23608 	do {
23609 		/* Only do TCP at the moment */
23610 		if (connp->conn_ulp != IPPROTO_TCP)
23611 			break;
23612 
23613 		/*
23614 		 * IPsec outbound policy present?  Note that we get here
23615 		 * after calling ipsec_conn_cache_policy() where the global
23616 		 * policy checking is performed.  conn_latch will be
23617 		 * non-NULL as long as there's a policy defined,
23618 		 * i.e. conn_out_enforce_policy may be NULL in such case
23619 		 * when the connection is non-secure, and hence we check
23620 		 * further if the latch refers to an outbound policy.
23621 		 */
23622 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23623 			break;
23624 
23625 		/* CGTP (multiroute) is enabled? */
23626 		if (dst_ire->ire_flags & RTF_MULTIRT)
23627 			break;
23628 
23629 		/* Outbound IPQoS enabled? */
23630 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23631 			/*
23632 			 * In this case, we disable MDT for this and all
23633 			 * future connections going over the interface.
23634 			 */
23635 			mdt_cap->ill_mdt_on = 0;
23636 			break;
23637 		}
23638 
23639 		/* socket option(s) present? */
23640 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23641 			break;
23642 
23643 		rc = B_TRUE;
23644 	/* CONSTCOND */
23645 	} while (0);
23646 
23647 	/* Remember the result */
23648 	connp->conn_mdt_ok = rc;
23649 
23650 	if (!rc)
23651 		return (NULL);
23652 	else if (!mdt_cap->ill_mdt_on) {
23653 		/*
23654 		 * If MDT has been previously turned off in the past, and we
23655 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23656 		 * then enable it for this interface.
23657 		 */
23658 		mdt_cap->ill_mdt_on = 1;
23659 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23660 		    "interface %s\n", ill_name));
23661 	}
23662 
23663 	/* Allocate the MDT info mblk */
23664 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23665 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23666 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23667 		return (NULL);
23668 	}
23669 	return (mp);
23670 }
23671 
23672 /*
23673  * Routine to allocate a message that is used to notify the ULP about LSO.
23674  * The caller may provide a pointer to the link-layer LSO capabilities,
23675  * or NULL if LSO is to be disabled on the stream.
23676  */
23677 mblk_t *
23678 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23679 {
23680 	mblk_t *mp;
23681 	ip_lso_info_t *lsoi;
23682 	ill_lso_capab_t *idst;
23683 
23684 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23685 		DB_TYPE(mp) = M_CTL;
23686 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23687 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23688 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23689 		idst = &(lsoi->lso_capab);
23690 
23691 		/*
23692 		 * If the caller provides us with the capability, copy
23693 		 * it over into our notification message; otherwise
23694 		 * we zero out the capability portion.
23695 		 */
23696 		if (isrc != NULL)
23697 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23698 		else
23699 			bzero((caddr_t)idst, sizeof (*idst));
23700 	}
23701 	return (mp);
23702 }
23703 
23704 /*
23705  * Routine which determines whether LSO can be enabled on the destination
23706  * IRE and IPC combination, and if so, allocates and returns the LSO
23707  * notification mblk that may be used by ULP.  We also check if we need to
23708  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23709  * LSO usage in the past have been lifted.  This gets called during IP
23710  * and ULP binding.
23711  */
23712 mblk_t *
23713 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23714     ill_lso_capab_t *lso_cap)
23715 {
23716 	mblk_t *mp;
23717 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23718 
23719 	ASSERT(dst_ire != NULL);
23720 	ASSERT(connp != NULL);
23721 	ASSERT(lso_cap != NULL);
23722 
23723 	connp->conn_lso_ok = B_TRUE;
23724 
23725 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23726 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23727 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23728 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23729 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23730 		connp->conn_lso_ok = B_FALSE;
23731 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23732 			/*
23733 			 * Disable LSO for this and all future connections going
23734 			 * over the interface.
23735 			 */
23736 			lso_cap->ill_lso_on = 0;
23737 		}
23738 	}
23739 
23740 	if (!connp->conn_lso_ok)
23741 		return (NULL);
23742 	else if (!lso_cap->ill_lso_on) {
23743 		/*
23744 		 * If LSO has been previously turned off in the past, and we
23745 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23746 		 * then enable it for this interface.
23747 		 */
23748 		lso_cap->ill_lso_on = 1;
23749 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23750 		    ill_name));
23751 	}
23752 
23753 	/* Allocate the LSO info mblk */
23754 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23755 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23756 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23757 
23758 	return (mp);
23759 }
23760 
23761 /*
23762  * Create destination address attribute, and fill it with the physical
23763  * destination address and SAP taken from the template DL_UNITDATA_REQ
23764  * message block.
23765  */
23766 boolean_t
23767 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23768 {
23769 	dl_unitdata_req_t *dlurp;
23770 	pattr_t *pa;
23771 	pattrinfo_t pa_info;
23772 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23773 	uint_t das_len, das_off;
23774 
23775 	ASSERT(dlmp != NULL);
23776 
23777 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23778 	das_len = dlurp->dl_dest_addr_length;
23779 	das_off = dlurp->dl_dest_addr_offset;
23780 
23781 	pa_info.type = PATTR_DSTADDRSAP;
23782 	pa_info.len = sizeof (**das) + das_len - 1;
23783 
23784 	/* create and associate the attribute */
23785 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23786 	if (pa != NULL) {
23787 		ASSERT(*das != NULL);
23788 		(*das)->addr_is_group = 0;
23789 		(*das)->addr_len = (uint8_t)das_len;
23790 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23791 	}
23792 
23793 	return (pa != NULL);
23794 }
23795 
23796 /*
23797  * Create hardware checksum attribute and fill it with the values passed.
23798  */
23799 boolean_t
23800 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23801     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23802 {
23803 	pattr_t *pa;
23804 	pattrinfo_t pa_info;
23805 
23806 	ASSERT(mmd != NULL);
23807 
23808 	pa_info.type = PATTR_HCKSUM;
23809 	pa_info.len = sizeof (pattr_hcksum_t);
23810 
23811 	/* create and associate the attribute */
23812 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23813 	if (pa != NULL) {
23814 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23815 
23816 		hck->hcksum_start_offset = start_offset;
23817 		hck->hcksum_stuff_offset = stuff_offset;
23818 		hck->hcksum_end_offset = end_offset;
23819 		hck->hcksum_flags = flags;
23820 	}
23821 	return (pa != NULL);
23822 }
23823 
23824 /*
23825  * Create zerocopy attribute and fill it with the specified flags
23826  */
23827 boolean_t
23828 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23829 {
23830 	pattr_t *pa;
23831 	pattrinfo_t pa_info;
23832 
23833 	ASSERT(mmd != NULL);
23834 	pa_info.type = PATTR_ZCOPY;
23835 	pa_info.len = sizeof (pattr_zcopy_t);
23836 
23837 	/* create and associate the attribute */
23838 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23839 	if (pa != NULL) {
23840 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23841 
23842 		zcopy->zcopy_flags = flags;
23843 	}
23844 	return (pa != NULL);
23845 }
23846 
23847 /*
23848  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23849  * block chain. We could rewrite to handle arbitrary message block chains but
23850  * that would make the code complicated and slow. Right now there three
23851  * restrictions:
23852  *
23853  *   1. The first message block must contain the complete IP header and
23854  *	at least 1 byte of payload data.
23855  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23856  *	so that we can use a single Multidata message.
23857  *   3. No frag must be distributed over two or more message blocks so
23858  *	that we don't need more than two packet descriptors per frag.
23859  *
23860  * The above restrictions allow us to support userland applications (which
23861  * will send down a single message block) and NFS over UDP (which will
23862  * send down a chain of at most three message blocks).
23863  *
23864  * We also don't use MDT for payloads with less than or equal to
23865  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23866  */
23867 boolean_t
23868 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23869 {
23870 	int	blocks;
23871 	ssize_t	total, missing, size;
23872 
23873 	ASSERT(mp != NULL);
23874 	ASSERT(hdr_len > 0);
23875 
23876 	size = MBLKL(mp) - hdr_len;
23877 	if (size <= 0)
23878 		return (B_FALSE);
23879 
23880 	/* The first mblk contains the header and some payload. */
23881 	blocks = 1;
23882 	total = size;
23883 	size %= len;
23884 	missing = (size == 0) ? 0 : (len - size);
23885 	mp = mp->b_cont;
23886 
23887 	while (mp != NULL) {
23888 		/*
23889 		 * Give up if we encounter a zero length message block.
23890 		 * In practice, this should rarely happen and therefore
23891 		 * not worth the trouble of freeing and re-linking the
23892 		 * mblk from the chain to handle such case.
23893 		 */
23894 		if ((size = MBLKL(mp)) == 0)
23895 			return (B_FALSE);
23896 
23897 		/* Too many payload buffers for a single Multidata message? */
23898 		if (++blocks > MULTIDATA_MAX_PBUFS)
23899 			return (B_FALSE);
23900 
23901 		total += size;
23902 		/* Is a frag distributed over two or more message blocks? */
23903 		if (missing > size)
23904 			return (B_FALSE);
23905 		size -= missing;
23906 
23907 		size %= len;
23908 		missing = (size == 0) ? 0 : (len - size);
23909 
23910 		mp = mp->b_cont;
23911 	}
23912 
23913 	return (total > ip_wput_frag_mdt_min);
23914 }
23915 
23916 /*
23917  * Outbound IPv4 fragmentation routine using MDT.
23918  */
23919 static void
23920 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23921     uint32_t frag_flag, int offset)
23922 {
23923 	ipha_t		*ipha_orig;
23924 	int		i1, ip_data_end;
23925 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23926 	mblk_t		*hdr_mp, *md_mp = NULL;
23927 	unsigned char	*hdr_ptr, *pld_ptr;
23928 	multidata_t	*mmd;
23929 	ip_pdescinfo_t	pdi;
23930 	ill_t		*ill;
23931 	ip_stack_t	*ipst = ire->ire_ipst;
23932 
23933 	ASSERT(DB_TYPE(mp) == M_DATA);
23934 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23935 
23936 	ill = ire_to_ill(ire);
23937 	ASSERT(ill != NULL);
23938 
23939 	ipha_orig = (ipha_t *)mp->b_rptr;
23940 	mp->b_rptr += sizeof (ipha_t);
23941 
23942 	/* Calculate how many packets we will send out */
23943 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23944 	pkts = (i1 + len - 1) / len;
23945 	ASSERT(pkts > 1);
23946 
23947 	/* Allocate a message block which will hold all the IP Headers. */
23948 	wroff = ipst->ips_ip_wroff_extra;
23949 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23950 
23951 	i1 = pkts * hdr_chunk_len;
23952 	/*
23953 	 * Create the header buffer, Multidata and destination address
23954 	 * and SAP attribute that should be associated with it.
23955 	 */
23956 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23957 	    ((hdr_mp->b_wptr += i1),
23958 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23959 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23960 		freemsg(mp);
23961 		if (md_mp == NULL) {
23962 			freemsg(hdr_mp);
23963 		} else {
23964 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23965 			freemsg(md_mp);
23966 		}
23967 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23968 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23969 		return;
23970 	}
23971 	IP_STAT(ipst, ip_frag_mdt_allocd);
23972 
23973 	/*
23974 	 * Add a payload buffer to the Multidata; this operation must not
23975 	 * fail, or otherwise our logic in this routine is broken.  There
23976 	 * is no memory allocation done by the routine, so any returned
23977 	 * failure simply tells us that we've done something wrong.
23978 	 *
23979 	 * A failure tells us that either we're adding the same payload
23980 	 * buffer more than once, or we're trying to add more buffers than
23981 	 * allowed.  None of the above cases should happen, and we panic
23982 	 * because either there's horrible heap corruption, and/or
23983 	 * programming mistake.
23984 	 */
23985 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23986 		goto pbuf_panic;
23987 
23988 	hdr_ptr = hdr_mp->b_rptr;
23989 	pld_ptr = mp->b_rptr;
23990 
23991 	/* Establish the ending byte offset, based on the starting offset. */
23992 	offset <<= 3;
23993 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23994 	    IP_SIMPLE_HDR_LENGTH;
23995 
23996 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23997 
23998 	while (pld_ptr < mp->b_wptr) {
23999 		ipha_t		*ipha;
24000 		uint16_t	offset_and_flags;
24001 		uint16_t	ip_len;
24002 		int		error;
24003 
24004 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24005 		ipha = (ipha_t *)(hdr_ptr + wroff);
24006 		ASSERT(OK_32PTR(ipha));
24007 		*ipha = *ipha_orig;
24008 
24009 		if (ip_data_end - offset > len) {
24010 			offset_and_flags = IPH_MF;
24011 		} else {
24012 			/*
24013 			 * Last frag. Set len to the length of this last piece.
24014 			 */
24015 			len = ip_data_end - offset;
24016 			/* A frag of a frag might have IPH_MF non-zero */
24017 			offset_and_flags =
24018 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24019 			    IPH_MF;
24020 		}
24021 		offset_and_flags |= (uint16_t)(offset >> 3);
24022 		offset_and_flags |= (uint16_t)frag_flag;
24023 		/* Store the offset and flags in the IP header. */
24024 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24025 
24026 		/* Store the length in the IP header. */
24027 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24028 		ipha->ipha_length = htons(ip_len);
24029 
24030 		/*
24031 		 * Set the IP header checksum.  Note that mp is just
24032 		 * the header, so this is easy to pass to ip_csum.
24033 		 */
24034 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24035 
24036 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24037 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24038 		    NULL, int, 0);
24039 
24040 		/*
24041 		 * Record offset and size of header and data of the next packet
24042 		 * in the multidata message.
24043 		 */
24044 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24045 		PDESC_PLD_INIT(&pdi);
24046 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24047 		ASSERT(i1 > 0);
24048 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24049 		if (i1 == len) {
24050 			pld_ptr += len;
24051 		} else {
24052 			i1 = len - i1;
24053 			mp = mp->b_cont;
24054 			ASSERT(mp != NULL);
24055 			ASSERT(MBLKL(mp) >= i1);
24056 			/*
24057 			 * Attach the next payload message block to the
24058 			 * multidata message.
24059 			 */
24060 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24061 				goto pbuf_panic;
24062 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24063 			pld_ptr = mp->b_rptr + i1;
24064 		}
24065 
24066 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24067 		    KM_NOSLEEP)) == NULL) {
24068 			/*
24069 			 * Any failure other than ENOMEM indicates that we
24070 			 * have passed in invalid pdesc info or parameters
24071 			 * to mmd_addpdesc, which must not happen.
24072 			 *
24073 			 * EINVAL is a result of failure on boundary checks
24074 			 * against the pdesc info contents.  It should not
24075 			 * happen, and we panic because either there's
24076 			 * horrible heap corruption, and/or programming
24077 			 * mistake.
24078 			 */
24079 			if (error != ENOMEM) {
24080 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24081 				    "pdesc logic error detected for "
24082 				    "mmd %p pinfo %p (%d)\n",
24083 				    (void *)mmd, (void *)&pdi, error);
24084 				/* NOTREACHED */
24085 			}
24086 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24087 			/* Free unattached payload message blocks as well */
24088 			md_mp->b_cont = mp->b_cont;
24089 			goto free_mmd;
24090 		}
24091 
24092 		/* Advance fragment offset. */
24093 		offset += len;
24094 
24095 		/* Advance to location for next header in the buffer. */
24096 		hdr_ptr += hdr_chunk_len;
24097 
24098 		/* Did we reach the next payload message block? */
24099 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24100 			mp = mp->b_cont;
24101 			/*
24102 			 * Attach the next message block with payload
24103 			 * data to the multidata message.
24104 			 */
24105 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24106 				goto pbuf_panic;
24107 			pld_ptr = mp->b_rptr;
24108 		}
24109 	}
24110 
24111 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24112 	ASSERT(mp->b_wptr == pld_ptr);
24113 
24114 	/* Update IP statistics */
24115 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24116 
24117 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24118 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24119 
24120 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24121 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24122 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24123 
24124 	if (pkt_type == OB_PKT) {
24125 		ire->ire_ob_pkt_count += pkts;
24126 		if (ire->ire_ipif != NULL)
24127 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24128 	} else {
24129 		/* The type is IB_PKT in the forwarding path. */
24130 		ire->ire_ib_pkt_count += pkts;
24131 		ASSERT(!IRE_IS_LOCAL(ire));
24132 		if (ire->ire_type & IRE_BROADCAST) {
24133 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24134 		} else {
24135 			UPDATE_MIB(ill->ill_ip_mib,
24136 			    ipIfStatsHCOutForwDatagrams, pkts);
24137 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24138 		}
24139 	}
24140 	ire->ire_last_used_time = lbolt;
24141 	/* Send it down */
24142 	putnext(ire->ire_stq, md_mp);
24143 	return;
24144 
24145 pbuf_panic:
24146 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24147 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24148 	    pbuf_idx);
24149 	/* NOTREACHED */
24150 }
24151 
24152 /*
24153  * Outbound IP fragmentation routine.
24154  *
24155  * NOTE : This routine does not ire_refrele the ire that is passed in
24156  * as the argument.
24157  */
24158 static void
24159 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24160     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24161 {
24162 	int		i1;
24163 	mblk_t		*ll_hdr_mp;
24164 	int 		ll_hdr_len;
24165 	int		hdr_len;
24166 	mblk_t		*hdr_mp;
24167 	ipha_t		*ipha;
24168 	int		ip_data_end;
24169 	int		len;
24170 	mblk_t		*mp = mp_orig, *mp1;
24171 	int		offset;
24172 	queue_t		*q;
24173 	uint32_t	v_hlen_tos_len;
24174 	mblk_t		*first_mp;
24175 	boolean_t	mctl_present;
24176 	ill_t		*ill;
24177 	ill_t		*out_ill;
24178 	mblk_t		*xmit_mp;
24179 	mblk_t		*carve_mp;
24180 	ire_t		*ire1 = NULL;
24181 	ire_t		*save_ire = NULL;
24182 	mblk_t  	*next_mp = NULL;
24183 	boolean_t	last_frag = B_FALSE;
24184 	boolean_t	multirt_send = B_FALSE;
24185 	ire_t		*first_ire = NULL;
24186 	irb_t		*irb = NULL;
24187 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24188 
24189 	ill = ire_to_ill(ire);
24190 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24191 
24192 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24193 
24194 	if (max_frag == 0) {
24195 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24196 		    " -  dropping packet\n"));
24197 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24198 		freemsg(mp);
24199 		return;
24200 	}
24201 
24202 	/*
24203 	 * IPsec does not allow hw accelerated packets to be fragmented
24204 	 * This check is made in ip_wput_ipsec_out prior to coming here
24205 	 * via ip_wput_ire_fragmentit.
24206 	 *
24207 	 * If at this point we have an ire whose ARP request has not
24208 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24209 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24210 	 * This packet and all fragmentable packets for this ire will
24211 	 * continue to get dropped while ire_nce->nce_state remains in
24212 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24213 	 * ND_REACHABLE, all subsquent large packets for this ire will
24214 	 * get fragemented and sent out by this function.
24215 	 */
24216 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24217 		/* If nce_state is ND_INITIAL, trigger ARP query */
24218 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24219 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24220 		    " -  dropping packet\n"));
24221 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24222 		freemsg(mp);
24223 		return;
24224 	}
24225 
24226 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24227 	    "ip_wput_frag_start:");
24228 
24229 	if (mp->b_datap->db_type == M_CTL) {
24230 		first_mp = mp;
24231 		mp_orig = mp = mp->b_cont;
24232 		mctl_present = B_TRUE;
24233 	} else {
24234 		first_mp = mp;
24235 		mctl_present = B_FALSE;
24236 	}
24237 
24238 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24239 	ipha = (ipha_t *)mp->b_rptr;
24240 
24241 	/*
24242 	 * If the Don't Fragment flag is on, generate an ICMP destination
24243 	 * unreachable, fragmentation needed.
24244 	 */
24245 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24246 	if (offset & IPH_DF) {
24247 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24248 		if (is_system_labeled()) {
24249 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24250 			    ire->ire_max_frag - max_frag, AF_INET);
24251 		}
24252 		/*
24253 		 * Need to compute hdr checksum if called from ip_wput_ire.
24254 		 * Note that ip_rput_forward verifies the checksum before
24255 		 * calling this routine so in that case this is a noop.
24256 		 */
24257 		ipha->ipha_hdr_checksum = 0;
24258 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24259 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24260 		    ipst);
24261 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24262 		    "ip_wput_frag_end:(%S)",
24263 		    "don't fragment");
24264 		return;
24265 	}
24266 	/*
24267 	 * Labeled systems adjust max_frag if they add a label
24268 	 * to send the correct path mtu.  We need the real mtu since we
24269 	 * are fragmenting the packet after label adjustment.
24270 	 */
24271 	if (is_system_labeled())
24272 		max_frag = ire->ire_max_frag;
24273 	if (mctl_present)
24274 		freeb(first_mp);
24275 	/*
24276 	 * Establish the starting offset.  May not be zero if we are fragging
24277 	 * a fragment that is being forwarded.
24278 	 */
24279 	offset = offset & IPH_OFFSET;
24280 
24281 	/* TODO why is this test needed? */
24282 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24283 	if (((max_frag - LENGTH) & ~7) < 8) {
24284 		/* TODO: notify ulp somehow */
24285 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24286 		freemsg(mp);
24287 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24288 		    "ip_wput_frag_end:(%S)",
24289 		    "len < 8");
24290 		return;
24291 	}
24292 
24293 	hdr_len = (V_HLEN & 0xF) << 2;
24294 
24295 	ipha->ipha_hdr_checksum = 0;
24296 
24297 	/*
24298 	 * Establish the number of bytes maximum per frag, after putting
24299 	 * in the header.
24300 	 */
24301 	len = (max_frag - hdr_len) & ~7;
24302 
24303 	/* Check if we can use MDT to send out the frags. */
24304 	ASSERT(!IRE_IS_LOCAL(ire));
24305 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24306 	    ipst->ips_ip_multidata_outbound &&
24307 	    !(ire->ire_flags & RTF_MULTIRT) &&
24308 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24309 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24310 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24311 		ASSERT(ill->ill_mdt_capab != NULL);
24312 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24313 			/*
24314 			 * If MDT has been previously turned off in the past,
24315 			 * and we currently can do MDT (due to IPQoS policy
24316 			 * removal, etc.) then enable it for this interface.
24317 			 */
24318 			ill->ill_mdt_capab->ill_mdt_on = 1;
24319 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24320 			    ill->ill_name));
24321 		}
24322 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24323 		    offset);
24324 		return;
24325 	}
24326 
24327 	/* Get a copy of the header for the trailing frags */
24328 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
24329 	    mp);
24330 	if (!hdr_mp) {
24331 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24332 		freemsg(mp);
24333 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24334 		    "ip_wput_frag_end:(%S)",
24335 		    "couldn't copy hdr");
24336 		return;
24337 	}
24338 
24339 	/* Store the starting offset, with the MoreFrags flag. */
24340 	i1 = offset | IPH_MF | frag_flag;
24341 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24342 
24343 	/* Establish the ending byte offset, based on the starting offset. */
24344 	offset <<= 3;
24345 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24346 
24347 	/* Store the length of the first fragment in the IP header. */
24348 	i1 = len + hdr_len;
24349 	ASSERT(i1 <= IP_MAXPACKET);
24350 	ipha->ipha_length = htons((uint16_t)i1);
24351 
24352 	/*
24353 	 * Compute the IP header checksum for the first frag.  We have to
24354 	 * watch out that we stop at the end of the header.
24355 	 */
24356 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24357 
24358 	/*
24359 	 * Now carve off the first frag.  Note that this will include the
24360 	 * original IP header.
24361 	 */
24362 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24363 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24364 		freeb(hdr_mp);
24365 		freemsg(mp_orig);
24366 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24367 		    "ip_wput_frag_end:(%S)",
24368 		    "couldn't carve first");
24369 		return;
24370 	}
24371 
24372 	/*
24373 	 * Multirouting case. Each fragment is replicated
24374 	 * via all non-condemned RTF_MULTIRT routes
24375 	 * currently resolved.
24376 	 * We ensure that first_ire is the first RTF_MULTIRT
24377 	 * ire in the bucket.
24378 	 */
24379 	if (ire->ire_flags & RTF_MULTIRT) {
24380 		irb = ire->ire_bucket;
24381 		ASSERT(irb != NULL);
24382 
24383 		multirt_send = B_TRUE;
24384 
24385 		/* Make sure we do not omit any multiroute ire. */
24386 		IRB_REFHOLD(irb);
24387 		for (first_ire = irb->irb_ire;
24388 		    first_ire != NULL;
24389 		    first_ire = first_ire->ire_next) {
24390 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24391 			    (first_ire->ire_addr == ire->ire_addr) &&
24392 			    !(first_ire->ire_marks &
24393 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
24394 				break;
24395 		}
24396 
24397 		if (first_ire != NULL) {
24398 			if (first_ire != ire) {
24399 				IRE_REFHOLD(first_ire);
24400 				/*
24401 				 * Do not release the ire passed in
24402 				 * as the argument.
24403 				 */
24404 				ire = first_ire;
24405 			} else {
24406 				first_ire = NULL;
24407 			}
24408 		}
24409 		IRB_REFRELE(irb);
24410 
24411 		/*
24412 		 * Save the first ire; we will need to restore it
24413 		 * for the trailing frags.
24414 		 * We REFHOLD save_ire, as each iterated ire will be
24415 		 * REFRELEd.
24416 		 */
24417 		save_ire = ire;
24418 		IRE_REFHOLD(save_ire);
24419 	}
24420 
24421 	/*
24422 	 * First fragment emission loop.
24423 	 * In most cases, the emission loop below is entered only
24424 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24425 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24426 	 * bucket, and send the fragment through all crossed
24427 	 * RTF_MULTIRT routes.
24428 	 */
24429 	do {
24430 		if (ire->ire_flags & RTF_MULTIRT) {
24431 			/*
24432 			 * We are in a multiple send case, need to get
24433 			 * the next ire and make a copy of the packet.
24434 			 * ire1 holds here the next ire to process in the
24435 			 * bucket. If multirouting is expected,
24436 			 * any non-RTF_MULTIRT ire that has the
24437 			 * right destination address is ignored.
24438 			 *
24439 			 * We have to take into account the MTU of
24440 			 * each walked ire. max_frag is set by the
24441 			 * the caller and generally refers to
24442 			 * the primary ire entry. Here we ensure that
24443 			 * no route with a lower MTU will be used, as
24444 			 * fragments are carved once for all ires,
24445 			 * then replicated.
24446 			 */
24447 			ASSERT(irb != NULL);
24448 			IRB_REFHOLD(irb);
24449 			for (ire1 = ire->ire_next;
24450 			    ire1 != NULL;
24451 			    ire1 = ire1->ire_next) {
24452 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24453 					continue;
24454 				if (ire1->ire_addr != ire->ire_addr)
24455 					continue;
24456 				if (ire1->ire_marks &
24457 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
24458 					continue;
24459 				/*
24460 				 * Ensure we do not exceed the MTU
24461 				 * of the next route.
24462 				 */
24463 				if (ire1->ire_max_frag < max_frag) {
24464 					ip_multirt_bad_mtu(ire1, max_frag);
24465 					continue;
24466 				}
24467 
24468 				/* Got one. */
24469 				IRE_REFHOLD(ire1);
24470 				break;
24471 			}
24472 			IRB_REFRELE(irb);
24473 
24474 			if (ire1 != NULL) {
24475 				next_mp = copyb(mp);
24476 				if ((next_mp == NULL) ||
24477 				    ((mp->b_cont != NULL) &&
24478 				    ((next_mp->b_cont =
24479 				    dupmsg(mp->b_cont)) == NULL))) {
24480 					freemsg(next_mp);
24481 					next_mp = NULL;
24482 					ire_refrele(ire1);
24483 					ire1 = NULL;
24484 				}
24485 			}
24486 
24487 			/* Last multiroute ire; don't loop anymore. */
24488 			if (ire1 == NULL) {
24489 				multirt_send = B_FALSE;
24490 			}
24491 		}
24492 
24493 		ll_hdr_len = 0;
24494 		LOCK_IRE_FP_MP(ire);
24495 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24496 		if (ll_hdr_mp != NULL) {
24497 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24498 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24499 		} else {
24500 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24501 		}
24502 
24503 		/* If there is a transmit header, get a copy for this frag. */
24504 		/*
24505 		 * TODO: should check db_ref before calling ip_carve_mp since
24506 		 * it might give us a dup.
24507 		 */
24508 		if (!ll_hdr_mp) {
24509 			/* No xmit header. */
24510 			xmit_mp = mp;
24511 
24512 		/* We have a link-layer header that can fit in our mblk. */
24513 		} else if (mp->b_datap->db_ref == 1 &&
24514 		    ll_hdr_len != 0 &&
24515 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24516 			/* M_DATA fastpath */
24517 			mp->b_rptr -= ll_hdr_len;
24518 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24519 			xmit_mp = mp;
24520 
24521 		/* Corner case if copyb has failed */
24522 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24523 			UNLOCK_IRE_FP_MP(ire);
24524 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24525 			freeb(hdr_mp);
24526 			freemsg(mp);
24527 			freemsg(mp_orig);
24528 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24529 			    "ip_wput_frag_end:(%S)",
24530 			    "discard");
24531 
24532 			if (multirt_send) {
24533 				ASSERT(ire1);
24534 				ASSERT(next_mp);
24535 
24536 				freemsg(next_mp);
24537 				ire_refrele(ire1);
24538 			}
24539 			if (save_ire != NULL)
24540 				IRE_REFRELE(save_ire);
24541 
24542 			if (first_ire != NULL)
24543 				ire_refrele(first_ire);
24544 			return;
24545 
24546 		/*
24547 		 * Case of res_mp OR the fastpath mp can't fit
24548 		 * in the mblk
24549 		 */
24550 		} else {
24551 			xmit_mp->b_cont = mp;
24552 
24553 			/*
24554 			 * Get priority marking, if any.
24555 			 * We propagate the CoS marking from the
24556 			 * original packet that went to QoS processing
24557 			 * in ip_wput_ire to the newly carved mp.
24558 			 */
24559 			if (DB_TYPE(xmit_mp) == M_DATA)
24560 				xmit_mp->b_band = mp->b_band;
24561 		}
24562 		UNLOCK_IRE_FP_MP(ire);
24563 
24564 		q = ire->ire_stq;
24565 		out_ill = (ill_t *)q->q_ptr;
24566 
24567 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24568 
24569 		DTRACE_PROBE4(ip4__physical__out__start,
24570 		    ill_t *, NULL, ill_t *, out_ill,
24571 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24572 
24573 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24574 		    ipst->ips_ipv4firewall_physical_out,
24575 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24576 
24577 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24578 
24579 		if (xmit_mp != NULL) {
24580 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24581 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24582 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24583 
24584 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0, connp);
24585 
24586 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24587 			UPDATE_MIB(out_ill->ill_ip_mib,
24588 			    ipIfStatsHCOutOctets, i1);
24589 
24590 			if (pkt_type != OB_PKT) {
24591 				/*
24592 				 * Update the packet count and MIB stats
24593 				 * of trailing RTF_MULTIRT ires.
24594 				 */
24595 				UPDATE_OB_PKT_COUNT(ire);
24596 				BUMP_MIB(out_ill->ill_ip_mib,
24597 				    ipIfStatsOutFragReqds);
24598 			}
24599 		}
24600 
24601 		if (multirt_send) {
24602 			/*
24603 			 * We are in a multiple send case; look for
24604 			 * the next ire and re-enter the loop.
24605 			 */
24606 			ASSERT(ire1);
24607 			ASSERT(next_mp);
24608 			/* REFRELE the current ire before looping */
24609 			ire_refrele(ire);
24610 			ire = ire1;
24611 			ire1 = NULL;
24612 			mp = next_mp;
24613 			next_mp = NULL;
24614 		}
24615 	} while (multirt_send);
24616 
24617 	ASSERT(ire1 == NULL);
24618 
24619 	/* Restore the original ire; we need it for the trailing frags */
24620 	if (save_ire != NULL) {
24621 		/* REFRELE the last iterated ire */
24622 		ire_refrele(ire);
24623 		/* save_ire has been REFHOLDed */
24624 		ire = save_ire;
24625 		save_ire = NULL;
24626 		q = ire->ire_stq;
24627 	}
24628 
24629 	if (pkt_type == OB_PKT) {
24630 		UPDATE_OB_PKT_COUNT(ire);
24631 	} else {
24632 		out_ill = (ill_t *)q->q_ptr;
24633 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24634 		UPDATE_IB_PKT_COUNT(ire);
24635 	}
24636 
24637 	/* Advance the offset to the second frag starting point. */
24638 	offset += len;
24639 	/*
24640 	 * Update hdr_len from the copied header - there might be less options
24641 	 * in the later fragments.
24642 	 */
24643 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24644 	/* Loop until done. */
24645 	for (;;) {
24646 		uint16_t	offset_and_flags;
24647 		uint16_t	ip_len;
24648 
24649 		if (ip_data_end - offset > len) {
24650 			/*
24651 			 * Carve off the appropriate amount from the original
24652 			 * datagram.
24653 			 */
24654 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24655 				mp = NULL;
24656 				break;
24657 			}
24658 			/*
24659 			 * More frags after this one.  Get another copy
24660 			 * of the header.
24661 			 */
24662 			if (carve_mp->b_datap->db_ref == 1 &&
24663 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24664 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24665 				/* Inline IP header */
24666 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24667 				    hdr_mp->b_rptr;
24668 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24669 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24670 				mp = carve_mp;
24671 			} else {
24672 				if (!(mp = copyb(hdr_mp))) {
24673 					freemsg(carve_mp);
24674 					break;
24675 				}
24676 				/* Get priority marking, if any. */
24677 				mp->b_band = carve_mp->b_band;
24678 				mp->b_cont = carve_mp;
24679 			}
24680 			ipha = (ipha_t *)mp->b_rptr;
24681 			offset_and_flags = IPH_MF;
24682 		} else {
24683 			/*
24684 			 * Last frag.  Consume the header. Set len to
24685 			 * the length of this last piece.
24686 			 */
24687 			len = ip_data_end - offset;
24688 
24689 			/*
24690 			 * Carve off the appropriate amount from the original
24691 			 * datagram.
24692 			 */
24693 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24694 				mp = NULL;
24695 				break;
24696 			}
24697 			if (carve_mp->b_datap->db_ref == 1 &&
24698 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24699 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24700 				/* Inline IP header */
24701 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24702 				    hdr_mp->b_rptr;
24703 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24704 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24705 				mp = carve_mp;
24706 				freeb(hdr_mp);
24707 				hdr_mp = mp;
24708 			} else {
24709 				mp = hdr_mp;
24710 				/* Get priority marking, if any. */
24711 				mp->b_band = carve_mp->b_band;
24712 				mp->b_cont = carve_mp;
24713 			}
24714 			ipha = (ipha_t *)mp->b_rptr;
24715 			/* A frag of a frag might have IPH_MF non-zero */
24716 			offset_and_flags =
24717 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24718 			    IPH_MF;
24719 		}
24720 		offset_and_flags |= (uint16_t)(offset >> 3);
24721 		offset_and_flags |= (uint16_t)frag_flag;
24722 		/* Store the offset and flags in the IP header. */
24723 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24724 
24725 		/* Store the length in the IP header. */
24726 		ip_len = (uint16_t)(len + hdr_len);
24727 		ipha->ipha_length = htons(ip_len);
24728 
24729 		/*
24730 		 * Set the IP header checksum.	Note that mp is just
24731 		 * the header, so this is easy to pass to ip_csum.
24732 		 */
24733 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24734 
24735 		/* Attach a transmit header, if any, and ship it. */
24736 		if (pkt_type == OB_PKT) {
24737 			UPDATE_OB_PKT_COUNT(ire);
24738 		} else {
24739 			out_ill = (ill_t *)q->q_ptr;
24740 			BUMP_MIB(out_ill->ill_ip_mib,
24741 			    ipIfStatsHCOutForwDatagrams);
24742 			UPDATE_IB_PKT_COUNT(ire);
24743 		}
24744 
24745 		if (ire->ire_flags & RTF_MULTIRT) {
24746 			irb = ire->ire_bucket;
24747 			ASSERT(irb != NULL);
24748 
24749 			multirt_send = B_TRUE;
24750 
24751 			/*
24752 			 * Save the original ire; we will need to restore it
24753 			 * for the tailing frags.
24754 			 */
24755 			save_ire = ire;
24756 			IRE_REFHOLD(save_ire);
24757 		}
24758 		/*
24759 		 * Emission loop for this fragment, similar
24760 		 * to what is done for the first fragment.
24761 		 */
24762 		do {
24763 			if (multirt_send) {
24764 				/*
24765 				 * We are in a multiple send case, need to get
24766 				 * the next ire and make a copy of the packet.
24767 				 */
24768 				ASSERT(irb != NULL);
24769 				IRB_REFHOLD(irb);
24770 				for (ire1 = ire->ire_next;
24771 				    ire1 != NULL;
24772 				    ire1 = ire1->ire_next) {
24773 					if (!(ire1->ire_flags & RTF_MULTIRT))
24774 						continue;
24775 					if (ire1->ire_addr != ire->ire_addr)
24776 						continue;
24777 					if (ire1->ire_marks &
24778 					    (IRE_MARK_CONDEMNED |
24779 					    IRE_MARK_TESTHIDDEN))
24780 						continue;
24781 					/*
24782 					 * Ensure we do not exceed the MTU
24783 					 * of the next route.
24784 					 */
24785 					if (ire1->ire_max_frag < max_frag) {
24786 						ip_multirt_bad_mtu(ire1,
24787 						    max_frag);
24788 						continue;
24789 					}
24790 
24791 					/* Got one. */
24792 					IRE_REFHOLD(ire1);
24793 					break;
24794 				}
24795 				IRB_REFRELE(irb);
24796 
24797 				if (ire1 != NULL) {
24798 					next_mp = copyb(mp);
24799 					if ((next_mp == NULL) ||
24800 					    ((mp->b_cont != NULL) &&
24801 					    ((next_mp->b_cont =
24802 					    dupmsg(mp->b_cont)) == NULL))) {
24803 						freemsg(next_mp);
24804 						next_mp = NULL;
24805 						ire_refrele(ire1);
24806 						ire1 = NULL;
24807 					}
24808 				}
24809 
24810 				/* Last multiroute ire; don't loop anymore. */
24811 				if (ire1 == NULL) {
24812 					multirt_send = B_FALSE;
24813 				}
24814 			}
24815 
24816 			/* Update transmit header */
24817 			ll_hdr_len = 0;
24818 			LOCK_IRE_FP_MP(ire);
24819 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24820 			if (ll_hdr_mp != NULL) {
24821 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24822 				ll_hdr_len = MBLKL(ll_hdr_mp);
24823 			} else {
24824 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24825 			}
24826 
24827 			if (!ll_hdr_mp) {
24828 				xmit_mp = mp;
24829 
24830 			/*
24831 			 * We have link-layer header that can fit in
24832 			 * our mblk.
24833 			 */
24834 			} else if (mp->b_datap->db_ref == 1 &&
24835 			    ll_hdr_len != 0 &&
24836 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24837 				/* M_DATA fastpath */
24838 				mp->b_rptr -= ll_hdr_len;
24839 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24840 				    ll_hdr_len);
24841 				xmit_mp = mp;
24842 
24843 			/*
24844 			 * Case of res_mp OR the fastpath mp can't fit
24845 			 * in the mblk
24846 			 */
24847 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24848 				xmit_mp->b_cont = mp;
24849 				/* Get priority marking, if any. */
24850 				if (DB_TYPE(xmit_mp) == M_DATA)
24851 					xmit_mp->b_band = mp->b_band;
24852 
24853 			/* Corner case if copyb failed */
24854 			} else {
24855 				/*
24856 				 * Exit both the replication and
24857 				 * fragmentation loops.
24858 				 */
24859 				UNLOCK_IRE_FP_MP(ire);
24860 				goto drop_pkt;
24861 			}
24862 			UNLOCK_IRE_FP_MP(ire);
24863 
24864 			mp1 = mp;
24865 			out_ill = (ill_t *)q->q_ptr;
24866 
24867 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24868 
24869 			DTRACE_PROBE4(ip4__physical__out__start,
24870 			    ill_t *, NULL, ill_t *, out_ill,
24871 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24872 
24873 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24874 			    ipst->ips_ipv4firewall_physical_out,
24875 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24876 
24877 			DTRACE_PROBE1(ip4__physical__out__end,
24878 			    mblk_t *, xmit_mp);
24879 
24880 			if (mp != mp1 && hdr_mp == mp1)
24881 				hdr_mp = mp;
24882 			if (mp != mp1 && mp_orig == mp1)
24883 				mp_orig = mp;
24884 
24885 			if (xmit_mp != NULL) {
24886 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24887 				    NULL, void_ip_t *, ipha,
24888 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24889 				    ipha, ip6_t *, NULL, int, 0);
24890 
24891 				ILL_SEND_TX(out_ill, ire, connp,
24892 				    xmit_mp, 0, connp);
24893 
24894 				BUMP_MIB(out_ill->ill_ip_mib,
24895 				    ipIfStatsHCOutTransmits);
24896 				UPDATE_MIB(out_ill->ill_ip_mib,
24897 				    ipIfStatsHCOutOctets, ip_len);
24898 
24899 				if (pkt_type != OB_PKT) {
24900 					/*
24901 					 * Update the packet count of trailing
24902 					 * RTF_MULTIRT ires.
24903 					 */
24904 					UPDATE_OB_PKT_COUNT(ire);
24905 				}
24906 			}
24907 
24908 			/* All done if we just consumed the hdr_mp. */
24909 			if (mp == hdr_mp) {
24910 				last_frag = B_TRUE;
24911 				BUMP_MIB(out_ill->ill_ip_mib,
24912 				    ipIfStatsOutFragOKs);
24913 			}
24914 
24915 			if (multirt_send) {
24916 				/*
24917 				 * We are in a multiple send case; look for
24918 				 * the next ire and re-enter the loop.
24919 				 */
24920 				ASSERT(ire1);
24921 				ASSERT(next_mp);
24922 				/* REFRELE the current ire before looping */
24923 				ire_refrele(ire);
24924 				ire = ire1;
24925 				ire1 = NULL;
24926 				q = ire->ire_stq;
24927 				mp = next_mp;
24928 				next_mp = NULL;
24929 			}
24930 		} while (multirt_send);
24931 		/*
24932 		 * Restore the original ire; we need it for the
24933 		 * trailing frags
24934 		 */
24935 		if (save_ire != NULL) {
24936 			ASSERT(ire1 == NULL);
24937 			/* REFRELE the last iterated ire */
24938 			ire_refrele(ire);
24939 			/* save_ire has been REFHOLDed */
24940 			ire = save_ire;
24941 			q = ire->ire_stq;
24942 			save_ire = NULL;
24943 		}
24944 
24945 		if (last_frag) {
24946 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24947 			    "ip_wput_frag_end:(%S)",
24948 			    "consumed hdr_mp");
24949 
24950 			if (first_ire != NULL)
24951 				ire_refrele(first_ire);
24952 			return;
24953 		}
24954 		/* Otherwise, advance and loop. */
24955 		offset += len;
24956 	}
24957 
24958 drop_pkt:
24959 	/* Clean up following allocation failure. */
24960 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24961 	freemsg(mp);
24962 	if (mp != hdr_mp)
24963 		freeb(hdr_mp);
24964 	if (mp != mp_orig)
24965 		freemsg(mp_orig);
24966 
24967 	if (save_ire != NULL)
24968 		IRE_REFRELE(save_ire);
24969 	if (first_ire != NULL)
24970 		ire_refrele(first_ire);
24971 
24972 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24973 	    "ip_wput_frag_end:(%S)",
24974 	    "end--alloc failure");
24975 }
24976 
24977 /*
24978  * Copy the header plus those options which have the copy bit set
24979  * src is the template to make sure we preserve the cred for TX purposes.
24980  */
24981 static mblk_t *
24982 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
24983     mblk_t *src)
24984 {
24985 	mblk_t	*mp;
24986 	uchar_t	*up;
24987 
24988 	/*
24989 	 * Quick check if we need to look for options without the copy bit
24990 	 * set
24991 	 */
24992 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
24993 	if (!mp)
24994 		return (mp);
24995 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24996 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24997 		bcopy(rptr, mp->b_rptr, hdr_len);
24998 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24999 		return (mp);
25000 	}
25001 	up  = mp->b_rptr;
25002 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25003 	up += IP_SIMPLE_HDR_LENGTH;
25004 	rptr += IP_SIMPLE_HDR_LENGTH;
25005 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25006 	while (hdr_len > 0) {
25007 		uint32_t optval;
25008 		uint32_t optlen;
25009 
25010 		optval = *rptr;
25011 		if (optval == IPOPT_EOL)
25012 			break;
25013 		if (optval == IPOPT_NOP)
25014 			optlen = 1;
25015 		else
25016 			optlen = rptr[1];
25017 		if (optval & IPOPT_COPY) {
25018 			bcopy(rptr, up, optlen);
25019 			up += optlen;
25020 		}
25021 		rptr += optlen;
25022 		hdr_len -= optlen;
25023 	}
25024 	/*
25025 	 * Make sure that we drop an even number of words by filling
25026 	 * with EOL to the next word boundary.
25027 	 */
25028 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25029 	    hdr_len & 0x3; hdr_len++)
25030 		*up++ = IPOPT_EOL;
25031 	mp->b_wptr = up;
25032 	/* Update header length */
25033 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25034 	return (mp);
25035 }
25036 
25037 /*
25038  * Delivery to local recipients including fanout to multiple recipients.
25039  * Does not do checksumming of UDP/TCP.
25040  * Note: q should be the read side queue for either the ill or conn.
25041  * Note: rq should be the read side q for the lower (ill) stream.
25042  * We don't send packets to IPPF processing, thus the last argument
25043  * to all the fanout calls are B_FALSE.
25044  */
25045 void
25046 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25047     int fanout_flags, zoneid_t zoneid)
25048 {
25049 	uint32_t	protocol;
25050 	mblk_t		*first_mp;
25051 	boolean_t	mctl_present;
25052 	int		ire_type;
25053 #define	rptr	((uchar_t *)ipha)
25054 	ip_stack_t	*ipst = ill->ill_ipst;
25055 
25056 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25057 	    "ip_wput_local_start: q %p", q);
25058 
25059 	if (ire != NULL) {
25060 		ire_type = ire->ire_type;
25061 	} else {
25062 		/*
25063 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25064 		 * packet is not multicast, we can't tell the ire type.
25065 		 */
25066 		ASSERT(CLASSD(ipha->ipha_dst));
25067 		ire_type = IRE_BROADCAST;
25068 	}
25069 
25070 	first_mp = mp;
25071 	if (first_mp->b_datap->db_type == M_CTL) {
25072 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25073 		if (!io->ipsec_out_secure) {
25074 			/*
25075 			 * This ipsec_out_t was allocated in ip_wput
25076 			 * for multicast packets to store the ill_index.
25077 			 * As this is being delivered locally, we don't
25078 			 * need this anymore.
25079 			 */
25080 			mp = first_mp->b_cont;
25081 			freeb(first_mp);
25082 			first_mp = mp;
25083 			mctl_present = B_FALSE;
25084 		} else {
25085 			/*
25086 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25087 			 * security properties for the looped-back packet.
25088 			 */
25089 			mctl_present = B_TRUE;
25090 			mp = first_mp->b_cont;
25091 			ASSERT(mp != NULL);
25092 			ipsec_out_to_in(first_mp);
25093 		}
25094 	} else {
25095 		mctl_present = B_FALSE;
25096 	}
25097 
25098 	DTRACE_PROBE4(ip4__loopback__in__start,
25099 	    ill_t *, ill, ill_t *, NULL,
25100 	    ipha_t *, ipha, mblk_t *, first_mp);
25101 
25102 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25103 	    ipst->ips_ipv4firewall_loopback_in,
25104 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25105 
25106 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25107 
25108 	if (first_mp == NULL)
25109 		return;
25110 
25111 	if (ipst->ips_ipobs_enabled) {
25112 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25113 		zoneid_t stackzoneid = netstackid_to_zoneid(
25114 		    ipst->ips_netstack->netstack_stackid);
25115 
25116 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25117 		/*
25118 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25119 		 * address.  Restrict the lookup below to the destination zone.
25120 		 */
25121 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25122 			lookup_zoneid = zoneid;
25123 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25124 		    lookup_zoneid);
25125 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25126 		    IPV4_VERSION, 0, ipst);
25127 	}
25128 
25129 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25130 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25131 	    int, 1);
25132 
25133 	ipst->ips_loopback_packets++;
25134 
25135 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25136 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25137 	if (!IS_SIMPLE_IPH(ipha)) {
25138 		ip_wput_local_options(ipha, ipst);
25139 	}
25140 
25141 	protocol = ipha->ipha_protocol;
25142 	switch (protocol) {
25143 	case IPPROTO_ICMP: {
25144 		ire_t		*ire_zone;
25145 		ilm_t		*ilm;
25146 		mblk_t		*mp1;
25147 		zoneid_t	last_zoneid;
25148 		ilm_walker_t	ilw;
25149 
25150 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25151 			ASSERT(ire_type == IRE_BROADCAST);
25152 			/*
25153 			 * In the multicast case, applications may have joined
25154 			 * the group from different zones, so we need to deliver
25155 			 * the packet to each of them. Loop through the
25156 			 * multicast memberships structures (ilm) on the receive
25157 			 * ill and send a copy of the packet up each matching
25158 			 * one. However, we don't do this for multicasts sent on
25159 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25160 			 * they must stay in the sender's zone.
25161 			 *
25162 			 * ilm_add_v6() ensures that ilms in the same zone are
25163 			 * contiguous in the ill_ilm list. We use this property
25164 			 * to avoid sending duplicates needed when two
25165 			 * applications in the same zone join the same group on
25166 			 * different logical interfaces: we ignore the ilm if
25167 			 * it's zoneid is the same as the last matching one.
25168 			 * In addition, the sending of the packet for
25169 			 * ire_zoneid is delayed until all of the other ilms
25170 			 * have been exhausted.
25171 			 */
25172 			last_zoneid = -1;
25173 			ilm = ilm_walker_start(&ilw, ill);
25174 			for (; ilm != NULL; ilm = ilm_walker_step(&ilw, ilm)) {
25175 				if (ipha->ipha_dst != ilm->ilm_addr ||
25176 				    ilm->ilm_zoneid == last_zoneid ||
25177 				    ilm->ilm_zoneid == zoneid ||
25178 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25179 					continue;
25180 				mp1 = ip_copymsg(first_mp);
25181 				if (mp1 == NULL)
25182 					continue;
25183 				icmp_inbound(q, mp1, B_TRUE, ilw.ilw_walk_ill,
25184 				    0, 0, mctl_present, B_FALSE, ill,
25185 				    ilm->ilm_zoneid);
25186 				last_zoneid = ilm->ilm_zoneid;
25187 			}
25188 			ilm_walker_finish(&ilw);
25189 			/*
25190 			 * Loopback case: the sending endpoint has
25191 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25192 			 * dispatch the multicast packet to the sending zone.
25193 			 */
25194 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25195 				freemsg(first_mp);
25196 				return;
25197 			}
25198 		} else if (ire_type == IRE_BROADCAST) {
25199 			/*
25200 			 * In the broadcast case, there may be many zones
25201 			 * which need a copy of the packet delivered to them.
25202 			 * There is one IRE_BROADCAST per broadcast address
25203 			 * and per zone; we walk those using a helper function.
25204 			 * In addition, the sending of the packet for zoneid is
25205 			 * delayed until all of the other ires have been
25206 			 * processed.
25207 			 */
25208 			IRB_REFHOLD(ire->ire_bucket);
25209 			ire_zone = NULL;
25210 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25211 			    ire)) != NULL) {
25212 				mp1 = ip_copymsg(first_mp);
25213 				if (mp1 == NULL)
25214 					continue;
25215 
25216 				UPDATE_IB_PKT_COUNT(ire_zone);
25217 				ire_zone->ire_last_used_time = lbolt;
25218 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25219 				    mctl_present, B_FALSE, ill,
25220 				    ire_zone->ire_zoneid);
25221 			}
25222 			IRB_REFRELE(ire->ire_bucket);
25223 		}
25224 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25225 		    0, mctl_present, B_FALSE, ill, zoneid);
25226 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25227 		    "ip_wput_local_end: q %p (%S)",
25228 		    q, "icmp");
25229 		return;
25230 	}
25231 	case IPPROTO_IGMP:
25232 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25233 			/* Bad packet - discarded by igmp_input */
25234 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25235 			    "ip_wput_local_end: q %p (%S)",
25236 			    q, "igmp_input--bad packet");
25237 			if (mctl_present)
25238 				freeb(first_mp);
25239 			return;
25240 		}
25241 		/*
25242 		 * igmp_input() may have returned the pulled up message.
25243 		 * So first_mp and ipha need to be reinitialized.
25244 		 */
25245 		ipha = (ipha_t *)mp->b_rptr;
25246 		if (mctl_present)
25247 			first_mp->b_cont = mp;
25248 		else
25249 			first_mp = mp;
25250 		/* deliver to local raw users */
25251 		break;
25252 	case IPPROTO_ENCAP:
25253 		/*
25254 		 * This case is covered by either ip_fanout_proto, or by
25255 		 * the above security processing for self-tunneled packets.
25256 		 */
25257 		break;
25258 	case IPPROTO_UDP: {
25259 		uint16_t	*up;
25260 		uint32_t	ports;
25261 
25262 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25263 		    UDP_PORTS_OFFSET);
25264 		/* Force a 'valid' checksum. */
25265 		up[3] = 0;
25266 
25267 		ports = *(uint32_t *)up;
25268 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25269 		    (ire_type == IRE_BROADCAST),
25270 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25271 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25272 		    ill, zoneid);
25273 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25274 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25275 		return;
25276 	}
25277 	case IPPROTO_TCP: {
25278 
25279 		/*
25280 		 * For TCP, discard broadcast packets.
25281 		 */
25282 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25283 			freemsg(first_mp);
25284 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25285 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25286 			return;
25287 		}
25288 
25289 		if (mp->b_datap->db_type == M_DATA) {
25290 			/*
25291 			 * M_DATA mblk, so init mblk (chain) for no struio().
25292 			 */
25293 			mblk_t	*mp1 = mp;
25294 
25295 			do {
25296 				mp1->b_datap->db_struioflag = 0;
25297 			} while ((mp1 = mp1->b_cont) != NULL);
25298 		}
25299 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25300 		    <= mp->b_wptr);
25301 		ip_fanout_tcp(q, first_mp, ill, ipha,
25302 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25303 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25304 		    mctl_present, B_FALSE, zoneid);
25305 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25306 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25307 		return;
25308 	}
25309 	case IPPROTO_SCTP:
25310 	{
25311 		uint32_t	ports;
25312 
25313 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25314 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25315 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25316 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25317 		return;
25318 	}
25319 
25320 	default:
25321 		break;
25322 	}
25323 	/*
25324 	 * Find a client for some other protocol.  We give
25325 	 * copies to multiple clients, if more than one is
25326 	 * bound.
25327 	 */
25328 	ip_fanout_proto(q, first_mp, ill, ipha,
25329 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25330 	    mctl_present, B_FALSE, ill, zoneid);
25331 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25332 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25333 #undef	rptr
25334 }
25335 
25336 /*
25337  * Update any source route, record route, or timestamp options.
25338  * Check that we are at end of strict source route.
25339  * The options have been sanity checked by ip_wput_options().
25340  */
25341 static void
25342 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25343 {
25344 	ipoptp_t	opts;
25345 	uchar_t		*opt;
25346 	uint8_t		optval;
25347 	uint8_t		optlen;
25348 	ipaddr_t	dst;
25349 	uint32_t	ts;
25350 	ire_t		*ire;
25351 	timestruc_t	now;
25352 
25353 	ip2dbg(("ip_wput_local_options\n"));
25354 	for (optval = ipoptp_first(&opts, ipha);
25355 	    optval != IPOPT_EOL;
25356 	    optval = ipoptp_next(&opts)) {
25357 		opt = opts.ipoptp_cur;
25358 		optlen = opts.ipoptp_len;
25359 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25360 		switch (optval) {
25361 			uint32_t off;
25362 		case IPOPT_SSRR:
25363 		case IPOPT_LSRR:
25364 			off = opt[IPOPT_OFFSET];
25365 			off--;
25366 			if (optlen < IP_ADDR_LEN ||
25367 			    off > optlen - IP_ADDR_LEN) {
25368 				/* End of source route */
25369 				break;
25370 			}
25371 			/*
25372 			 * This will only happen if two consecutive entries
25373 			 * in the source route contains our address or if
25374 			 * it is a packet with a loose source route which
25375 			 * reaches us before consuming the whole source route
25376 			 */
25377 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25378 			if (optval == IPOPT_SSRR) {
25379 				return;
25380 			}
25381 			/*
25382 			 * Hack: instead of dropping the packet truncate the
25383 			 * source route to what has been used by filling the
25384 			 * rest with IPOPT_NOP.
25385 			 */
25386 			opt[IPOPT_OLEN] = (uint8_t)off;
25387 			while (off < optlen) {
25388 				opt[off++] = IPOPT_NOP;
25389 			}
25390 			break;
25391 		case IPOPT_RR:
25392 			off = opt[IPOPT_OFFSET];
25393 			off--;
25394 			if (optlen < IP_ADDR_LEN ||
25395 			    off > optlen - IP_ADDR_LEN) {
25396 				/* No more room - ignore */
25397 				ip1dbg((
25398 				    "ip_wput_forward_options: end of RR\n"));
25399 				break;
25400 			}
25401 			dst = htonl(INADDR_LOOPBACK);
25402 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25403 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25404 			break;
25405 		case IPOPT_TS:
25406 			/* Insert timestamp if there is romm */
25407 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25408 			case IPOPT_TS_TSONLY:
25409 				off = IPOPT_TS_TIMELEN;
25410 				break;
25411 			case IPOPT_TS_PRESPEC:
25412 			case IPOPT_TS_PRESPEC_RFC791:
25413 				/* Verify that the address matched */
25414 				off = opt[IPOPT_OFFSET] - 1;
25415 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25416 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25417 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25418 				    ipst);
25419 				if (ire == NULL) {
25420 					/* Not for us */
25421 					break;
25422 				}
25423 				ire_refrele(ire);
25424 				/* FALLTHRU */
25425 			case IPOPT_TS_TSANDADDR:
25426 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25427 				break;
25428 			default:
25429 				/*
25430 				 * ip_*put_options should have already
25431 				 * dropped this packet.
25432 				 */
25433 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25434 				    "unknown IT - bug in ip_wput_options?\n");
25435 				return;	/* Keep "lint" happy */
25436 			}
25437 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25438 				/* Increase overflow counter */
25439 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25440 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25441 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25442 				    (off << 4);
25443 				break;
25444 			}
25445 			off = opt[IPOPT_OFFSET] - 1;
25446 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25447 			case IPOPT_TS_PRESPEC:
25448 			case IPOPT_TS_PRESPEC_RFC791:
25449 			case IPOPT_TS_TSANDADDR:
25450 				dst = htonl(INADDR_LOOPBACK);
25451 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25452 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25453 				/* FALLTHRU */
25454 			case IPOPT_TS_TSONLY:
25455 				off = opt[IPOPT_OFFSET] - 1;
25456 				/* Compute # of milliseconds since midnight */
25457 				gethrestime(&now);
25458 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25459 				    now.tv_nsec / (NANOSEC / MILLISEC);
25460 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25461 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25462 				break;
25463 			}
25464 			break;
25465 		}
25466 	}
25467 }
25468 
25469 /*
25470  * Send out a multicast packet on interface ipif.
25471  * The sender does not have an conn.
25472  * Caller verifies that this isn't a PHYI_LOOPBACK.
25473  */
25474 void
25475 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25476 {
25477 	ipha_t	*ipha;
25478 	ire_t	*ire;
25479 	ipaddr_t	dst;
25480 	mblk_t		*first_mp;
25481 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25482 
25483 	/* igmp_sendpkt always allocates a ipsec_out_t */
25484 	ASSERT(mp->b_datap->db_type == M_CTL);
25485 	ASSERT(!ipif->ipif_isv6);
25486 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25487 
25488 	first_mp = mp;
25489 	mp = first_mp->b_cont;
25490 	ASSERT(mp->b_datap->db_type == M_DATA);
25491 	ipha = (ipha_t *)mp->b_rptr;
25492 
25493 	/*
25494 	 * Find an IRE which matches the destination and the outgoing
25495 	 * queue (i.e. the outgoing interface.)
25496 	 */
25497 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25498 		dst = ipif->ipif_pp_dst_addr;
25499 	else
25500 		dst = ipha->ipha_dst;
25501 	/*
25502 	 * The source address has already been initialized by the
25503 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25504 	 * be sufficient rather than MATCH_IRE_IPIF.
25505 	 *
25506 	 * This function is used for sending IGMP packets.  For IPMP,
25507 	 * we sidestep IGMP snooping issues by sending all multicast
25508 	 * traffic on a single interface in the IPMP group.
25509 	 */
25510 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25511 	    MATCH_IRE_ILL, ipst);
25512 	if (!ire) {
25513 		/*
25514 		 * Mark this packet to make it be delivered to
25515 		 * ip_wput_ire after the new ire has been
25516 		 * created.
25517 		 */
25518 		mp->b_prev = NULL;
25519 		mp->b_next = NULL;
25520 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25521 		    zoneid, &zero_info);
25522 		return;
25523 	}
25524 
25525 	/*
25526 	 * Honor the RTF_SETSRC flag; this is the only case
25527 	 * where we force this addr whatever the current src addr is,
25528 	 * because this address is set by igmp_sendpkt(), and
25529 	 * cannot be specified by any user.
25530 	 */
25531 	if (ire->ire_flags & RTF_SETSRC) {
25532 		ipha->ipha_src = ire->ire_src_addr;
25533 	}
25534 
25535 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25536 }
25537 
25538 /*
25539  * NOTE : This function does not ire_refrele the ire argument passed in.
25540  *
25541  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25542  * failure. The nce_fp_mp can vanish any time in the case of
25543  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25544  * the ire_lock to access the nce_fp_mp in this case.
25545  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25546  * prepending a fastpath message IPQoS processing must precede it, we also set
25547  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25548  * (IPQoS might have set the b_band for CoS marking).
25549  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25550  * must follow it so that IPQoS can mark the dl_priority field for CoS
25551  * marking, if needed.
25552  */
25553 static mblk_t *
25554 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25555     uint32_t ill_index, ipha_t **iphap)
25556 {
25557 	uint_t	hlen;
25558 	ipha_t *ipha;
25559 	mblk_t *mp1;
25560 	boolean_t qos_done = B_FALSE;
25561 	uchar_t	*ll_hdr;
25562 	ip_stack_t	*ipst = ire->ire_ipst;
25563 
25564 #define	rptr	((uchar_t *)ipha)
25565 
25566 	ipha = (ipha_t *)mp->b_rptr;
25567 	hlen = 0;
25568 	LOCK_IRE_FP_MP(ire);
25569 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25570 		ASSERT(DB_TYPE(mp1) == M_DATA);
25571 		/* Initiate IPPF processing */
25572 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25573 			UNLOCK_IRE_FP_MP(ire);
25574 			ip_process(proc, &mp, ill_index);
25575 			if (mp == NULL)
25576 				return (NULL);
25577 
25578 			ipha = (ipha_t *)mp->b_rptr;
25579 			LOCK_IRE_FP_MP(ire);
25580 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25581 				qos_done = B_TRUE;
25582 				goto no_fp_mp;
25583 			}
25584 			ASSERT(DB_TYPE(mp1) == M_DATA);
25585 		}
25586 		hlen = MBLKL(mp1);
25587 		/*
25588 		 * Check if we have enough room to prepend fastpath
25589 		 * header
25590 		 */
25591 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25592 			ll_hdr = rptr - hlen;
25593 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25594 			/*
25595 			 * Set the b_rptr to the start of the link layer
25596 			 * header
25597 			 */
25598 			mp->b_rptr = ll_hdr;
25599 			mp1 = mp;
25600 		} else {
25601 			mp1 = copyb(mp1);
25602 			if (mp1 == NULL)
25603 				goto unlock_err;
25604 			mp1->b_band = mp->b_band;
25605 			mp1->b_cont = mp;
25606 			/*
25607 			 * XXX disable ICK_VALID and compute checksum
25608 			 * here; can happen if nce_fp_mp changes and
25609 			 * it can't be copied now due to insufficient
25610 			 * space. (unlikely, fp mp can change, but it
25611 			 * does not increase in length)
25612 			 */
25613 		}
25614 		UNLOCK_IRE_FP_MP(ire);
25615 	} else {
25616 no_fp_mp:
25617 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25618 		if (mp1 == NULL) {
25619 unlock_err:
25620 			UNLOCK_IRE_FP_MP(ire);
25621 			freemsg(mp);
25622 			return (NULL);
25623 		}
25624 		UNLOCK_IRE_FP_MP(ire);
25625 		mp1->b_cont = mp;
25626 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25627 			ip_process(proc, &mp1, ill_index);
25628 			if (mp1 == NULL)
25629 				return (NULL);
25630 
25631 			if (mp1->b_cont == NULL)
25632 				ipha = NULL;
25633 			else
25634 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25635 		}
25636 	}
25637 
25638 	*iphap = ipha;
25639 	return (mp1);
25640 #undef rptr
25641 }
25642 
25643 /*
25644  * Finish the outbound IPsec processing for an IPv6 packet. This function
25645  * is called from ipsec_out_process() if the IPsec packet was processed
25646  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25647  * asynchronously.
25648  */
25649 void
25650 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25651     ire_t *ire_arg)
25652 {
25653 	in6_addr_t *v6dstp;
25654 	ire_t *ire;
25655 	mblk_t *mp;
25656 	ip6_t *ip6h1;
25657 	uint_t	ill_index;
25658 	ipsec_out_t *io;
25659 	boolean_t hwaccel;
25660 	uint32_t flags = IP6_NO_IPPOLICY;
25661 	int match_flags;
25662 	zoneid_t zoneid;
25663 	boolean_t ill_need_rele = B_FALSE;
25664 	boolean_t ire_need_rele = B_FALSE;
25665 	ip_stack_t	*ipst;
25666 
25667 	mp = ipsec_mp->b_cont;
25668 	ip6h1 = (ip6_t *)mp->b_rptr;
25669 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25670 	ASSERT(io->ipsec_out_ns != NULL);
25671 	ipst = io->ipsec_out_ns->netstack_ip;
25672 	ill_index = io->ipsec_out_ill_index;
25673 	if (io->ipsec_out_reachable) {
25674 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25675 	}
25676 	hwaccel = io->ipsec_out_accelerated;
25677 	zoneid = io->ipsec_out_zoneid;
25678 	ASSERT(zoneid != ALL_ZONES);
25679 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25680 	/* Multicast addresses should have non-zero ill_index. */
25681 	v6dstp = &ip6h->ip6_dst;
25682 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25683 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25684 
25685 	if (ill == NULL && ill_index != 0) {
25686 		ill = ip_grab_ill(ipsec_mp, ill_index, B_TRUE, ipst);
25687 		/* Failure case frees things for us. */
25688 		if (ill == NULL)
25689 			return;
25690 
25691 		ill_need_rele = B_TRUE;
25692 	}
25693 	ASSERT(mp != NULL);
25694 
25695 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25696 		boolean_t unspec_src;
25697 		ipif_t	*ipif;
25698 
25699 		/*
25700 		 * Use the ill_index to get the right ill.
25701 		 */
25702 		unspec_src = io->ipsec_out_unspec_src;
25703 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25704 		if (ipif == NULL) {
25705 			if (ill_need_rele)
25706 				ill_refrele(ill);
25707 			freemsg(ipsec_mp);
25708 			return;
25709 		}
25710 
25711 		if (ire_arg != NULL) {
25712 			ire = ire_arg;
25713 		} else {
25714 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25715 			    zoneid, msg_getlabel(mp), match_flags, ipst);
25716 			ire_need_rele = B_TRUE;
25717 		}
25718 		if (ire != NULL) {
25719 			ipif_refrele(ipif);
25720 			/*
25721 			 * XXX Do the multicast forwarding now, as the IPsec
25722 			 * processing has been done.
25723 			 */
25724 			goto send;
25725 		}
25726 
25727 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25728 		mp->b_prev = NULL;
25729 		mp->b_next = NULL;
25730 
25731 		/*
25732 		 * If the IPsec packet was processed asynchronously,
25733 		 * drop it now.
25734 		 */
25735 		if (q == NULL) {
25736 			if (ill_need_rele)
25737 				ill_refrele(ill);
25738 			freemsg(ipsec_mp);
25739 			return;
25740 		}
25741 
25742 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, v6dstp, &ip6h->ip6_src,
25743 		    unspec_src, zoneid);
25744 		ipif_refrele(ipif);
25745 	} else {
25746 		if (ire_arg != NULL) {
25747 			ire = ire_arg;
25748 		} else {
25749 			ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL, ipst);
25750 			ire_need_rele = B_TRUE;
25751 		}
25752 		if (ire != NULL)
25753 			goto send;
25754 		/*
25755 		 * ire disappeared underneath.
25756 		 *
25757 		 * What we need to do here is the ip_newroute
25758 		 * logic to get the ire without doing the IPsec
25759 		 * processing. Follow the same old path. But this
25760 		 * time, ip_wput or ire_add_then_send will call us
25761 		 * directly as all the IPsec operations are done.
25762 		 */
25763 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25764 		mp->b_prev = NULL;
25765 		mp->b_next = NULL;
25766 
25767 		/*
25768 		 * If the IPsec packet was processed asynchronously,
25769 		 * drop it now.
25770 		 */
25771 		if (q == NULL) {
25772 			if (ill_need_rele)
25773 				ill_refrele(ill);
25774 			freemsg(ipsec_mp);
25775 			return;
25776 		}
25777 
25778 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25779 		    zoneid, ipst);
25780 	}
25781 	if (ill != NULL && ill_need_rele)
25782 		ill_refrele(ill);
25783 	return;
25784 send:
25785 	if (ill != NULL && ill_need_rele)
25786 		ill_refrele(ill);
25787 
25788 	/* Local delivery */
25789 	if (ire->ire_stq == NULL) {
25790 		ill_t	*out_ill;
25791 		ASSERT(q != NULL);
25792 
25793 		/* PFHooks: LOOPBACK_OUT */
25794 		out_ill = ire_to_ill(ire);
25795 
25796 		/*
25797 		 * DTrace this as ip:::send.  A blocked packet will fire the
25798 		 * send probe, but not the receive probe.
25799 		 */
25800 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25801 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25802 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25803 
25804 		DTRACE_PROBE4(ip6__loopback__out__start,
25805 		    ill_t *, NULL, ill_t *, out_ill,
25806 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25807 
25808 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25809 		    ipst->ips_ipv6firewall_loopback_out,
25810 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25811 
25812 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25813 
25814 		if (ipsec_mp != NULL) {
25815 			ip_wput_local_v6(RD(q), out_ill,
25816 			    ip6h, ipsec_mp, ire, 0, zoneid);
25817 		}
25818 		if (ire_need_rele)
25819 			ire_refrele(ire);
25820 		return;
25821 	}
25822 	/*
25823 	 * Everything is done. Send it out on the wire.
25824 	 * We force the insertion of a fragment header using the
25825 	 * IPH_FRAG_HDR flag in two cases:
25826 	 * - after reception of an ICMPv6 "packet too big" message
25827 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25828 	 * - for multirouted IPv6 packets, so that the receiver can
25829 	 *   discard duplicates according to their fragment identifier
25830 	 */
25831 	/* XXX fix flow control problems. */
25832 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25833 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25834 		if (hwaccel) {
25835 			/*
25836 			 * hardware acceleration does not handle these
25837 			 * "slow path" cases.
25838 			 */
25839 			/* IPsec KSTATS: should bump bean counter here. */
25840 			if (ire_need_rele)
25841 				ire_refrele(ire);
25842 			freemsg(ipsec_mp);
25843 			return;
25844 		}
25845 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25846 		    (mp->b_cont ? msgdsize(mp) :
25847 		    mp->b_wptr - (uchar_t *)ip6h)) {
25848 			/* IPsec KSTATS: should bump bean counter here. */
25849 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25850 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25851 			    msgdsize(mp)));
25852 			if (ire_need_rele)
25853 				ire_refrele(ire);
25854 			freemsg(ipsec_mp);
25855 			return;
25856 		}
25857 		ASSERT(mp->b_prev == NULL);
25858 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25859 		    ntohs(ip6h->ip6_plen) +
25860 		    IPV6_HDR_LEN, ire->ire_max_frag));
25861 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25862 		    ire->ire_max_frag);
25863 	} else {
25864 		UPDATE_OB_PKT_COUNT(ire);
25865 		ire->ire_last_used_time = lbolt;
25866 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25867 	}
25868 	if (ire_need_rele)
25869 		ire_refrele(ire);
25870 	freeb(ipsec_mp);
25871 }
25872 
25873 void
25874 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25875 {
25876 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25877 	da_ipsec_t *hada;	/* data attributes */
25878 	ill_t *ill = (ill_t *)q->q_ptr;
25879 
25880 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25881 
25882 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25883 		/* IPsec KSTATS: Bump lose counter here! */
25884 		freemsg(mp);
25885 		return;
25886 	}
25887 
25888 	/*
25889 	 * It's an IPsec packet that must be
25890 	 * accelerated by the Provider, and the
25891 	 * outbound ill is IPsec acceleration capable.
25892 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25893 	 * to the ill.
25894 	 * IPsec KSTATS: should bump packet counter here.
25895 	 */
25896 
25897 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25898 	if (hada_mp == NULL) {
25899 		/* IPsec KSTATS: should bump packet counter here. */
25900 		freemsg(mp);
25901 		return;
25902 	}
25903 
25904 	hada_mp->b_datap->db_type = M_CTL;
25905 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25906 	hada_mp->b_cont = mp;
25907 
25908 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25909 	bzero(hada, sizeof (da_ipsec_t));
25910 	hada->da_type = IPHADA_M_CTL;
25911 
25912 	putnext(q, hada_mp);
25913 }
25914 
25915 /*
25916  * Finish the outbound IPsec processing. This function is called from
25917  * ipsec_out_process() if the IPsec packet was processed
25918  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25919  * asynchronously.
25920  */
25921 void
25922 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25923     ire_t *ire_arg)
25924 {
25925 	uint32_t v_hlen_tos_len;
25926 	ipaddr_t	dst;
25927 	ipif_t	*ipif = NULL;
25928 	ire_t *ire;
25929 	ire_t *ire1 = NULL;
25930 	mblk_t *next_mp = NULL;
25931 	uint32_t max_frag;
25932 	boolean_t multirt_send = B_FALSE;
25933 	mblk_t *mp;
25934 	ipha_t *ipha1;
25935 	uint_t	ill_index;
25936 	ipsec_out_t *io;
25937 	int match_flags;
25938 	irb_t *irb = NULL;
25939 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25940 	zoneid_t zoneid;
25941 	ipxmit_state_t	pktxmit_state;
25942 	ip_stack_t	*ipst;
25943 
25944 #ifdef	_BIG_ENDIAN
25945 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25946 #else
25947 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25948 #endif
25949 
25950 	mp = ipsec_mp->b_cont;
25951 	ipha1 = (ipha_t *)mp->b_rptr;
25952 	ASSERT(mp != NULL);
25953 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25954 	dst = ipha->ipha_dst;
25955 
25956 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25957 	ill_index = io->ipsec_out_ill_index;
25958 	zoneid = io->ipsec_out_zoneid;
25959 	ASSERT(zoneid != ALL_ZONES);
25960 	ipst = io->ipsec_out_ns->netstack_ip;
25961 	ASSERT(io->ipsec_out_ns != NULL);
25962 
25963 	match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25964 	if (ill == NULL && ill_index != 0) {
25965 		ill = ip_grab_ill(ipsec_mp, ill_index, B_FALSE, ipst);
25966 		/* Failure case frees things for us. */
25967 		if (ill == NULL)
25968 			return;
25969 
25970 		ill_need_rele = B_TRUE;
25971 	}
25972 
25973 	if (CLASSD(dst)) {
25974 		boolean_t conn_dontroute;
25975 		/*
25976 		 * Use the ill_index to get the right ipif.
25977 		 */
25978 		conn_dontroute = io->ipsec_out_dontroute;
25979 		if (ill_index == 0)
25980 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25981 		else
25982 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25983 		if (ipif == NULL) {
25984 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25985 			    " multicast\n"));
25986 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25987 			freemsg(ipsec_mp);
25988 			goto done;
25989 		}
25990 		/*
25991 		 * ipha_src has already been intialized with the
25992 		 * value of the ipif in ip_wput. All we need now is
25993 		 * an ire to send this downstream.
25994 		 */
25995 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25996 		    msg_getlabel(mp), match_flags, ipst);
25997 		if (ire != NULL) {
25998 			ill_t *ill1;
25999 			/*
26000 			 * Do the multicast forwarding now, as the IPsec
26001 			 * processing has been done.
26002 			 */
26003 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26004 			    (ill1 = ire_to_ill(ire))) {
26005 				if (ip_mforward(ill1, ipha, mp)) {
26006 					freemsg(ipsec_mp);
26007 					ip1dbg(("ip_wput_ipsec_out: mforward "
26008 					    "failed\n"));
26009 					ire_refrele(ire);
26010 					goto done;
26011 				}
26012 			}
26013 			goto send;
26014 		}
26015 
26016 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26017 		mp->b_prev = NULL;
26018 		mp->b_next = NULL;
26019 
26020 		/*
26021 		 * If the IPsec packet was processed asynchronously,
26022 		 * drop it now.
26023 		 */
26024 		if (q == NULL) {
26025 			freemsg(ipsec_mp);
26026 			goto done;
26027 		}
26028 
26029 		/*
26030 		 * We may be using a wrong ipif to create the ire.
26031 		 * But it is okay as the source address is assigned
26032 		 * for the packet already. Next outbound packet would
26033 		 * create the IRE with the right IPIF in ip_wput.
26034 		 *
26035 		 * Also handle RTF_MULTIRT routes.
26036 		 */
26037 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26038 		    zoneid, &zero_info);
26039 	} else {
26040 		if (ire_arg != NULL) {
26041 			ire = ire_arg;
26042 			ire_need_rele = B_FALSE;
26043 		} else {
26044 			ire = ire_cache_lookup(dst, zoneid,
26045 			    msg_getlabel(mp), ipst);
26046 		}
26047 		if (ire != NULL) {
26048 			goto send;
26049 		}
26050 
26051 		/*
26052 		 * ire disappeared underneath.
26053 		 *
26054 		 * What we need to do here is the ip_newroute
26055 		 * logic to get the ire without doing the IPsec
26056 		 * processing. Follow the same old path. But this
26057 		 * time, ip_wput or ire_add_then_put will call us
26058 		 * directly as all the IPsec operations are done.
26059 		 */
26060 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26061 		mp->b_prev = NULL;
26062 		mp->b_next = NULL;
26063 
26064 		/*
26065 		 * If the IPsec packet was processed asynchronously,
26066 		 * drop it now.
26067 		 */
26068 		if (q == NULL) {
26069 			freemsg(ipsec_mp);
26070 			goto done;
26071 		}
26072 
26073 		/*
26074 		 * Since we're going through ip_newroute() again, we
26075 		 * need to make sure we don't:
26076 		 *
26077 		 *	1.) Trigger the ASSERT() with the ipha_ident
26078 		 *	    overloading.
26079 		 *	2.) Redo transport-layer checksumming, since we've
26080 		 *	    already done all that to get this far.
26081 		 *
26082 		 * The easiest way not do either of the above is to set
26083 		 * the ipha_ident field to IP_HDR_INCLUDED.
26084 		 */
26085 		ipha->ipha_ident = IP_HDR_INCLUDED;
26086 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26087 		    zoneid, ipst);
26088 	}
26089 	goto done;
26090 send:
26091 	if (ire->ire_stq == NULL) {
26092 		ill_t	*out_ill;
26093 		/*
26094 		 * Loopbacks go through ip_wput_local except for one case.
26095 		 * We come here if we generate a icmp_frag_needed message
26096 		 * after IPsec processing is over. When this function calls
26097 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26098 		 * icmp_frag_needed. The message generated comes back here
26099 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26100 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26101 		 * source address as it is usually set in ip_wput_ire. As
26102 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26103 		 * and we end up here. We can't enter ip_wput_ire once the
26104 		 * IPsec processing is over and hence we need to do it here.
26105 		 */
26106 		ASSERT(q != NULL);
26107 		UPDATE_OB_PKT_COUNT(ire);
26108 		ire->ire_last_used_time = lbolt;
26109 		if (ipha->ipha_src == 0)
26110 			ipha->ipha_src = ire->ire_src_addr;
26111 
26112 		/* PFHooks: LOOPBACK_OUT */
26113 		out_ill = ire_to_ill(ire);
26114 
26115 		/*
26116 		 * DTrace this as ip:::send.  A blocked packet will fire the
26117 		 * send probe, but not the receive probe.
26118 		 */
26119 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26120 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26121 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26122 
26123 		DTRACE_PROBE4(ip4__loopback__out__start,
26124 		    ill_t *, NULL, ill_t *, out_ill,
26125 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26126 
26127 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26128 		    ipst->ips_ipv4firewall_loopback_out,
26129 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26130 
26131 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26132 
26133 		if (ipsec_mp != NULL)
26134 			ip_wput_local(RD(q), out_ill,
26135 			    ipha, ipsec_mp, ire, 0, zoneid);
26136 		if (ire_need_rele)
26137 			ire_refrele(ire);
26138 		goto done;
26139 	}
26140 
26141 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26142 		/*
26143 		 * We are through with IPsec processing.
26144 		 * Fragment this and send it on the wire.
26145 		 */
26146 		if (io->ipsec_out_accelerated) {
26147 			/*
26148 			 * The packet has been accelerated but must
26149 			 * be fragmented. This should not happen
26150 			 * since AH and ESP must not accelerate
26151 			 * packets that need fragmentation, however
26152 			 * the configuration could have changed
26153 			 * since the AH or ESP processing.
26154 			 * Drop packet.
26155 			 * IPsec KSTATS: bump bean counter here.
26156 			 */
26157 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26158 			    "fragmented accelerated packet!\n"));
26159 			freemsg(ipsec_mp);
26160 		} else {
26161 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26162 			    zoneid, ipst, NULL);
26163 		}
26164 		if (ire_need_rele)
26165 			ire_refrele(ire);
26166 		goto done;
26167 	}
26168 
26169 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26170 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26171 	    (void *)ire->ire_ipif, (void *)ipif));
26172 
26173 	/*
26174 	 * Multiroute the secured packet.
26175 	 */
26176 	if (ire->ire_flags & RTF_MULTIRT) {
26177 		ire_t *first_ire;
26178 		irb = ire->ire_bucket;
26179 		ASSERT(irb != NULL);
26180 		/*
26181 		 * This ire has been looked up as the one that
26182 		 * goes through the given ipif;
26183 		 * make sure we do not omit any other multiroute ire
26184 		 * that may be present in the bucket before this one.
26185 		 */
26186 		IRB_REFHOLD(irb);
26187 		for (first_ire = irb->irb_ire;
26188 		    first_ire != NULL;
26189 		    first_ire = first_ire->ire_next) {
26190 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26191 			    (first_ire->ire_addr == ire->ire_addr) &&
26192 			    !(first_ire->ire_marks &
26193 			    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN)))
26194 				break;
26195 		}
26196 
26197 		if ((first_ire != NULL) && (first_ire != ire)) {
26198 			/*
26199 			 * Don't change the ire if the packet must
26200 			 * be fragmented if sent via this new one.
26201 			 */
26202 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26203 				IRE_REFHOLD(first_ire);
26204 				if (ire_need_rele)
26205 					ire_refrele(ire);
26206 				else
26207 					ire_need_rele = B_TRUE;
26208 				ire = first_ire;
26209 			}
26210 		}
26211 		IRB_REFRELE(irb);
26212 
26213 		multirt_send = B_TRUE;
26214 		max_frag = ire->ire_max_frag;
26215 	}
26216 
26217 	/*
26218 	 * In most cases, the emission loop below is entered only once.
26219 	 * Only in the case where the ire holds the RTF_MULTIRT
26220 	 * flag, we loop to process all RTF_MULTIRT ires in the
26221 	 * bucket, and send the packet through all crossed
26222 	 * RTF_MULTIRT routes.
26223 	 */
26224 	do {
26225 		if (multirt_send) {
26226 			/*
26227 			 * ire1 holds here the next ire to process in the
26228 			 * bucket. If multirouting is expected,
26229 			 * any non-RTF_MULTIRT ire that has the
26230 			 * right destination address is ignored.
26231 			 */
26232 			ASSERT(irb != NULL);
26233 			IRB_REFHOLD(irb);
26234 			for (ire1 = ire->ire_next;
26235 			    ire1 != NULL;
26236 			    ire1 = ire1->ire_next) {
26237 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26238 					continue;
26239 				if (ire1->ire_addr != ire->ire_addr)
26240 					continue;
26241 				if (ire1->ire_marks &
26242 				    (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN))
26243 					continue;
26244 				/* No loopback here */
26245 				if (ire1->ire_stq == NULL)
26246 					continue;
26247 				/*
26248 				 * Ensure we do not exceed the MTU
26249 				 * of the next route.
26250 				 */
26251 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26252 					ip_multirt_bad_mtu(ire1, max_frag);
26253 					continue;
26254 				}
26255 
26256 				IRE_REFHOLD(ire1);
26257 				break;
26258 			}
26259 			IRB_REFRELE(irb);
26260 			if (ire1 != NULL) {
26261 				/*
26262 				 * We are in a multiple send case, need to
26263 				 * make a copy of the packet.
26264 				 */
26265 				next_mp = copymsg(ipsec_mp);
26266 				if (next_mp == NULL) {
26267 					ire_refrele(ire1);
26268 					ire1 = NULL;
26269 				}
26270 			}
26271 		}
26272 		/*
26273 		 * Everything is done. Send it out on the wire
26274 		 *
26275 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26276 		 * either send it on the wire or, in the case of
26277 		 * HW acceleration, call ipsec_hw_putnext.
26278 		 */
26279 		if (ire->ire_nce &&
26280 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26281 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26282 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26283 			/*
26284 			 * If ire's link-layer is unresolved (this
26285 			 * would only happen if the incomplete ire
26286 			 * was added to cachetable via forwarding path)
26287 			 * don't bother going to ip_xmit_v4. Just drop the
26288 			 * packet.
26289 			 * There is a slight risk here, in that, if we
26290 			 * have the forwarding path create an incomplete
26291 			 * IRE, then until the IRE is completed, any
26292 			 * transmitted IPsec packets will be dropped
26293 			 * instead of being queued waiting for resolution.
26294 			 *
26295 			 * But the likelihood of a forwarding packet and a wput
26296 			 * packet sending to the same dst at the same time
26297 			 * and there not yet be an ARP entry for it is small.
26298 			 * Furthermore, if this actually happens, it might
26299 			 * be likely that wput would generate multiple
26300 			 * packets (and forwarding would also have a train
26301 			 * of packets) for that destination. If this is
26302 			 * the case, some of them would have been dropped
26303 			 * anyway, since ARP only queues a few packets while
26304 			 * waiting for resolution
26305 			 *
26306 			 * NOTE: We should really call ip_xmit_v4,
26307 			 * and let it queue the packet and send the
26308 			 * ARP query and have ARP come back thus:
26309 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26310 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26311 			 * hw accel work. But it's too complex to get
26312 			 * the IPsec hw  acceleration approach to fit
26313 			 * well with ip_xmit_v4 doing ARP without
26314 			 * doing IPsec simplification. For now, we just
26315 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26316 			 * that we can continue with the send on the next
26317 			 * attempt.
26318 			 *
26319 			 * XXX THis should be revisited, when
26320 			 * the IPsec/IP interaction is cleaned up
26321 			 */
26322 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26323 			    " - dropping packet\n"));
26324 			freemsg(ipsec_mp);
26325 			/*
26326 			 * Call ip_xmit_v4() to trigger ARP query
26327 			 * in case the nce_state is ND_INITIAL
26328 			 */
26329 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26330 			goto drop_pkt;
26331 		}
26332 
26333 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26334 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26335 		    mblk_t *, ipsec_mp);
26336 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26337 		    ipst->ips_ipv4firewall_physical_out, NULL,
26338 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26339 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26340 		if (ipsec_mp == NULL)
26341 			goto drop_pkt;
26342 
26343 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26344 		pktxmit_state = ip_xmit_v4(mp, ire,
26345 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26346 
26347 		if ((pktxmit_state ==  SEND_FAILED) ||
26348 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26349 
26350 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26351 drop_pkt:
26352 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26353 			    ipIfStatsOutDiscards);
26354 			if (ire_need_rele)
26355 				ire_refrele(ire);
26356 			if (ire1 != NULL) {
26357 				ire_refrele(ire1);
26358 				freemsg(next_mp);
26359 			}
26360 			goto done;
26361 		}
26362 
26363 		freeb(ipsec_mp);
26364 		if (ire_need_rele)
26365 			ire_refrele(ire);
26366 
26367 		if (ire1 != NULL) {
26368 			ire = ire1;
26369 			ire_need_rele = B_TRUE;
26370 			ASSERT(next_mp);
26371 			ipsec_mp = next_mp;
26372 			mp = ipsec_mp->b_cont;
26373 			ire1 = NULL;
26374 			next_mp = NULL;
26375 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26376 		} else {
26377 			multirt_send = B_FALSE;
26378 		}
26379 	} while (multirt_send);
26380 done:
26381 	if (ill != NULL && ill_need_rele)
26382 		ill_refrele(ill);
26383 	if (ipif != NULL)
26384 		ipif_refrele(ipif);
26385 }
26386 
26387 /*
26388  * Get the ill corresponding to the specified ire, and compare its
26389  * capabilities with the protocol and algorithms specified by the
26390  * the SA obtained from ipsec_out. If they match, annotate the
26391  * ipsec_out structure to indicate that the packet needs acceleration.
26392  *
26393  *
26394  * A packet is eligible for outbound hardware acceleration if the
26395  * following conditions are satisfied:
26396  *
26397  * 1. the packet will not be fragmented
26398  * 2. the provider supports the algorithm
26399  * 3. there is no pending control message being exchanged
26400  * 4. snoop is not attached
26401  * 5. the destination address is not a broadcast or multicast address.
26402  *
26403  * Rationale:
26404  *	- Hardware drivers do not support fragmentation with
26405  *	  the current interface.
26406  *	- snoop, multicast, and broadcast may result in exposure of
26407  *	  a cleartext datagram.
26408  * We check all five of these conditions here.
26409  *
26410  * XXX would like to nuke "ire_t *" parameter here; problem is that
26411  * IRE is only way to figure out if a v4 address is a broadcast and
26412  * thus ineligible for acceleration...
26413  */
26414 static void
26415 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26416 {
26417 	ipsec_out_t *io;
26418 	mblk_t *data_mp;
26419 	uint_t plen, overhead;
26420 	ip_stack_t	*ipst;
26421 
26422 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26423 		return;
26424 
26425 	if (ill == NULL)
26426 		return;
26427 	ipst = ill->ill_ipst;
26428 	/*
26429 	 * Destination address is a broadcast or multicast.  Punt.
26430 	 */
26431 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26432 	    IRE_LOCAL)))
26433 		return;
26434 
26435 	data_mp = ipsec_mp->b_cont;
26436 
26437 	if (ill->ill_isv6) {
26438 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26439 
26440 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26441 			return;
26442 
26443 		plen = ip6h->ip6_plen;
26444 	} else {
26445 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26446 
26447 		if (CLASSD(ipha->ipha_dst))
26448 			return;
26449 
26450 		plen = ipha->ipha_length;
26451 	}
26452 	/*
26453 	 * Is there a pending DLPI control message being exchanged
26454 	 * between IP/IPsec and the DLS Provider? If there is, it
26455 	 * could be a SADB update, and the state of the DLS Provider
26456 	 * SADB might not be in sync with the SADB maintained by
26457 	 * IPsec. To avoid dropping packets or using the wrong keying
26458 	 * material, we do not accelerate this packet.
26459 	 */
26460 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26461 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26462 		    "ill_dlpi_pending! don't accelerate packet\n"));
26463 		return;
26464 	}
26465 
26466 	/*
26467 	 * Is the Provider in promiscous mode? If it does, we don't
26468 	 * accelerate the packet since it will bounce back up to the
26469 	 * listeners in the clear.
26470 	 */
26471 	if (ill->ill_promisc_on_phys) {
26472 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26473 		    "ill in promiscous mode, don't accelerate packet\n"));
26474 		return;
26475 	}
26476 
26477 	/*
26478 	 * Will the packet require fragmentation?
26479 	 */
26480 
26481 	/*
26482 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26483 	 * as is used elsewhere.
26484 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26485 	 *	+ 2-byte trailer
26486 	 */
26487 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26488 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26489 
26490 	if ((plen + overhead) > ill->ill_max_mtu)
26491 		return;
26492 
26493 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26494 
26495 	/*
26496 	 * Can the ill accelerate this IPsec protocol and algorithm
26497 	 * specified by the SA?
26498 	 */
26499 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26500 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26501 		return;
26502 	}
26503 
26504 	/*
26505 	 * Tell AH or ESP that the outbound ill is capable of
26506 	 * accelerating this packet.
26507 	 */
26508 	io->ipsec_out_is_capab_ill = B_TRUE;
26509 }
26510 
26511 /*
26512  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26513  *
26514  * If this function returns B_TRUE, the requested SA's have been filled
26515  * into the ipsec_out_*_sa pointers.
26516  *
26517  * If the function returns B_FALSE, the packet has been "consumed", most
26518  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26519  *
26520  * The SA references created by the protocol-specific "select"
26521  * function will be released when the ipsec_mp is freed, thanks to the
26522  * ipsec_out_free destructor -- see spd.c.
26523  */
26524 static boolean_t
26525 ipsec_out_select_sa(mblk_t *ipsec_mp)
26526 {
26527 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26528 	ipsec_out_t *io;
26529 	ipsec_policy_t *pp;
26530 	ipsec_action_t *ap;
26531 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26532 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26533 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26534 
26535 	if (!io->ipsec_out_secure) {
26536 		/*
26537 		 * We came here by mistake.
26538 		 * Don't bother with ipsec processing
26539 		 * We should "discourage" this path in the future.
26540 		 */
26541 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26542 		return (B_FALSE);
26543 	}
26544 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26545 	ASSERT((io->ipsec_out_policy != NULL) ||
26546 	    (io->ipsec_out_act != NULL));
26547 
26548 	ASSERT(io->ipsec_out_failed == B_FALSE);
26549 
26550 	/*
26551 	 * IPsec processing has started.
26552 	 */
26553 	io->ipsec_out_proc_begin = B_TRUE;
26554 	ap = io->ipsec_out_act;
26555 	if (ap == NULL) {
26556 		pp = io->ipsec_out_policy;
26557 		ASSERT(pp != NULL);
26558 		ap = pp->ipsp_act;
26559 		ASSERT(ap != NULL);
26560 	}
26561 
26562 	/*
26563 	 * We have an action.  now, let's select SA's.
26564 	 * (In the future, we can cache this in the conn_t..)
26565 	 */
26566 	if (ap->ipa_want_esp) {
26567 		if (io->ipsec_out_esp_sa == NULL) {
26568 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26569 			    IPPROTO_ESP);
26570 		}
26571 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26572 	}
26573 
26574 	if (ap->ipa_want_ah) {
26575 		if (io->ipsec_out_ah_sa == NULL) {
26576 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26577 			    IPPROTO_AH);
26578 		}
26579 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26580 		/*
26581 		 * The ESP and AH processing order needs to be preserved
26582 		 * when both protocols are required (ESP should be applied
26583 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26584 		 * when both ESP and AH are required, and an AH ACQUIRE
26585 		 * is needed.
26586 		 */
26587 		if (ap->ipa_want_esp && need_ah_acquire)
26588 			need_esp_acquire = B_TRUE;
26589 	}
26590 
26591 	/*
26592 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26593 	 * Release SAs that got referenced, but will not be used until we
26594 	 * acquire _all_ of the SAs we need.
26595 	 */
26596 	if (need_ah_acquire || need_esp_acquire) {
26597 		if (io->ipsec_out_ah_sa != NULL) {
26598 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26599 			io->ipsec_out_ah_sa = NULL;
26600 		}
26601 		if (io->ipsec_out_esp_sa != NULL) {
26602 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26603 			io->ipsec_out_esp_sa = NULL;
26604 		}
26605 
26606 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26607 		return (B_FALSE);
26608 	}
26609 
26610 	return (B_TRUE);
26611 }
26612 
26613 /*
26614  * Process an IPSEC_OUT message and see what you can
26615  * do with it.
26616  * IPQoS Notes:
26617  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26618  * IPsec.
26619  * XXX would like to nuke ire_t.
26620  * XXX ill_index better be "real"
26621  */
26622 void
26623 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26624 {
26625 	ipsec_out_t *io;
26626 	ipsec_policy_t *pp;
26627 	ipsec_action_t *ap;
26628 	ipha_t *ipha;
26629 	ip6_t *ip6h;
26630 	mblk_t *mp;
26631 	ill_t *ill;
26632 	zoneid_t zoneid;
26633 	ipsec_status_t ipsec_rc;
26634 	boolean_t ill_need_rele = B_FALSE;
26635 	ip_stack_t	*ipst;
26636 	ipsec_stack_t	*ipss;
26637 
26638 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26639 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26640 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26641 	ipst = io->ipsec_out_ns->netstack_ip;
26642 	mp = ipsec_mp->b_cont;
26643 
26644 	/*
26645 	 * Initiate IPPF processing. We do it here to account for packets
26646 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26647 	 * We can check for ipsec_out_proc_begin even for such packets, as
26648 	 * they will always be false (asserted below).
26649 	 */
26650 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26651 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26652 		    io->ipsec_out_ill_index : ill_index);
26653 		if (mp == NULL) {
26654 			ip2dbg(("ipsec_out_process: packet dropped "\
26655 			    "during IPPF processing\n"));
26656 			freeb(ipsec_mp);
26657 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26658 			return;
26659 		}
26660 	}
26661 
26662 	if (!io->ipsec_out_secure) {
26663 		/*
26664 		 * We came here by mistake.
26665 		 * Don't bother with ipsec processing
26666 		 * Should "discourage" this path in the future.
26667 		 */
26668 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26669 		goto done;
26670 	}
26671 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26672 	ASSERT((io->ipsec_out_policy != NULL) ||
26673 	    (io->ipsec_out_act != NULL));
26674 	ASSERT(io->ipsec_out_failed == B_FALSE);
26675 
26676 	ipss = ipst->ips_netstack->netstack_ipsec;
26677 	if (!ipsec_loaded(ipss)) {
26678 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26679 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26680 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26681 		} else {
26682 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26683 		}
26684 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26685 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26686 		    &ipss->ipsec_dropper);
26687 		return;
26688 	}
26689 
26690 	/*
26691 	 * IPsec processing has started.
26692 	 */
26693 	io->ipsec_out_proc_begin = B_TRUE;
26694 	ap = io->ipsec_out_act;
26695 	if (ap == NULL) {
26696 		pp = io->ipsec_out_policy;
26697 		ASSERT(pp != NULL);
26698 		ap = pp->ipsp_act;
26699 		ASSERT(ap != NULL);
26700 	}
26701 
26702 	/*
26703 	 * Save the outbound ill index. When the packet comes back
26704 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26705 	 * before sending it the accelerated packet.
26706 	 */
26707 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26708 		ill = ire_to_ill(ire);
26709 		io->ipsec_out_capab_ill_index = ill->ill_phyint->phyint_ifindex;
26710 	}
26711 
26712 	/*
26713 	 * The order of processing is first insert a IP header if needed.
26714 	 * Then insert the ESP header and then the AH header.
26715 	 */
26716 	if ((io->ipsec_out_se_done == B_FALSE) &&
26717 	    (ap->ipa_want_se)) {
26718 		/*
26719 		 * First get the outer IP header before sending
26720 		 * it to ESP.
26721 		 */
26722 		ipha_t *oipha, *iipha;
26723 		mblk_t *outer_mp, *inner_mp;
26724 
26725 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26726 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26727 			    "ipsec_out_process: "
26728 			    "Self-Encapsulation failed: Out of memory\n");
26729 			freemsg(ipsec_mp);
26730 			if (ill != NULL) {
26731 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26732 			} else {
26733 				BUMP_MIB(&ipst->ips_ip_mib,
26734 				    ipIfStatsOutDiscards);
26735 			}
26736 			return;
26737 		}
26738 		inner_mp = ipsec_mp->b_cont;
26739 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26740 		oipha = (ipha_t *)outer_mp->b_rptr;
26741 		iipha = (ipha_t *)inner_mp->b_rptr;
26742 		*oipha = *iipha;
26743 		outer_mp->b_wptr += sizeof (ipha_t);
26744 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26745 		    sizeof (ipha_t));
26746 		oipha->ipha_protocol = IPPROTO_ENCAP;
26747 		oipha->ipha_version_and_hdr_length =
26748 		    IP_SIMPLE_HDR_VERSION;
26749 		oipha->ipha_hdr_checksum = 0;
26750 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26751 		outer_mp->b_cont = inner_mp;
26752 		ipsec_mp->b_cont = outer_mp;
26753 
26754 		io->ipsec_out_se_done = B_TRUE;
26755 		io->ipsec_out_tunnel = B_TRUE;
26756 	}
26757 
26758 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26759 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26760 	    !ipsec_out_select_sa(ipsec_mp))
26761 		return;
26762 
26763 	/*
26764 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26765 	 * to do the heavy lifting.
26766 	 */
26767 	zoneid = io->ipsec_out_zoneid;
26768 	ASSERT(zoneid != ALL_ZONES);
26769 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26770 		ASSERT(io->ipsec_out_esp_sa != NULL);
26771 		io->ipsec_out_esp_done = B_TRUE;
26772 		/*
26773 		 * Note that since hw accel can only apply one transform,
26774 		 * not two, we skip hw accel for ESP if we also have AH
26775 		 * This is an design limitation of the interface
26776 		 * which should be revisited.
26777 		 */
26778 		ASSERT(ire != NULL);
26779 		if (io->ipsec_out_ah_sa == NULL) {
26780 			ill = (ill_t *)ire->ire_stq->q_ptr;
26781 			ipsec_out_is_accelerated(ipsec_mp,
26782 			    io->ipsec_out_esp_sa, ill, ire);
26783 		}
26784 
26785 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26786 		switch (ipsec_rc) {
26787 		case IPSEC_STATUS_SUCCESS:
26788 			break;
26789 		case IPSEC_STATUS_FAILED:
26790 			if (ill != NULL) {
26791 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26792 			} else {
26793 				BUMP_MIB(&ipst->ips_ip_mib,
26794 				    ipIfStatsOutDiscards);
26795 			}
26796 			/* FALLTHRU */
26797 		case IPSEC_STATUS_PENDING:
26798 			return;
26799 		}
26800 	}
26801 
26802 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26803 		ASSERT(io->ipsec_out_ah_sa != NULL);
26804 		io->ipsec_out_ah_done = B_TRUE;
26805 		if (ire == NULL) {
26806 			int idx = io->ipsec_out_capab_ill_index;
26807 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26808 			    NULL, NULL, NULL, NULL, ipst);
26809 			ill_need_rele = B_TRUE;
26810 		} else {
26811 			ill = (ill_t *)ire->ire_stq->q_ptr;
26812 		}
26813 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26814 		    ire);
26815 
26816 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26817 		switch (ipsec_rc) {
26818 		case IPSEC_STATUS_SUCCESS:
26819 			break;
26820 		case IPSEC_STATUS_FAILED:
26821 			if (ill != NULL) {
26822 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26823 			} else {
26824 				BUMP_MIB(&ipst->ips_ip_mib,
26825 				    ipIfStatsOutDiscards);
26826 			}
26827 			/* FALLTHRU */
26828 		case IPSEC_STATUS_PENDING:
26829 			if (ill != NULL && ill_need_rele)
26830 				ill_refrele(ill);
26831 			return;
26832 		}
26833 	}
26834 	/*
26835 	 * We are done with IPsec processing. Send it over the wire.
26836 	 */
26837 done:
26838 	mp = ipsec_mp->b_cont;
26839 	ipha = (ipha_t *)mp->b_rptr;
26840 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26841 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ire->ire_ipif->ipif_ill,
26842 		    ire);
26843 	} else {
26844 		ip6h = (ip6_t *)ipha;
26845 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ire->ire_ipif->ipif_ill,
26846 		    ire);
26847 	}
26848 	if (ill != NULL && ill_need_rele)
26849 		ill_refrele(ill);
26850 }
26851 
26852 /* ARGSUSED */
26853 void
26854 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26855 {
26856 	opt_restart_t	*or;
26857 	int	err;
26858 	conn_t	*connp;
26859 	cred_t	*cr;
26860 
26861 	ASSERT(CONN_Q(q));
26862 	connp = Q_TO_CONN(q);
26863 
26864 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26865 	or = (opt_restart_t *)first_mp->b_rptr;
26866 	/*
26867 	 * We checked for a db_credp the first time svr4_optcom_req
26868 	 * was called (from ip_wput_nondata). So we can just ASSERT here.
26869 	 */
26870 	cr = msg_getcred(first_mp, NULL);
26871 	ASSERT(cr != NULL);
26872 
26873 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26874 		err = svr4_optcom_req(q, first_mp, cr,
26875 		    &ip_opt_obj, B_FALSE);
26876 	} else {
26877 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26878 		err = tpi_optcom_req(q, first_mp, cr,
26879 		    &ip_opt_obj, B_FALSE);
26880 	}
26881 	if (err != EINPROGRESS) {
26882 		/* operation is done */
26883 		CONN_OPER_PENDING_DONE(connp);
26884 	}
26885 }
26886 
26887 /*
26888  * ioctls that go through a down/up sequence may need to wait for the down
26889  * to complete. This involves waiting for the ire and ipif refcnts to go down
26890  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26891  */
26892 /* ARGSUSED */
26893 void
26894 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26895 {
26896 	struct iocblk *iocp;
26897 	mblk_t *mp1;
26898 	ip_ioctl_cmd_t *ipip;
26899 	int err;
26900 	sin_t	*sin;
26901 	struct lifreq *lifr;
26902 	struct ifreq *ifr;
26903 
26904 	iocp = (struct iocblk *)mp->b_rptr;
26905 	ASSERT(ipsq != NULL);
26906 	/* Existence of mp1 verified in ip_wput_nondata */
26907 	mp1 = mp->b_cont->b_cont;
26908 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26909 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26910 		/*
26911 		 * Special case where ipx_current_ipif is not set:
26912 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26913 		 * We are here as were not able to complete the operation in
26914 		 * ipif_set_values because we could not become exclusive on
26915 		 * the new ipsq.
26916 		 */
26917 		ill_t *ill = q->q_ptr;
26918 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26919 	}
26920 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
26921 
26922 	if (ipip->ipi_cmd_type == IF_CMD) {
26923 		/* This a old style SIOC[GS]IF* command */
26924 		ifr = (struct ifreq *)mp1->b_rptr;
26925 		sin = (sin_t *)&ifr->ifr_addr;
26926 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26927 		/* This a new style SIOC[GS]LIF* command */
26928 		lifr = (struct lifreq *)mp1->b_rptr;
26929 		sin = (sin_t *)&lifr->lifr_addr;
26930 	} else {
26931 		sin = NULL;
26932 	}
26933 
26934 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
26935 	    q, mp, ipip, mp1->b_rptr);
26936 
26937 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26938 }
26939 
26940 /*
26941  * ioctl processing
26942  *
26943  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26944  * the ioctl command in the ioctl tables, determines the copyin data size
26945  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26946  *
26947  * ioctl processing then continues when the M_IOCDATA makes its way down to
26948  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26949  * associated 'conn' is refheld till the end of the ioctl and the general
26950  * ioctl processing function ip_process_ioctl() is called to extract the
26951  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26952  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26953  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26954  * is used to extract the ioctl's arguments.
26955  *
26956  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26957  * so goes thru the serialization primitive ipsq_try_enter. Then the
26958  * appropriate function to handle the ioctl is called based on the entry in
26959  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26960  * which also refreleases the 'conn' that was refheld at the start of the
26961  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26962  *
26963  * Many exclusive ioctls go thru an internal down up sequence as part of
26964  * the operation. For example an attempt to change the IP address of an
26965  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26966  * does all the cleanup such as deleting all ires that use this address.
26967  * Then we need to wait till all references to the interface go away.
26968  */
26969 void
26970 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26971 {
26972 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26973 	ip_ioctl_cmd_t *ipip = arg;
26974 	ip_extract_func_t *extract_funcp;
26975 	cmd_info_t ci;
26976 	int err;
26977 	boolean_t entered_ipsq = B_FALSE;
26978 
26979 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26980 
26981 	if (ipip == NULL)
26982 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26983 
26984 	/*
26985 	 * SIOCLIFADDIF needs to go thru a special path since the
26986 	 * ill may not exist yet. This happens in the case of lo0
26987 	 * which is created using this ioctl.
26988 	 */
26989 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26990 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26991 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26992 		return;
26993 	}
26994 
26995 	ci.ci_ipif = NULL;
26996 	if (ipip->ipi_cmd_type == MISC_CMD) {
26997 		/*
26998 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26999 		 */
27000 		if (ipip->ipi_cmd == IF_UNITSEL) {
27001 			/* ioctl comes down the ill */
27002 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27003 			ipif_refhold(ci.ci_ipif);
27004 		}
27005 		err = 0;
27006 		ci.ci_sin = NULL;
27007 		ci.ci_sin6 = NULL;
27008 		ci.ci_lifr = NULL;
27009 	} else {
27010 		switch (ipip->ipi_cmd_type) {
27011 		case IF_CMD:
27012 		case LIF_CMD:
27013 			extract_funcp = ip_extract_lifreq;
27014 			break;
27015 
27016 		case ARP_CMD:
27017 		case XARP_CMD:
27018 			extract_funcp = ip_extract_arpreq;
27019 			break;
27020 
27021 		case TUN_CMD:
27022 			extract_funcp = ip_extract_tunreq;
27023 			break;
27024 
27025 		case MSFILT_CMD:
27026 			extract_funcp = ip_extract_msfilter;
27027 			break;
27028 
27029 		default:
27030 			ASSERT(0);
27031 		}
27032 
27033 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27034 		if (err != 0) {
27035 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27036 			return;
27037 		}
27038 
27039 		/*
27040 		 * All of the extraction functions return a refheld ipif.
27041 		 */
27042 		ASSERT(ci.ci_ipif != NULL);
27043 	}
27044 
27045 	if (!(ipip->ipi_flags & IPI_WR)) {
27046 		/*
27047 		 * A return value of EINPROGRESS means the ioctl is
27048 		 * either queued and waiting for some reason or has
27049 		 * already completed.
27050 		 */
27051 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27052 		    ci.ci_lifr);
27053 		if (ci.ci_ipif != NULL)
27054 			ipif_refrele(ci.ci_ipif);
27055 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27056 		return;
27057 	}
27058 
27059 	ASSERT(ci.ci_ipif != NULL);
27060 
27061 	/*
27062 	 * If ipsq is non-NULL, we are already being called exclusively.
27063 	 */
27064 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27065 	if (ipsq == NULL) {
27066 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27067 		    NEW_OP, B_TRUE);
27068 		if (ipsq == NULL) {
27069 			ipif_refrele(ci.ci_ipif);
27070 			return;
27071 		}
27072 		entered_ipsq = B_TRUE;
27073 	}
27074 
27075 	/*
27076 	 * Release the ipif so that ipif_down and friends that wait for
27077 	 * references to go away are not misled about the current ipif_refcnt
27078 	 * values. We are writer so we can access the ipif even after releasing
27079 	 * the ipif.
27080 	 */
27081 	ipif_refrele(ci.ci_ipif);
27082 
27083 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27084 
27085 	/*
27086 	 * A return value of EINPROGRESS means the ioctl is
27087 	 * either queued and waiting for some reason or has
27088 	 * already completed.
27089 	 */
27090 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27091 
27092 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27093 
27094 	if (entered_ipsq)
27095 		ipsq_exit(ipsq);
27096 }
27097 
27098 /*
27099  * Complete the ioctl. Typically ioctls use the mi package and need to
27100  * do mi_copyout/mi_copy_done.
27101  */
27102 void
27103 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27104 {
27105 	conn_t	*connp = NULL;
27106 
27107 	if (err == EINPROGRESS)
27108 		return;
27109 
27110 	if (CONN_Q(q)) {
27111 		connp = Q_TO_CONN(q);
27112 		ASSERT(connp->conn_ref >= 2);
27113 	}
27114 
27115 	switch (mode) {
27116 	case COPYOUT:
27117 		if (err == 0)
27118 			mi_copyout(q, mp);
27119 		else
27120 			mi_copy_done(q, mp, err);
27121 		break;
27122 
27123 	case NO_COPYOUT:
27124 		mi_copy_done(q, mp, err);
27125 		break;
27126 
27127 	default:
27128 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27129 		break;
27130 	}
27131 
27132 	/*
27133 	 * The refhold placed at the start of the ioctl is released here.
27134 	 */
27135 	if (connp != NULL)
27136 		CONN_OPER_PENDING_DONE(connp);
27137 
27138 	if (ipsq != NULL)
27139 		ipsq_current_finish(ipsq);
27140 }
27141 
27142 /* Called from ip_wput for all non data messages */
27143 /* ARGSUSED */
27144 void
27145 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27146 {
27147 	mblk_t		*mp1;
27148 	ire_t		*ire, *fake_ire;
27149 	ill_t		*ill;
27150 	struct iocblk	*iocp;
27151 	ip_ioctl_cmd_t	*ipip;
27152 	cred_t		*cr;
27153 	conn_t		*connp;
27154 	int		err;
27155 	nce_t		*nce;
27156 	ipif_t		*ipif;
27157 	ip_stack_t	*ipst;
27158 	char		*proto_str;
27159 
27160 	if (CONN_Q(q)) {
27161 		connp = Q_TO_CONN(q);
27162 		ipst = connp->conn_netstack->netstack_ip;
27163 	} else {
27164 		connp = NULL;
27165 		ipst = ILLQ_TO_IPST(q);
27166 	}
27167 
27168 	switch (DB_TYPE(mp)) {
27169 	case M_IOCTL:
27170 		/*
27171 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27172 		 * will arrange to copy in associated control structures.
27173 		 */
27174 		ip_sioctl_copyin_setup(q, mp);
27175 		return;
27176 	case M_IOCDATA:
27177 		/*
27178 		 * Ensure that this is associated with one of our trans-
27179 		 * parent ioctls.  If it's not ours, discard it if we're
27180 		 * running as a driver, or pass it on if we're a module.
27181 		 */
27182 		iocp = (struct iocblk *)mp->b_rptr;
27183 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27184 		if (ipip == NULL) {
27185 			if (q->q_next == NULL) {
27186 				goto nak;
27187 			} else {
27188 				putnext(q, mp);
27189 			}
27190 			return;
27191 		}
27192 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27193 			/*
27194 			 * the ioctl is one we recognise, but is not
27195 			 * consumed by IP as a module, pass M_IOCDATA
27196 			 * for processing downstream, but only for
27197 			 * common Streams ioctls.
27198 			 */
27199 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27200 				putnext(q, mp);
27201 				return;
27202 			} else {
27203 				goto nak;
27204 			}
27205 		}
27206 
27207 		/* IOCTL continuation following copyin or copyout. */
27208 		if (mi_copy_state(q, mp, NULL) == -1) {
27209 			/*
27210 			 * The copy operation failed.  mi_copy_state already
27211 			 * cleaned up, so we're out of here.
27212 			 */
27213 			return;
27214 		}
27215 		/*
27216 		 * If we just completed a copy in, we become writer and
27217 		 * continue processing in ip_sioctl_copyin_done.  If it
27218 		 * was a copy out, we call mi_copyout again.  If there is
27219 		 * nothing more to copy out, it will complete the IOCTL.
27220 		 */
27221 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27222 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27223 				mi_copy_done(q, mp, EPROTO);
27224 				return;
27225 			}
27226 			/*
27227 			 * Check for cases that need more copying.  A return
27228 			 * value of 0 means a second copyin has been started,
27229 			 * so we return; a return value of 1 means no more
27230 			 * copying is needed, so we continue.
27231 			 */
27232 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27233 			    MI_COPY_COUNT(mp) == 1) {
27234 				if (ip_copyin_msfilter(q, mp) == 0)
27235 					return;
27236 			}
27237 			/*
27238 			 * Refhold the conn, till the ioctl completes. This is
27239 			 * needed in case the ioctl ends up in the pending mp
27240 			 * list. Every mp in the ill_pending_mp list and
27241 			 * the ipx_pending_mp must have a refhold on the conn
27242 			 * to resume processing. The refhold is released when
27243 			 * the ioctl completes. (normally or abnormally)
27244 			 * In all cases ip_ioctl_finish is called to finish
27245 			 * the ioctl.
27246 			 */
27247 			if (connp != NULL) {
27248 				/* This is not a reentry */
27249 				ASSERT(ipsq == NULL);
27250 				CONN_INC_REF(connp);
27251 			} else {
27252 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27253 					mi_copy_done(q, mp, EINVAL);
27254 					return;
27255 				}
27256 			}
27257 
27258 			ip_process_ioctl(ipsq, q, mp, ipip);
27259 
27260 		} else {
27261 			mi_copyout(q, mp);
27262 		}
27263 		return;
27264 nak:
27265 		iocp->ioc_error = EINVAL;
27266 		mp->b_datap->db_type = M_IOCNAK;
27267 		iocp->ioc_count = 0;
27268 		qreply(q, mp);
27269 		return;
27270 
27271 	case M_IOCNAK:
27272 		/*
27273 		 * The only way we could get here is if a resolver didn't like
27274 		 * an IOCTL we sent it.	 This shouldn't happen.
27275 		 */
27276 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27277 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27278 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27279 		freemsg(mp);
27280 		return;
27281 	case M_IOCACK:
27282 		/* /dev/ip shouldn't see this */
27283 		if (CONN_Q(q))
27284 			goto nak;
27285 
27286 		/*
27287 		 * Finish socket ioctls passed through to ARP.  We use the
27288 		 * ioc_cmd values we set in ip_sioctl_arp() to decide whether
27289 		 * we need to become writer before calling ip_sioctl_iocack().
27290 		 * Note that qwriter_ip() will release the refhold, and that a
27291 		 * refhold is OK without ILL_CAN_LOOKUP() since we're on the
27292 		 * ill stream.
27293 		 */
27294 		iocp = (struct iocblk *)mp->b_rptr;
27295 		if (iocp->ioc_cmd == AR_ENTRY_SQUERY) {
27296 			ip_sioctl_iocack(NULL, q, mp, NULL);
27297 			return;
27298 		}
27299 
27300 		ASSERT(iocp->ioc_cmd == AR_ENTRY_DELETE ||
27301 		    iocp->ioc_cmd == AR_ENTRY_ADD);
27302 		ill = q->q_ptr;
27303 		ill_refhold(ill);
27304 		qwriter_ip(ill, q, mp, ip_sioctl_iocack, CUR_OP, B_FALSE);
27305 		return;
27306 	case M_FLUSH:
27307 		if (*mp->b_rptr & FLUSHW)
27308 			flushq(q, FLUSHALL);
27309 		if (q->q_next) {
27310 			putnext(q, mp);
27311 			return;
27312 		}
27313 		if (*mp->b_rptr & FLUSHR) {
27314 			*mp->b_rptr &= ~FLUSHW;
27315 			qreply(q, mp);
27316 			return;
27317 		}
27318 		freemsg(mp);
27319 		return;
27320 	case IRE_DB_REQ_TYPE:
27321 		if (connp == NULL) {
27322 			proto_str = "IRE_DB_REQ_TYPE";
27323 			goto protonak;
27324 		}
27325 		/* An Upper Level Protocol wants a copy of an IRE. */
27326 		ip_ire_req(q, mp);
27327 		return;
27328 	case M_CTL:
27329 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27330 			break;
27331 
27332 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27333 		    TUN_HELLO) {
27334 			ASSERT(connp != NULL);
27335 			connp->conn_flags |= IPCL_IPTUN;
27336 			freeb(mp);
27337 			return;
27338 		}
27339 
27340 		/* M_CTL messages are used by ARP to tell us things. */
27341 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27342 			break;
27343 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27344 		case AR_ENTRY_SQUERY:
27345 			putnext(q, mp);
27346 			return;
27347 		case AR_CLIENT_NOTIFY:
27348 			ip_arp_news(q, mp);
27349 			return;
27350 		case AR_DLPIOP_DONE:
27351 			ASSERT(q->q_next != NULL);
27352 			ill = (ill_t *)q->q_ptr;
27353 			/* qwriter_ip releases the refhold */
27354 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27355 			ill_refhold(ill);
27356 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27357 			return;
27358 		case AR_ARP_CLOSING:
27359 			/*
27360 			 * ARP (above us) is closing. If no ARP bringup is
27361 			 * currently pending, ack the message so that ARP
27362 			 * can complete its close. Also mark ill_arp_closing
27363 			 * so that new ARP bringups will fail. If any
27364 			 * ARP bringup is currently in progress, we will
27365 			 * ack this when the current ARP bringup completes.
27366 			 */
27367 			ASSERT(q->q_next != NULL);
27368 			ill = (ill_t *)q->q_ptr;
27369 			mutex_enter(&ill->ill_lock);
27370 			ill->ill_arp_closing = 1;
27371 			if (!ill->ill_arp_bringup_pending) {
27372 				mutex_exit(&ill->ill_lock);
27373 				qreply(q, mp);
27374 			} else {
27375 				mutex_exit(&ill->ill_lock);
27376 				freemsg(mp);
27377 			}
27378 			return;
27379 		case AR_ARP_EXTEND:
27380 			/*
27381 			 * The ARP module above us is capable of duplicate
27382 			 * address detection.  Old ATM drivers will not send
27383 			 * this message.
27384 			 */
27385 			ASSERT(q->q_next != NULL);
27386 			ill = (ill_t *)q->q_ptr;
27387 			ill->ill_arp_extend = B_TRUE;
27388 			freemsg(mp);
27389 			return;
27390 		default:
27391 			break;
27392 		}
27393 		break;
27394 	case M_PROTO:
27395 	case M_PCPROTO:
27396 		/*
27397 		 * The only PROTO messages we expect are copies of option
27398 		 * negotiation acknowledgements, AH and ESP bind requests
27399 		 * are also expected.
27400 		 */
27401 		switch (((union T_primitives *)mp->b_rptr)->type) {
27402 		case O_T_BIND_REQ:
27403 		case T_BIND_REQ: {
27404 			/* Request can get queued in bind */
27405 			if (connp == NULL) {
27406 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27407 				goto protonak;
27408 			}
27409 			/*
27410 			 * The transports except SCTP call ip_bind_{v4,v6}()
27411 			 * directly instead of a a putnext. SCTP doesn't
27412 			 * generate any T_BIND_REQ since it has its own
27413 			 * fanout data structures. However, ESP and AH
27414 			 * come in for regular binds; all other cases are
27415 			 * bind retries.
27416 			 */
27417 			ASSERT(!IPCL_IS_SCTP(connp));
27418 
27419 			/* Don't increment refcnt if this is a re-entry */
27420 			if (ipsq == NULL)
27421 				CONN_INC_REF(connp);
27422 
27423 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27424 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27425 			ASSERT(mp != NULL);
27426 
27427 			ASSERT(!IPCL_IS_TCP(connp));
27428 			ASSERT(!IPCL_IS_UDP(connp));
27429 			ASSERT(!IPCL_IS_RAWIP(connp));
27430 
27431 			/* The case of AH and ESP */
27432 			qreply(q, mp);
27433 			CONN_OPER_PENDING_DONE(connp);
27434 			return;
27435 		}
27436 		case T_SVR4_OPTMGMT_REQ:
27437 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27438 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27439 
27440 			if (connp == NULL) {
27441 				proto_str = "T_SVR4_OPTMGMT_REQ";
27442 				goto protonak;
27443 			}
27444 
27445 			/*
27446 			 * All Solaris components should pass a db_credp
27447 			 * for this TPI message, hence we ASSERT.
27448 			 * But in case there is some other M_PROTO that looks
27449 			 * like a TPI message sent by some other kernel
27450 			 * component, we check and return an error.
27451 			 */
27452 			cr = msg_getcred(mp, NULL);
27453 			ASSERT(cr != NULL);
27454 			if (cr == NULL) {
27455 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27456 				if (mp != NULL)
27457 					qreply(q, mp);
27458 				return;
27459 			}
27460 
27461 			if (!snmpcom_req(q, mp, ip_snmp_set,
27462 			    ip_snmp_get, cr)) {
27463 				/*
27464 				 * Call svr4_optcom_req so that it can
27465 				 * generate the ack. We don't come here
27466 				 * if this operation is being restarted.
27467 				 * ip_restart_optmgmt will drop the conn ref.
27468 				 * In the case of ipsec option after the ipsec
27469 				 * load is complete conn_restart_ipsec_waiter
27470 				 * drops the conn ref.
27471 				 */
27472 				ASSERT(ipsq == NULL);
27473 				CONN_INC_REF(connp);
27474 				if (ip_check_for_ipsec_opt(q, mp))
27475 					return;
27476 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27477 				    B_FALSE);
27478 				if (err != EINPROGRESS) {
27479 					/* Operation is done */
27480 					CONN_OPER_PENDING_DONE(connp);
27481 				}
27482 			}
27483 			return;
27484 		case T_OPTMGMT_REQ:
27485 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27486 			/*
27487 			 * Note: No snmpcom_req support through new
27488 			 * T_OPTMGMT_REQ.
27489 			 * Call tpi_optcom_req so that it can
27490 			 * generate the ack.
27491 			 */
27492 			if (connp == NULL) {
27493 				proto_str = "T_OPTMGMT_REQ";
27494 				goto protonak;
27495 			}
27496 
27497 			/*
27498 			 * All Solaris components should pass a db_credp
27499 			 * for this TPI message, hence we ASSERT.
27500 			 * But in case there is some other M_PROTO that looks
27501 			 * like a TPI message sent by some other kernel
27502 			 * component, we check and return an error.
27503 			 */
27504 			cr = msg_getcred(mp, NULL);
27505 			ASSERT(cr != NULL);
27506 			if (cr == NULL) {
27507 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
27508 				if (mp != NULL)
27509 					qreply(q, mp);
27510 				return;
27511 			}
27512 			ASSERT(ipsq == NULL);
27513 			/*
27514 			 * We don't come here for restart. ip_restart_optmgmt
27515 			 * will drop the conn ref. In the case of ipsec option
27516 			 * after the ipsec load is complete
27517 			 * conn_restart_ipsec_waiter drops the conn ref.
27518 			 */
27519 			CONN_INC_REF(connp);
27520 			if (ip_check_for_ipsec_opt(q, mp))
27521 				return;
27522 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27523 			if (err != EINPROGRESS) {
27524 				/* Operation is done */
27525 				CONN_OPER_PENDING_DONE(connp);
27526 			}
27527 			return;
27528 		case T_UNBIND_REQ:
27529 			if (connp == NULL) {
27530 				proto_str = "T_UNBIND_REQ";
27531 				goto protonak;
27532 			}
27533 			ip_unbind(Q_TO_CONN(q));
27534 			mp = mi_tpi_ok_ack_alloc(mp);
27535 			qreply(q, mp);
27536 			return;
27537 		default:
27538 			/*
27539 			 * Have to drop any DLPI messages coming down from
27540 			 * arp (such as an info_req which would cause ip
27541 			 * to receive an extra info_ack if it was passed
27542 			 * through.
27543 			 */
27544 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27545 			    (int)*(uint_t *)mp->b_rptr));
27546 			freemsg(mp);
27547 			return;
27548 		}
27549 		/* NOTREACHED */
27550 	case IRE_DB_TYPE: {
27551 		nce_t		*nce;
27552 		ill_t		*ill;
27553 		in6_addr_t	gw_addr_v6;
27554 
27555 		/*
27556 		 * This is a response back from a resolver.  It
27557 		 * consists of a message chain containing:
27558 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27559 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27560 		 * The LL_HDR_MBLK is the DLPI header to use to get
27561 		 * the attached packet, and subsequent ones for the
27562 		 * same destination, transmitted.
27563 		 */
27564 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27565 			break;
27566 		/*
27567 		 * First, check to make sure the resolution succeeded.
27568 		 * If it failed, the second mblk will be empty.
27569 		 * If it is, free the chain, dropping the packet.
27570 		 * (We must ire_delete the ire; that frees the ire mblk)
27571 		 * We're doing this now to support PVCs for ATM; it's
27572 		 * a partial xresolv implementation. When we fully implement
27573 		 * xresolv interfaces, instead of freeing everything here
27574 		 * we'll initiate neighbor discovery.
27575 		 *
27576 		 * For v4 (ARP and other external resolvers) the resolver
27577 		 * frees the message, so no check is needed. This check
27578 		 * is required, though, for a full xresolve implementation.
27579 		 * Including this code here now both shows how external
27580 		 * resolvers can NACK a resolution request using an
27581 		 * existing design that has no specific provisions for NACKs,
27582 		 * and also takes into account that the current non-ARP
27583 		 * external resolver has been coded to use this method of
27584 		 * NACKing for all IPv6 (xresolv) cases,
27585 		 * whether our xresolv implementation is complete or not.
27586 		 *
27587 		 */
27588 		ire = (ire_t *)mp->b_rptr;
27589 		ill = ire_to_ill(ire);
27590 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27591 		if (mp1->b_rptr == mp1->b_wptr) {
27592 			if (ire->ire_ipversion == IPV6_VERSION) {
27593 				/*
27594 				 * XRESOLV interface.
27595 				 */
27596 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27597 				mutex_enter(&ire->ire_lock);
27598 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27599 				mutex_exit(&ire->ire_lock);
27600 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27601 					nce = ndp_lookup_v6(ill, B_FALSE,
27602 					    &ire->ire_addr_v6, B_FALSE);
27603 				} else {
27604 					nce = ndp_lookup_v6(ill, B_FALSE,
27605 					    &gw_addr_v6, B_FALSE);
27606 				}
27607 				if (nce != NULL) {
27608 					nce_resolv_failed(nce);
27609 					ndp_delete(nce);
27610 					NCE_REFRELE(nce);
27611 				}
27612 			}
27613 			mp->b_cont = NULL;
27614 			freemsg(mp1);		/* frees the pkt as well */
27615 			ASSERT(ire->ire_nce == NULL);
27616 			ire_delete((ire_t *)mp->b_rptr);
27617 			return;
27618 		}
27619 
27620 		/*
27621 		 * Split them into IRE_MBLK and pkt and feed it into
27622 		 * ire_add_then_send. Then in ire_add_then_send
27623 		 * the IRE will be added, and then the packet will be
27624 		 * run back through ip_wput. This time it will make
27625 		 * it to the wire.
27626 		 */
27627 		mp->b_cont = NULL;
27628 		mp = mp1->b_cont;		/* now, mp points to pkt */
27629 		mp1->b_cont = NULL;
27630 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27631 		if (ire->ire_ipversion == IPV6_VERSION) {
27632 			/*
27633 			 * XRESOLV interface. Find the nce and put a copy
27634 			 * of the dl_unitdata_req in nce_res_mp
27635 			 */
27636 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27637 			mutex_enter(&ire->ire_lock);
27638 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27639 			mutex_exit(&ire->ire_lock);
27640 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27641 				nce = ndp_lookup_v6(ill, B_FALSE,
27642 				    &ire->ire_addr_v6, B_FALSE);
27643 			} else {
27644 				nce = ndp_lookup_v6(ill, B_FALSE,
27645 				    &gw_addr_v6, B_FALSE);
27646 			}
27647 			if (nce != NULL) {
27648 				/*
27649 				 * We have to protect nce_res_mp here
27650 				 * from being accessed by other threads
27651 				 * while we change the mblk pointer.
27652 				 * Other functions will also lock the nce when
27653 				 * accessing nce_res_mp.
27654 				 *
27655 				 * The reason we change the mblk pointer
27656 				 * here rather than copying the resolved address
27657 				 * into the template is that, unlike with
27658 				 * ethernet, we have no guarantee that the
27659 				 * resolved address length will be
27660 				 * smaller than or equal to the lla length
27661 				 * with which the template was allocated,
27662 				 * (for ethernet, they're equal)
27663 				 * so we have to use the actual resolved
27664 				 * address mblk - which holds the real
27665 				 * dl_unitdata_req with the resolved address.
27666 				 *
27667 				 * Doing this is the same behavior as was
27668 				 * previously used in the v4 ARP case.
27669 				 */
27670 				mutex_enter(&nce->nce_lock);
27671 				if (nce->nce_res_mp != NULL)
27672 					freemsg(nce->nce_res_mp);
27673 				nce->nce_res_mp = mp1;
27674 				mutex_exit(&nce->nce_lock);
27675 				/*
27676 				 * We do a fastpath probe here because
27677 				 * we have resolved the address without
27678 				 * using Neighbor Discovery.
27679 				 * In the non-XRESOLV v6 case, the fastpath
27680 				 * probe is done right after neighbor
27681 				 * discovery completes.
27682 				 */
27683 				if (nce->nce_res_mp != NULL) {
27684 					int res;
27685 					nce_fastpath_list_add(nce);
27686 					res = ill_fastpath_probe(ill,
27687 					    nce->nce_res_mp);
27688 					if (res != 0 && res != EAGAIN)
27689 						nce_fastpath_list_delete(nce);
27690 				}
27691 
27692 				ire_add_then_send(q, ire, mp);
27693 				/*
27694 				 * Now we have to clean out any packets
27695 				 * that may have been queued on the nce
27696 				 * while it was waiting for address resolution
27697 				 * to complete.
27698 				 */
27699 				mutex_enter(&nce->nce_lock);
27700 				mp1 = nce->nce_qd_mp;
27701 				nce->nce_qd_mp = NULL;
27702 				mutex_exit(&nce->nce_lock);
27703 				while (mp1 != NULL) {
27704 					mblk_t *nxt_mp;
27705 					queue_t *fwdq = NULL;
27706 					ill_t   *inbound_ill;
27707 					uint_t ifindex;
27708 
27709 					nxt_mp = mp1->b_next;
27710 					mp1->b_next = NULL;
27711 					/*
27712 					 * Retrieve ifindex stored in
27713 					 * ip_rput_data_v6()
27714 					 */
27715 					ifindex =
27716 					    (uint_t)(uintptr_t)mp1->b_prev;
27717 					inbound_ill =
27718 					    ill_lookup_on_ifindex(ifindex,
27719 					    B_TRUE, NULL, NULL, NULL,
27720 					    NULL, ipst);
27721 					mp1->b_prev = NULL;
27722 					if (inbound_ill != NULL)
27723 						fwdq = inbound_ill->ill_rq;
27724 
27725 					if (fwdq != NULL) {
27726 						put(fwdq, mp1);
27727 						ill_refrele(inbound_ill);
27728 					} else
27729 						put(WR(ill->ill_rq), mp1);
27730 					mp1 = nxt_mp;
27731 				}
27732 				NCE_REFRELE(nce);
27733 			} else {	/* nce is NULL; clean up */
27734 				ire_delete(ire);
27735 				freemsg(mp);
27736 				freemsg(mp1);
27737 				return;
27738 			}
27739 		} else {
27740 			nce_t *arpce;
27741 			/*
27742 			 * Link layer resolution succeeded. Recompute the
27743 			 * ire_nce.
27744 			 */
27745 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27746 			if ((arpce = ndp_lookup_v4(ill,
27747 			    (ire->ire_gateway_addr != INADDR_ANY ?
27748 			    &ire->ire_gateway_addr : &ire->ire_addr),
27749 			    B_FALSE)) == NULL) {
27750 				freeb(ire->ire_mp);
27751 				freeb(mp1);
27752 				freemsg(mp);
27753 				return;
27754 			}
27755 			mutex_enter(&arpce->nce_lock);
27756 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27757 			if (arpce->nce_state == ND_REACHABLE) {
27758 				/*
27759 				 * Someone resolved this before us;
27760 				 * cleanup the res_mp. Since ire has
27761 				 * not been added yet, the call to ire_add_v4
27762 				 * from ire_add_then_send (when a dup is
27763 				 * detected) will clean up the ire.
27764 				 */
27765 				freeb(mp1);
27766 			} else {
27767 				ASSERT(arpce->nce_res_mp == NULL);
27768 				arpce->nce_res_mp = mp1;
27769 				arpce->nce_state = ND_REACHABLE;
27770 			}
27771 			mutex_exit(&arpce->nce_lock);
27772 			if (ire->ire_marks & IRE_MARK_NOADD) {
27773 				/*
27774 				 * this ire will not be added to the ire
27775 				 * cache table, so we can set the ire_nce
27776 				 * here, as there are no atomicity constraints.
27777 				 */
27778 				ire->ire_nce = arpce;
27779 				/*
27780 				 * We are associating this nce with the ire
27781 				 * so change the nce ref taken in
27782 				 * ndp_lookup_v4() from
27783 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27784 				 */
27785 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27786 			} else {
27787 				NCE_REFRELE(arpce);
27788 			}
27789 			ire_add_then_send(q, ire, mp);
27790 		}
27791 		return;	/* All is well, the packet has been sent. */
27792 	}
27793 	case IRE_ARPRESOLVE_TYPE: {
27794 
27795 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27796 			break;
27797 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27798 		mp->b_cont = NULL;
27799 		/*
27800 		 * First, check to make sure the resolution succeeded.
27801 		 * If it failed, the second mblk will be empty.
27802 		 */
27803 		if (mp1->b_rptr == mp1->b_wptr) {
27804 			/* cleanup  the incomplete ire, free queued packets */
27805 			freemsg(mp); /* fake ire */
27806 			freeb(mp1);  /* dl_unitdata response */
27807 			return;
27808 		}
27809 
27810 		/*
27811 		 * Update any incomplete nce_t found. We search the ctable
27812 		 * and find the nce from the ire->ire_nce because we need
27813 		 * to pass the ire to ip_xmit_v4 later, and can find both
27814 		 * ire and nce in one lookup.
27815 		 */
27816 		fake_ire = (ire_t *)mp->b_rptr;
27817 
27818 		/*
27819 		 * By the time we come back here from ARP the logical outgoing
27820 		 * interface of the incomplete ire we added in ire_forward()
27821 		 * could have disappeared, causing the incomplete ire to also
27822 		 * disappear.  So we need to retreive the proper ipif for the
27823 		 * ire before looking in ctable.  In the case of IPMP, the
27824 		 * ipif may be on the IPMP ill, so look it up based on the
27825 		 * ire_ipif_ifindex we stashed back in ire_init_common().
27826 		 * Then, we can verify that ire_ipif_seqid still exists.
27827 		 */
27828 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27829 		    NULL, NULL, NULL, NULL, ipst);
27830 		if (ill == NULL) {
27831 			ip1dbg(("ill for incomplete ire vanished\n"));
27832 			freemsg(mp); /* fake ire */
27833 			freeb(mp1);  /* dl_unitdata response */
27834 			return;
27835 		}
27836 
27837 		/* Get the outgoing ipif */
27838 		mutex_enter(&ill->ill_lock);
27839 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27840 		if (ipif == NULL) {
27841 			mutex_exit(&ill->ill_lock);
27842 			ill_refrele(ill);
27843 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27844 			freemsg(mp); /* fake_ire */
27845 			freeb(mp1);  /* dl_unitdata response */
27846 			return;
27847 		}
27848 
27849 		ipif_refhold_locked(ipif);
27850 		mutex_exit(&ill->ill_lock);
27851 		ill_refrele(ill);
27852 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27853 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27854 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27855 		ipif_refrele(ipif);
27856 		if (ire == NULL) {
27857 			/*
27858 			 * no ire was found; check if there is an nce
27859 			 * for this lookup; if it has no ire's pointing at it
27860 			 * cleanup.
27861 			 */
27862 			if ((nce = ndp_lookup_v4(q->q_ptr,
27863 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27864 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27865 			    B_FALSE)) != NULL) {
27866 				/*
27867 				 * cleanup:
27868 				 * We check for refcnt 2 (one for the nce
27869 				 * hash list + 1 for the ref taken by
27870 				 * ndp_lookup_v4) to check that there are
27871 				 * no ire's pointing at the nce.
27872 				 */
27873 				if (nce->nce_refcnt == 2)
27874 					ndp_delete(nce);
27875 				NCE_REFRELE(nce);
27876 			}
27877 			freeb(mp1);  /* dl_unitdata response */
27878 			freemsg(mp); /* fake ire */
27879 			return;
27880 		}
27881 
27882 		nce = ire->ire_nce;
27883 		DTRACE_PROBE2(ire__arpresolve__type,
27884 		    ire_t *, ire, nce_t *, nce);
27885 		mutex_enter(&nce->nce_lock);
27886 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27887 		if (nce->nce_state == ND_REACHABLE) {
27888 			/*
27889 			 * Someone resolved this before us;
27890 			 * our response is not needed any more.
27891 			 */
27892 			mutex_exit(&nce->nce_lock);
27893 			freeb(mp1);  /* dl_unitdata response */
27894 		} else {
27895 			ASSERT(nce->nce_res_mp == NULL);
27896 			nce->nce_res_mp = mp1;
27897 			nce->nce_state = ND_REACHABLE;
27898 			mutex_exit(&nce->nce_lock);
27899 			nce_fastpath(nce);
27900 		}
27901 		/*
27902 		 * The cached nce_t has been updated to be reachable;
27903 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27904 		 */
27905 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27906 		freemsg(mp);
27907 		/*
27908 		 * send out queued packets.
27909 		 */
27910 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
27911 
27912 		IRE_REFRELE(ire);
27913 		return;
27914 	}
27915 	default:
27916 		break;
27917 	}
27918 	if (q->q_next) {
27919 		putnext(q, mp);
27920 	} else
27921 		freemsg(mp);
27922 	return;
27923 
27924 protonak:
27925 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27926 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27927 		qreply(q, mp);
27928 }
27929 
27930 /*
27931  * Process IP options in an outbound packet.  Modify the destination if there
27932  * is a source route option.
27933  * Returns non-zero if something fails in which case an ICMP error has been
27934  * sent and mp freed.
27935  */
27936 static int
27937 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27938     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27939 {
27940 	ipoptp_t	opts;
27941 	uchar_t		*opt;
27942 	uint8_t		optval;
27943 	uint8_t		optlen;
27944 	ipaddr_t	dst;
27945 	intptr_t	code = 0;
27946 	mblk_t		*mp;
27947 	ire_t		*ire = NULL;
27948 
27949 	ip2dbg(("ip_wput_options\n"));
27950 	mp = ipsec_mp;
27951 	if (mctl_present) {
27952 		mp = ipsec_mp->b_cont;
27953 	}
27954 
27955 	dst = ipha->ipha_dst;
27956 	for (optval = ipoptp_first(&opts, ipha);
27957 	    optval != IPOPT_EOL;
27958 	    optval = ipoptp_next(&opts)) {
27959 		opt = opts.ipoptp_cur;
27960 		optlen = opts.ipoptp_len;
27961 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27962 		    optval, optlen));
27963 		switch (optval) {
27964 			uint32_t off;
27965 		case IPOPT_SSRR:
27966 		case IPOPT_LSRR:
27967 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27968 				ip1dbg((
27969 				    "ip_wput_options: bad option offset\n"));
27970 				code = (char *)&opt[IPOPT_OLEN] -
27971 				    (char *)ipha;
27972 				goto param_prob;
27973 			}
27974 			off = opt[IPOPT_OFFSET];
27975 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27976 			    ntohl(dst)));
27977 			/*
27978 			 * For strict: verify that dst is directly
27979 			 * reachable.
27980 			 */
27981 			if (optval == IPOPT_SSRR) {
27982 				ire = ire_ftable_lookup(dst, 0, 0,
27983 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27984 				    msg_getlabel(mp),
27985 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27986 				if (ire == NULL) {
27987 					ip1dbg(("ip_wput_options: SSRR not"
27988 					    " directly reachable: 0x%x\n",
27989 					    ntohl(dst)));
27990 					goto bad_src_route;
27991 				}
27992 				ire_refrele(ire);
27993 			}
27994 			break;
27995 		case IPOPT_RR:
27996 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27997 				ip1dbg((
27998 				    "ip_wput_options: bad option offset\n"));
27999 				code = (char *)&opt[IPOPT_OLEN] -
28000 				    (char *)ipha;
28001 				goto param_prob;
28002 			}
28003 			break;
28004 		case IPOPT_TS:
28005 			/*
28006 			 * Verify that length >=5 and that there is either
28007 			 * room for another timestamp or that the overflow
28008 			 * counter is not maxed out.
28009 			 */
28010 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28011 			if (optlen < IPOPT_MINLEN_IT) {
28012 				goto param_prob;
28013 			}
28014 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28015 				ip1dbg((
28016 				    "ip_wput_options: bad option offset\n"));
28017 				code = (char *)&opt[IPOPT_OFFSET] -
28018 				    (char *)ipha;
28019 				goto param_prob;
28020 			}
28021 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28022 			case IPOPT_TS_TSONLY:
28023 				off = IPOPT_TS_TIMELEN;
28024 				break;
28025 			case IPOPT_TS_TSANDADDR:
28026 			case IPOPT_TS_PRESPEC:
28027 			case IPOPT_TS_PRESPEC_RFC791:
28028 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28029 				break;
28030 			default:
28031 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28032 				    (char *)ipha;
28033 				goto param_prob;
28034 			}
28035 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28036 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28037 				/*
28038 				 * No room and the overflow counter is 15
28039 				 * already.
28040 				 */
28041 				goto param_prob;
28042 			}
28043 			break;
28044 		}
28045 	}
28046 
28047 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28048 		return (0);
28049 
28050 	ip1dbg(("ip_wput_options: error processing IP options."));
28051 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28052 
28053 param_prob:
28054 	/*
28055 	 * Since ip_wput() isn't close to finished, we fill
28056 	 * in enough of the header for credible error reporting.
28057 	 */
28058 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28059 		/* Failed */
28060 		freemsg(ipsec_mp);
28061 		return (-1);
28062 	}
28063 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28064 	return (-1);
28065 
28066 bad_src_route:
28067 	/*
28068 	 * Since ip_wput() isn't close to finished, we fill
28069 	 * in enough of the header for credible error reporting.
28070 	 */
28071 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28072 		/* Failed */
28073 		freemsg(ipsec_mp);
28074 		return (-1);
28075 	}
28076 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28077 	return (-1);
28078 }
28079 
28080 /*
28081  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28082  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28083  * thru /etc/system.
28084  */
28085 #define	CONN_MAXDRAINCNT	64
28086 
28087 static void
28088 conn_drain_init(ip_stack_t *ipst)
28089 {
28090 	int i, j;
28091 	idl_tx_list_t *itl_tx;
28092 
28093 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28094 
28095 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28096 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28097 		/*
28098 		 * Default value of the number of drainers is the
28099 		 * number of cpus, subject to maximum of 8 drainers.
28100 		 */
28101 		if (boot_max_ncpus != -1)
28102 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28103 		else
28104 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28105 	}
28106 
28107 	ipst->ips_idl_tx_list =
28108 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
28109 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28110 		itl_tx =  &ipst->ips_idl_tx_list[i];
28111 		itl_tx->txl_drain_list =
28112 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28113 		    sizeof (idl_t), KM_SLEEP);
28114 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
28115 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
28116 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
28117 			    MUTEX_DEFAULT, NULL);
28118 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
28119 		}
28120 	}
28121 }
28122 
28123 static void
28124 conn_drain_fini(ip_stack_t *ipst)
28125 {
28126 	int i;
28127 	idl_tx_list_t *itl_tx;
28128 
28129 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
28130 		itl_tx =  &ipst->ips_idl_tx_list[i];
28131 		kmem_free(itl_tx->txl_drain_list,
28132 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28133 	}
28134 	kmem_free(ipst->ips_idl_tx_list,
28135 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
28136 	ipst->ips_idl_tx_list = NULL;
28137 }
28138 
28139 /*
28140  * Note: For an overview of how flowcontrol is handled in IP please see the
28141  * IP Flowcontrol notes at the top of this file.
28142  *
28143  * Flow control has blocked us from proceeding. Insert the given conn in one
28144  * of the conn drain lists. These conn wq's will be qenabled later on when
28145  * STREAMS flow control does a backenable. conn_walk_drain will enable
28146  * the first conn in each of these drain lists. Each of these qenabled conns
28147  * in turn enables the next in the list, after it runs, or when it closes,
28148  * thus sustaining the drain process.
28149  */
28150 void
28151 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
28152 {
28153 	idl_t	*idl = tx_list->txl_drain_list;
28154 	uint_t	index;
28155 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28156 
28157 	mutex_enter(&connp->conn_lock);
28158 	if (connp->conn_state_flags & CONN_CLOSING) {
28159 		/*
28160 		 * The conn is closing as a result of which CONN_CLOSING
28161 		 * is set. Return.
28162 		 */
28163 		mutex_exit(&connp->conn_lock);
28164 		return;
28165 	} else if (connp->conn_idl == NULL) {
28166 		/*
28167 		 * Assign the next drain list round robin. We dont' use
28168 		 * a lock, and thus it may not be strictly round robin.
28169 		 * Atomicity of load/stores is enough to make sure that
28170 		 * conn_drain_list_index is always within bounds.
28171 		 */
28172 		index = tx_list->txl_drain_index;
28173 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28174 		connp->conn_idl = &tx_list->txl_drain_list[index];
28175 		index++;
28176 		if (index == ipst->ips_conn_drain_list_cnt)
28177 			index = 0;
28178 		tx_list->txl_drain_index = index;
28179 	}
28180 	mutex_exit(&connp->conn_lock);
28181 
28182 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28183 	if ((connp->conn_drain_prev != NULL) ||
28184 	    (connp->conn_state_flags & CONN_CLOSING)) {
28185 		/*
28186 		 * The conn is already in the drain list, OR
28187 		 * the conn is closing. We need to check again for
28188 		 * the closing case again since close can happen
28189 		 * after we drop the conn_lock, and before we
28190 		 * acquire the CONN_DRAIN_LIST_LOCK.
28191 		 */
28192 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28193 		return;
28194 	} else {
28195 		idl = connp->conn_idl;
28196 	}
28197 
28198 	/*
28199 	 * The conn is not in the drain list. Insert it at the
28200 	 * tail of the drain list. The drain list is circular
28201 	 * and doubly linked. idl_conn points to the 1st element
28202 	 * in the list.
28203 	 */
28204 	if (idl->idl_conn == NULL) {
28205 		idl->idl_conn = connp;
28206 		connp->conn_drain_next = connp;
28207 		connp->conn_drain_prev = connp;
28208 	} else {
28209 		conn_t *head = idl->idl_conn;
28210 
28211 		connp->conn_drain_next = head;
28212 		connp->conn_drain_prev = head->conn_drain_prev;
28213 		head->conn_drain_prev->conn_drain_next = connp;
28214 		head->conn_drain_prev = connp;
28215 	}
28216 	/*
28217 	 * For non streams based sockets assert flow control.
28218 	 */
28219 	if (IPCL_IS_NONSTR(connp)) {
28220 		DTRACE_PROBE1(su__txq__full, conn_t *, connp);
28221 		(*connp->conn_upcalls->su_txq_full)
28222 		    (connp->conn_upper_handle, B_TRUE);
28223 	} else {
28224 		conn_setqfull(connp);
28225 		noenable(connp->conn_wq);
28226 	}
28227 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28228 }
28229 
28230 /*
28231  * This conn is closing, and we are called from ip_close. OR
28232  * This conn has been serviced by ip_wsrv, and we need to do the tail
28233  * processing.
28234  * If this conn is part of the drain list, we may need to sustain the drain
28235  * process by qenabling the next conn in the drain list. We may also need to
28236  * remove this conn from the list, if it is done.
28237  */
28238 static void
28239 conn_drain_tail(conn_t *connp, boolean_t closing)
28240 {
28241 	idl_t *idl;
28242 
28243 	/*
28244 	 * connp->conn_idl is stable at this point, and no lock is needed
28245 	 * to check it. If we are called from ip_close, close has already
28246 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28247 	 * called us only because conn_idl is non-null. If we are called thru
28248 	 * service, conn_idl could be null, but it cannot change because
28249 	 * service is single-threaded per queue, and there cannot be another
28250 	 * instance of service trying to call conn_drain_insert on this conn
28251 	 * now.
28252 	 */
28253 	ASSERT(!closing || (connp->conn_idl != NULL));
28254 
28255 	/*
28256 	 * If connp->conn_idl is null, the conn has not been inserted into any
28257 	 * drain list even once since creation of the conn. Just return.
28258 	 */
28259 	if (connp->conn_idl == NULL)
28260 		return;
28261 
28262 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28263 
28264 	if (connp->conn_drain_prev == NULL) {
28265 		/* This conn is currently not in the drain list.  */
28266 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28267 		return;
28268 	}
28269 	idl = connp->conn_idl;
28270 	if (idl->idl_conn_draining == connp) {
28271 		/*
28272 		 * This conn is the current drainer. If this is the last conn
28273 		 * in the drain list, we need to do more checks, in the 'if'
28274 		 * below. Otherwwise we need to just qenable the next conn,
28275 		 * to sustain the draining, and is handled in the 'else'
28276 		 * below.
28277 		 */
28278 		if (connp->conn_drain_next == idl->idl_conn) {
28279 			/*
28280 			 * This conn is the last in this list. This round
28281 			 * of draining is complete. If idl_repeat is set,
28282 			 * it means another flow enabling has happened from
28283 			 * the driver/streams and we need to another round
28284 			 * of draining.
28285 			 * If there are more than 2 conns in the drain list,
28286 			 * do a left rotate by 1, so that all conns except the
28287 			 * conn at the head move towards the head by 1, and the
28288 			 * the conn at the head goes to the tail. This attempts
28289 			 * a more even share for all queues that are being
28290 			 * drained.
28291 			 */
28292 			if ((connp->conn_drain_next != connp) &&
28293 			    (idl->idl_conn->conn_drain_next != connp)) {
28294 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28295 			}
28296 			if (idl->idl_repeat) {
28297 				qenable(idl->idl_conn->conn_wq);
28298 				idl->idl_conn_draining = idl->idl_conn;
28299 				idl->idl_repeat = 0;
28300 			} else {
28301 				idl->idl_conn_draining = NULL;
28302 			}
28303 		} else {
28304 			/*
28305 			 * If the next queue that we are now qenable'ing,
28306 			 * is closing, it will remove itself from this list
28307 			 * and qenable the subsequent queue in ip_close().
28308 			 * Serialization is acheived thru idl_lock.
28309 			 */
28310 			qenable(connp->conn_drain_next->conn_wq);
28311 			idl->idl_conn_draining = connp->conn_drain_next;
28312 		}
28313 	}
28314 	if (!connp->conn_did_putbq || closing) {
28315 		/*
28316 		 * Remove ourself from the drain list, if we did not do
28317 		 * a putbq, or if the conn is closing.
28318 		 * Note: It is possible that q->q_first is non-null. It means
28319 		 * that these messages landed after we did a enableok() in
28320 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28321 		 * service them.
28322 		 */
28323 		if (connp->conn_drain_next == connp) {
28324 			/* Singleton in the list */
28325 			ASSERT(connp->conn_drain_prev == connp);
28326 			idl->idl_conn = NULL;
28327 			idl->idl_conn_draining = NULL;
28328 		} else {
28329 			connp->conn_drain_prev->conn_drain_next =
28330 			    connp->conn_drain_next;
28331 			connp->conn_drain_next->conn_drain_prev =
28332 			    connp->conn_drain_prev;
28333 			if (idl->idl_conn == connp)
28334 				idl->idl_conn = connp->conn_drain_next;
28335 			ASSERT(idl->idl_conn_draining != connp);
28336 
28337 		}
28338 		connp->conn_drain_next = NULL;
28339 		connp->conn_drain_prev = NULL;
28340 
28341 		/*
28342 		 * For non streams based sockets open up flow control.
28343 		 */
28344 		if (IPCL_IS_NONSTR(connp)) {
28345 			(*connp->conn_upcalls->su_txq_full)
28346 			    (connp->conn_upper_handle, B_FALSE);
28347 		} else {
28348 			conn_clrqfull(connp);
28349 			enableok(connp->conn_wq);
28350 		}
28351 	}
28352 
28353 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28354 }
28355 
28356 /*
28357  * Write service routine. Shared perimeter entry point.
28358  * ip_wsrv can be called in any of the following ways.
28359  * 1. The device queue's messages has fallen below the low water mark
28360  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28361  *    the drain lists and backenable the first conn in each list.
28362  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28363  *    qenabled non-tcp upper layers. We start dequeing messages and call
28364  *    ip_wput for each message.
28365  */
28366 
28367 void
28368 ip_wsrv(queue_t *q)
28369 {
28370 	conn_t	*connp;
28371 	ill_t	*ill;
28372 	mblk_t	*mp;
28373 
28374 	if (q->q_next) {
28375 		ill = (ill_t *)q->q_ptr;
28376 		if (ill->ill_state_flags == 0) {
28377 			ip_stack_t *ipst = ill->ill_ipst;
28378 
28379 			/*
28380 			 * The device flow control has opened up.
28381 			 * Walk through conn drain lists and qenable the
28382 			 * first conn in each list. This makes sense only
28383 			 * if the stream is fully plumbed and setup.
28384 			 * Hence the if check above.
28385 			 */
28386 			ip1dbg(("ip_wsrv: walking\n"));
28387 			conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
28388 		}
28389 		return;
28390 	}
28391 
28392 	connp = Q_TO_CONN(q);
28393 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28394 
28395 	/*
28396 	 * 1. Set conn_draining flag to signal that service is active.
28397 	 *
28398 	 * 2. ip_output determines whether it has been called from service,
28399 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28400 	 *    has been called from service.
28401 	 *
28402 	 * 3. Message ordering is preserved by the following logic.
28403 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28404 	 *    the message at the tail, if conn_draining is set (i.e. service
28405 	 *    is running) or if q->q_first is non-null.
28406 	 *
28407 	 *    ii. If ip_output is called from service, and if ip_output cannot
28408 	 *    putnext due to flow control, it does a putbq.
28409 	 *
28410 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28411 	 *    (causing an infinite loop).
28412 	 */
28413 	ASSERT(!connp->conn_did_putbq);
28414 
28415 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28416 		connp->conn_draining = 1;
28417 		noenable(q);
28418 		while ((mp = getq(q)) != NULL) {
28419 			ASSERT(CONN_Q(q));
28420 
28421 			DTRACE_PROBE1(ip__wsrv__ip__output, conn_t *, connp);
28422 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28423 			if (connp->conn_did_putbq) {
28424 				/* ip_wput did a putbq */
28425 				break;
28426 			}
28427 		}
28428 		/*
28429 		 * At this point, a thread coming down from top, calling
28430 		 * ip_wput, may end up queueing the message. We have not yet
28431 		 * enabled the queue, so ip_wsrv won't be called again.
28432 		 * To avoid this race, check q->q_first again (in the loop)
28433 		 * If the other thread queued the message before we call
28434 		 * enableok(), we will catch it in the q->q_first check.
28435 		 * If the other thread queues the message after we call
28436 		 * enableok(), ip_wsrv will be called again by STREAMS.
28437 		 */
28438 		connp->conn_draining = 0;
28439 		enableok(q);
28440 	}
28441 
28442 	/* Enable the next conn for draining */
28443 	conn_drain_tail(connp, B_FALSE);
28444 
28445 	/*
28446 	 * conn_direct_blocked is used to indicate blocked
28447 	 * condition for direct path (ILL_DIRECT_CAPABLE()).
28448 	 * This is the only place where it is set without
28449 	 * checking for ILL_DIRECT_CAPABLE() and setting it
28450 	 * to 0 is ok even if it is not ILL_DIRECT_CAPABLE().
28451 	 */
28452 	if (!connp->conn_did_putbq && connp->conn_direct_blocked) {
28453 		DTRACE_PROBE1(ip__wsrv__direct__blocked, conn_t *, connp);
28454 		connp->conn_direct_blocked = B_FALSE;
28455 	}
28456 
28457 	connp->conn_did_putbq = 0;
28458 }
28459 
28460 /*
28461  * Callback to disable flow control in IP.
28462  *
28463  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28464  * is enabled.
28465  *
28466  * When MAC_TX() is not able to send any more packets, dld sets its queue
28467  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28468  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28469  * function and wakes up corresponding mac worker threads, which in turn
28470  * calls this callback function, and disables flow control.
28471  */
28472 void
28473 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
28474 {
28475 	ill_t *ill = (ill_t *)arg;
28476 	ip_stack_t *ipst = ill->ill_ipst;
28477 	idl_tx_list_t *idl_txl;
28478 
28479 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
28480 	mutex_enter(&idl_txl->txl_lock);
28481 	/* add code to to set a flag to indicate idl_txl is enabled */
28482 	conn_walk_drain(ipst, idl_txl);
28483 	mutex_exit(&idl_txl->txl_lock);
28484 }
28485 
28486 /*
28487  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28488  * of conns that need to be drained, check if drain is already in progress.
28489  * If so set the idl_repeat bit, indicating that the last conn in the list
28490  * needs to reinitiate the drain once again, for the list. If drain is not
28491  * in progress for the list, initiate the draining, by qenabling the 1st
28492  * conn in the list. The drain is self-sustaining, each qenabled conn will
28493  * in turn qenable the next conn, when it is done/blocked/closing.
28494  */
28495 static void
28496 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
28497 {
28498 	int i;
28499 	idl_t *idl;
28500 
28501 	IP_STAT(ipst, ip_conn_walk_drain);
28502 
28503 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28504 		idl = &tx_list->txl_drain_list[i];
28505 		mutex_enter(&idl->idl_lock);
28506 		if (idl->idl_conn == NULL) {
28507 			mutex_exit(&idl->idl_lock);
28508 			continue;
28509 		}
28510 		/*
28511 		 * If this list is not being drained currently by
28512 		 * an ip_wsrv thread, start the process.
28513 		 */
28514 		if (idl->idl_conn_draining == NULL) {
28515 			ASSERT(idl->idl_repeat == 0);
28516 			qenable(idl->idl_conn->conn_wq);
28517 			idl->idl_conn_draining = idl->idl_conn;
28518 		} else {
28519 			idl->idl_repeat = 1;
28520 		}
28521 		mutex_exit(&idl->idl_lock);
28522 	}
28523 }
28524 
28525 /*
28526  * Determine if the ill and multicast aspects of that packets
28527  * "matches" the conn.
28528  */
28529 boolean_t
28530 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28531     zoneid_t zoneid)
28532 {
28533 	ill_t *bound_ill;
28534 	boolean_t found;
28535 	ipif_t *ipif;
28536 	ire_t *ire;
28537 	ipaddr_t dst, src;
28538 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28539 
28540 	dst = ipha->ipha_dst;
28541 	src = ipha->ipha_src;
28542 
28543 	/*
28544 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28545 	 * unicast, broadcast and multicast reception to
28546 	 * conn_incoming_ill. conn_wantpacket itself is called
28547 	 * only for BROADCAST and multicast.
28548 	 */
28549 	bound_ill = connp->conn_incoming_ill;
28550 	if (bound_ill != NULL) {
28551 		if (IS_IPMP(bound_ill)) {
28552 			if (bound_ill->ill_grp != ill->ill_grp)
28553 				return (B_FALSE);
28554 		} else {
28555 			if (bound_ill != ill)
28556 				return (B_FALSE);
28557 		}
28558 	}
28559 
28560 	if (!CLASSD(dst)) {
28561 		if (IPCL_ZONE_MATCH(connp, zoneid))
28562 			return (B_TRUE);
28563 		/*
28564 		 * The conn is in a different zone; we need to check that this
28565 		 * broadcast address is configured in the application's zone.
28566 		 */
28567 		ipif = ipif_get_next_ipif(NULL, ill);
28568 		if (ipif == NULL)
28569 			return (B_FALSE);
28570 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28571 		    connp->conn_zoneid, NULL,
28572 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL), ipst);
28573 		ipif_refrele(ipif);
28574 		if (ire != NULL) {
28575 			ire_refrele(ire);
28576 			return (B_TRUE);
28577 		} else {
28578 			return (B_FALSE);
28579 		}
28580 	}
28581 
28582 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28583 	    connp->conn_zoneid == zoneid) {
28584 		/*
28585 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28586 		 * disabled, therefore we don't dispatch the multicast packet to
28587 		 * the sending zone.
28588 		 */
28589 		return (B_FALSE);
28590 	}
28591 
28592 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28593 		/*
28594 		 * Multicast packet on the loopback interface: we only match
28595 		 * conns who joined the group in the specified zone.
28596 		 */
28597 		return (B_FALSE);
28598 	}
28599 
28600 	if (connp->conn_multi_router) {
28601 		/* multicast packet and multicast router socket: send up */
28602 		return (B_TRUE);
28603 	}
28604 
28605 	mutex_enter(&connp->conn_lock);
28606 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28607 	mutex_exit(&connp->conn_lock);
28608 	return (found);
28609 }
28610 
28611 static void
28612 conn_setqfull(conn_t *connp)
28613 {
28614 	queue_t *q = connp->conn_wq;
28615 
28616 	if (!(q->q_flag & QFULL)) {
28617 		mutex_enter(QLOCK(q));
28618 		if (!(q->q_flag & QFULL)) {
28619 			/* still need to set QFULL */
28620 			q->q_flag |= QFULL;
28621 			mutex_exit(QLOCK(q));
28622 		} else {
28623 			mutex_exit(QLOCK(q));
28624 		}
28625 	}
28626 }
28627 
28628 static void
28629 conn_clrqfull(conn_t *connp)
28630 {
28631 	queue_t *q = connp->conn_wq;
28632 
28633 	if (q->q_flag & QFULL) {
28634 		mutex_enter(QLOCK(q));
28635 		if (q->q_flag & QFULL) {
28636 			q->q_flag &= ~QFULL;
28637 			mutex_exit(QLOCK(q));
28638 			if (q->q_flag & QWANTW)
28639 				qbackenable(q, 0);
28640 		} else {
28641 			mutex_exit(QLOCK(q));
28642 		}
28643 	}
28644 }
28645 
28646 /*
28647  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28648  */
28649 /* ARGSUSED */
28650 static void
28651 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28652 {
28653 	ill_t *ill = (ill_t *)q->q_ptr;
28654 	mblk_t	*mp1, *mp2;
28655 	ipif_t  *ipif;
28656 	int err = 0;
28657 	conn_t *connp = NULL;
28658 	ipsq_t	*ipsq;
28659 	arc_t	*arc;
28660 
28661 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28662 
28663 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28664 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28665 
28666 	ASSERT(IAM_WRITER_ILL(ill));
28667 	mp2 = mp->b_cont;
28668 	mp->b_cont = NULL;
28669 
28670 	/*
28671 	 * We have now received the arp bringup completion message
28672 	 * from ARP. Mark the arp bringup as done. Also if the arp
28673 	 * stream has already started closing, send up the AR_ARP_CLOSING
28674 	 * ack now since ARP is waiting in close for this ack.
28675 	 */
28676 	mutex_enter(&ill->ill_lock);
28677 	ill->ill_arp_bringup_pending = 0;
28678 	if (ill->ill_arp_closing) {
28679 		mutex_exit(&ill->ill_lock);
28680 		/* Let's reuse the mp for sending the ack */
28681 		arc = (arc_t *)mp->b_rptr;
28682 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28683 		arc->arc_cmd = AR_ARP_CLOSING;
28684 		qreply(q, mp);
28685 	} else {
28686 		mutex_exit(&ill->ill_lock);
28687 		freeb(mp);
28688 	}
28689 
28690 	ipsq = ill->ill_phyint->phyint_ipsq;
28691 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
28692 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28693 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28694 	if (mp1 == NULL) {
28695 		/* bringup was aborted by the user */
28696 		freemsg(mp2);
28697 		return;
28698 	}
28699 
28700 	/*
28701 	 * If an IOCTL is waiting on this (ipx_current_ioctl != 0), then we
28702 	 * must have an associated conn_t.  Otherwise, we're bringing this
28703 	 * interface back up as part of handling an asynchronous event (e.g.,
28704 	 * physical address change).
28705 	 */
28706 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0) {
28707 		ASSERT(connp != NULL);
28708 		q = CONNP_TO_WQ(connp);
28709 	} else {
28710 		ASSERT(connp == NULL);
28711 		q = ill->ill_rq;
28712 	}
28713 
28714 	/*
28715 	 * If the DL_BIND_REQ fails, it is noted
28716 	 * in arc_name_offset.
28717 	 */
28718 	err = *((int *)mp2->b_rptr);
28719 	if (err == 0) {
28720 		if (ipif->ipif_isv6) {
28721 			if ((err = ipif_up_done_v6(ipif)) != 0)
28722 				ip0dbg(("ip_arp_done: init failed\n"));
28723 		} else {
28724 			if ((err = ipif_up_done(ipif)) != 0)
28725 				ip0dbg(("ip_arp_done: init failed\n"));
28726 		}
28727 	} else {
28728 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28729 	}
28730 
28731 	freemsg(mp2);
28732 
28733 	if ((err == 0) && (ill->ill_up_ipifs)) {
28734 		err = ill_up_ipifs(ill, q, mp1);
28735 		if (err == EINPROGRESS)
28736 			return;
28737 	}
28738 
28739 	/*
28740 	 * If we have a moved ipif to bring up, and everything has succeeded
28741 	 * to this point, bring it up on the IPMP ill.  Otherwise, leave it
28742 	 * down -- the admin can try to bring it up by hand if need be.
28743 	 */
28744 	if (ill->ill_move_ipif != NULL) {
28745 		ipif = ill->ill_move_ipif;
28746 		ill->ill_move_ipif = NULL;
28747 		if (err == 0) {
28748 			err = ipif_up(ipif, q, mp1);
28749 			if (err == EINPROGRESS)
28750 				return;
28751 		}
28752 	}
28753 
28754 	/*
28755 	 * The operation must complete without EINPROGRESS since
28756 	 * ipsq_pending_mp_get() has removed the mblk.  Otherwise, the
28757 	 * operation will be stuck forever in the ipsq.
28758 	 */
28759 	ASSERT(err != EINPROGRESS);
28760 	if (ipsq->ipsq_xop->ipx_current_ioctl != 0)
28761 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28762 	else
28763 		ipsq_current_finish(ipsq);
28764 }
28765 
28766 /* Allocate the private structure */
28767 static int
28768 ip_priv_alloc(void **bufp)
28769 {
28770 	void	*buf;
28771 
28772 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28773 		return (ENOMEM);
28774 
28775 	*bufp = buf;
28776 	return (0);
28777 }
28778 
28779 /* Function to delete the private structure */
28780 void
28781 ip_priv_free(void *buf)
28782 {
28783 	ASSERT(buf != NULL);
28784 	kmem_free(buf, sizeof (ip_priv_t));
28785 }
28786 
28787 /*
28788  * The entry point for IPPF processing.
28789  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28790  * routine just returns.
28791  *
28792  * When called, ip_process generates an ipp_packet_t structure
28793  * which holds the state information for this packet and invokes the
28794  * the classifier (via ipp_packet_process). The classification, depending on
28795  * configured filters, results in a list of actions for this packet. Invoking
28796  * an action may cause the packet to be dropped, in which case the resulting
28797  * mblk (*mpp) is NULL. proc indicates the callout position for
28798  * this packet and ill_index is the interface this packet on or will leave
28799  * on (inbound and outbound resp.).
28800  */
28801 void
28802 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28803 {
28804 	mblk_t		*mp;
28805 	ip_priv_t	*priv;
28806 	ipp_action_id_t	aid;
28807 	int		rc = 0;
28808 	ipp_packet_t	*pp;
28809 #define	IP_CLASS	"ip"
28810 
28811 	/* If the classifier is not loaded, return  */
28812 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28813 		return;
28814 	}
28815 
28816 	mp = *mpp;
28817 	ASSERT(mp != NULL);
28818 
28819 	/* Allocate the packet structure */
28820 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28821 	if (rc != 0) {
28822 		*mpp = NULL;
28823 		freemsg(mp);
28824 		return;
28825 	}
28826 
28827 	/* Allocate the private structure */
28828 	rc = ip_priv_alloc((void **)&priv);
28829 	if (rc != 0) {
28830 		*mpp = NULL;
28831 		freemsg(mp);
28832 		ipp_packet_free(pp);
28833 		return;
28834 	}
28835 	priv->proc = proc;
28836 	priv->ill_index = ill_index;
28837 	ipp_packet_set_private(pp, priv, ip_priv_free);
28838 	ipp_packet_set_data(pp, mp);
28839 
28840 	/* Invoke the classifier */
28841 	rc = ipp_packet_process(&pp);
28842 	if (pp != NULL) {
28843 		mp = ipp_packet_get_data(pp);
28844 		ipp_packet_free(pp);
28845 		if (rc != 0) {
28846 			freemsg(mp);
28847 			*mpp = NULL;
28848 		}
28849 	} else {
28850 		*mpp = NULL;
28851 	}
28852 #undef	IP_CLASS
28853 }
28854 
28855 /*
28856  * Propagate a multicast group membership operation (add/drop) on
28857  * all the interfaces crossed by the related multirt routes.
28858  * The call is considered successful if the operation succeeds
28859  * on at least one interface.
28860  */
28861 static int
28862 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28863     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28864     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28865     mblk_t *first_mp)
28866 {
28867 	ire_t		*ire_gw;
28868 	irb_t		*irb;
28869 	int		error = 0;
28870 	opt_restart_t	*or;
28871 	ip_stack_t	*ipst = ire->ire_ipst;
28872 
28873 	irb = ire->ire_bucket;
28874 	ASSERT(irb != NULL);
28875 
28876 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28877 
28878 	or = (opt_restart_t *)first_mp->b_rptr;
28879 	IRB_REFHOLD(irb);
28880 	for (; ire != NULL; ire = ire->ire_next) {
28881 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28882 			continue;
28883 		if (ire->ire_addr != group)
28884 			continue;
28885 
28886 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28887 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28888 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28889 		/* No resolver exists for the gateway; skip this ire. */
28890 		if (ire_gw == NULL)
28891 			continue;
28892 
28893 		/*
28894 		 * This function can return EINPROGRESS. If so the operation
28895 		 * will be restarted from ip_restart_optmgmt which will
28896 		 * call ip_opt_set and option processing will restart for
28897 		 * this option. So we may end up calling 'fn' more than once.
28898 		 * This requires that 'fn' is idempotent except for the
28899 		 * return value. The operation is considered a success if
28900 		 * it succeeds at least once on any one interface.
28901 		 */
28902 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28903 		    NULL, fmode, src, first_mp);
28904 		if (error == 0)
28905 			or->or_private = CGTP_MCAST_SUCCESS;
28906 
28907 		if (ip_debug > 0) {
28908 			ulong_t	off;
28909 			char	*ksym;
28910 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28911 			ip2dbg(("ip_multirt_apply_membership: "
28912 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28913 			    "error %d [success %u]\n",
28914 			    ksym ? ksym : "?",
28915 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28916 			    error, or->or_private));
28917 		}
28918 
28919 		ire_refrele(ire_gw);
28920 		if (error == EINPROGRESS) {
28921 			IRB_REFRELE(irb);
28922 			return (error);
28923 		}
28924 	}
28925 	IRB_REFRELE(irb);
28926 	/*
28927 	 * Consider the call as successful if we succeeded on at least
28928 	 * one interface. Otherwise, return the last encountered error.
28929 	 */
28930 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28931 }
28932 
28933 /*
28934  * Issue a warning regarding a route crossing an interface with an
28935  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28936  * amount of time is logged.
28937  */
28938 static void
28939 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28940 {
28941 	hrtime_t	current = gethrtime();
28942 	char		buf[INET_ADDRSTRLEN];
28943 	ip_stack_t	*ipst = ire->ire_ipst;
28944 
28945 	/* Convert interval in ms to hrtime in ns */
28946 	if (ipst->ips_multirt_bad_mtu_last_time +
28947 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28948 	    current) {
28949 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28950 		    "to %s, incorrect MTU %u (expected %u)\n",
28951 		    ip_dot_addr(ire->ire_addr, buf),
28952 		    ire->ire_max_frag, max_frag);
28953 
28954 		ipst->ips_multirt_bad_mtu_last_time = current;
28955 	}
28956 }
28957 
28958 /*
28959  * Get the CGTP (multirouting) filtering status.
28960  * If 0, the CGTP hooks are transparent.
28961  */
28962 /* ARGSUSED */
28963 static int
28964 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28965 {
28966 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28967 
28968 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28969 	return (0);
28970 }
28971 
28972 /*
28973  * Set the CGTP (multirouting) filtering status.
28974  * If the status is changed from active to transparent
28975  * or from transparent to active, forward the new status
28976  * to the filtering module (if loaded).
28977  */
28978 /* ARGSUSED */
28979 static int
28980 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28981     cred_t *ioc_cr)
28982 {
28983 	long		new_value;
28984 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28985 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28986 
28987 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28988 		return (EPERM);
28989 
28990 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28991 	    new_value < 0 || new_value > 1) {
28992 		return (EINVAL);
28993 	}
28994 
28995 	if ((!*ip_cgtp_filter_value) && new_value) {
28996 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28997 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28998 		    " (module not loaded)" : "");
28999 	}
29000 	if (*ip_cgtp_filter_value && (!new_value)) {
29001 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29002 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29003 		    " (module not loaded)" : "");
29004 	}
29005 
29006 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29007 		int	res;
29008 		netstackid_t stackid;
29009 
29010 		stackid = ipst->ips_netstack->netstack_stackid;
29011 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29012 		    new_value);
29013 		if (res)
29014 			return (res);
29015 	}
29016 
29017 	*ip_cgtp_filter_value = (boolean_t)new_value;
29018 
29019 	return (0);
29020 }
29021 
29022 /*
29023  * Return the expected CGTP hooks version number.
29024  */
29025 int
29026 ip_cgtp_filter_supported(void)
29027 {
29028 	return (ip_cgtp_filter_rev);
29029 }
29030 
29031 /*
29032  * CGTP hooks can be registered by invoking this function.
29033  * Checks that the version number matches.
29034  */
29035 int
29036 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29037 {
29038 	netstack_t *ns;
29039 	ip_stack_t *ipst;
29040 
29041 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29042 		return (ENOTSUP);
29043 
29044 	ns = netstack_find_by_stackid(stackid);
29045 	if (ns == NULL)
29046 		return (EINVAL);
29047 	ipst = ns->netstack_ip;
29048 	ASSERT(ipst != NULL);
29049 
29050 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29051 		netstack_rele(ns);
29052 		return (EALREADY);
29053 	}
29054 
29055 	ipst->ips_ip_cgtp_filter_ops = ops;
29056 	netstack_rele(ns);
29057 	return (0);
29058 }
29059 
29060 /*
29061  * CGTP hooks can be unregistered by invoking this function.
29062  * Returns ENXIO if there was no registration.
29063  * Returns EBUSY if the ndd variable has not been turned off.
29064  */
29065 int
29066 ip_cgtp_filter_unregister(netstackid_t stackid)
29067 {
29068 	netstack_t *ns;
29069 	ip_stack_t *ipst;
29070 
29071 	ns = netstack_find_by_stackid(stackid);
29072 	if (ns == NULL)
29073 		return (EINVAL);
29074 	ipst = ns->netstack_ip;
29075 	ASSERT(ipst != NULL);
29076 
29077 	if (ipst->ips_ip_cgtp_filter) {
29078 		netstack_rele(ns);
29079 		return (EBUSY);
29080 	}
29081 
29082 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29083 		netstack_rele(ns);
29084 		return (ENXIO);
29085 	}
29086 	ipst->ips_ip_cgtp_filter_ops = NULL;
29087 	netstack_rele(ns);
29088 	return (0);
29089 }
29090 
29091 /*
29092  * Check whether there is a CGTP filter registration.
29093  * Returns non-zero if there is a registration, otherwise returns zero.
29094  * Note: returns zero if bad stackid.
29095  */
29096 int
29097 ip_cgtp_filter_is_registered(netstackid_t stackid)
29098 {
29099 	netstack_t *ns;
29100 	ip_stack_t *ipst;
29101 	int ret;
29102 
29103 	ns = netstack_find_by_stackid(stackid);
29104 	if (ns == NULL)
29105 		return (0);
29106 	ipst = ns->netstack_ip;
29107 	ASSERT(ipst != NULL);
29108 
29109 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29110 		ret = 1;
29111 	else
29112 		ret = 0;
29113 
29114 	netstack_rele(ns);
29115 	return (ret);
29116 }
29117 
29118 static int
29119 ip_squeue_switch(int val)
29120 {
29121 	int rval = SQ_FILL;
29122 
29123 	switch (val) {
29124 	case IP_SQUEUE_ENTER_NODRAIN:
29125 		rval = SQ_NODRAIN;
29126 		break;
29127 	case IP_SQUEUE_ENTER:
29128 		rval = SQ_PROCESS;
29129 		break;
29130 	default:
29131 		break;
29132 	}
29133 	return (rval);
29134 }
29135 
29136 /* ARGSUSED */
29137 static int
29138 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29139     caddr_t addr, cred_t *cr)
29140 {
29141 	int *v = (int *)addr;
29142 	long new_value;
29143 
29144 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29145 		return (EPERM);
29146 
29147 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29148 		return (EINVAL);
29149 
29150 	ip_squeue_flag = ip_squeue_switch(new_value);
29151 	*v = new_value;
29152 	return (0);
29153 }
29154 
29155 /*
29156  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29157  * ip_debug.
29158  */
29159 /* ARGSUSED */
29160 static int
29161 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29162     caddr_t addr, cred_t *cr)
29163 {
29164 	int *v = (int *)addr;
29165 	long new_value;
29166 
29167 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29168 		return (EPERM);
29169 
29170 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29171 		return (EINVAL);
29172 
29173 	*v = new_value;
29174 	return (0);
29175 }
29176 
29177 static void *
29178 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29179 {
29180 	kstat_t *ksp;
29181 
29182 	ip_stat_t template = {
29183 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29184 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29185 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29186 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29187 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29188 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29189 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29190 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29191 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29192 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29193 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29194 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29195 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29196 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29197 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29198 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29199 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29200 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29201 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29202 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29203 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29204 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29205 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29206 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29207 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29208 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29209 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29210 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29211 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29212 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29213 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29214 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29215 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29216 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29217 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29218 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29219 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29220 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29221 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29222 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29223 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29224 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29225 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29226 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29227 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29228 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29229 	};
29230 
29231 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29232 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29233 	    KSTAT_FLAG_VIRTUAL, stackid);
29234 
29235 	if (ksp == NULL)
29236 		return (NULL);
29237 
29238 	bcopy(&template, ip_statisticsp, sizeof (template));
29239 	ksp->ks_data = (void *)ip_statisticsp;
29240 	ksp->ks_private = (void *)(uintptr_t)stackid;
29241 
29242 	kstat_install(ksp);
29243 	return (ksp);
29244 }
29245 
29246 static void
29247 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29248 {
29249 	if (ksp != NULL) {
29250 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29251 		kstat_delete_netstack(ksp, stackid);
29252 	}
29253 }
29254 
29255 static void *
29256 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29257 {
29258 	kstat_t	*ksp;
29259 
29260 	ip_named_kstat_t template = {
29261 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29262 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29263 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29264 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29265 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29266 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29267 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29268 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29269 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29270 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29271 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29272 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29273 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29274 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29275 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29276 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29277 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29278 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29279 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29280 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29281 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29282 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29283 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29284 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29285 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29286 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29287 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29288 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29289 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29290 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29291 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29292 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29293 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29294 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29295 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29296 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29297 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29298 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29299 	};
29300 
29301 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29302 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29303 	if (ksp == NULL || ksp->ks_data == NULL)
29304 		return (NULL);
29305 
29306 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29307 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29308 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29309 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29310 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29311 
29312 	template.netToMediaEntrySize.value.i32 =
29313 	    sizeof (mib2_ipNetToMediaEntry_t);
29314 
29315 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29316 
29317 	bcopy(&template, ksp->ks_data, sizeof (template));
29318 	ksp->ks_update = ip_kstat_update;
29319 	ksp->ks_private = (void *)(uintptr_t)stackid;
29320 
29321 	kstat_install(ksp);
29322 	return (ksp);
29323 }
29324 
29325 static void
29326 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29327 {
29328 	if (ksp != NULL) {
29329 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29330 		kstat_delete_netstack(ksp, stackid);
29331 	}
29332 }
29333 
29334 static int
29335 ip_kstat_update(kstat_t *kp, int rw)
29336 {
29337 	ip_named_kstat_t *ipkp;
29338 	mib2_ipIfStatsEntry_t ipmib;
29339 	ill_walk_context_t ctx;
29340 	ill_t *ill;
29341 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29342 	netstack_t	*ns;
29343 	ip_stack_t	*ipst;
29344 
29345 	if (kp == NULL || kp->ks_data == NULL)
29346 		return (EIO);
29347 
29348 	if (rw == KSTAT_WRITE)
29349 		return (EACCES);
29350 
29351 	ns = netstack_find_by_stackid(stackid);
29352 	if (ns == NULL)
29353 		return (-1);
29354 	ipst = ns->netstack_ip;
29355 	if (ipst == NULL) {
29356 		netstack_rele(ns);
29357 		return (-1);
29358 	}
29359 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29360 
29361 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29362 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29363 	ill = ILL_START_WALK_V4(&ctx, ipst);
29364 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29365 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29366 	rw_exit(&ipst->ips_ill_g_lock);
29367 
29368 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29369 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29370 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29371 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29372 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29373 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29374 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29375 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29376 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29377 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29378 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29379 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29380 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29381 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29382 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29383 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29384 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29385 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29386 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29387 
29388 	ipkp->routingDiscards.value.ui32 =	0;
29389 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29390 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29391 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29392 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29393 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29394 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29395 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29396 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29397 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29398 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29399 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29400 
29401 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29402 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29403 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29404 
29405 	netstack_rele(ns);
29406 
29407 	return (0);
29408 }
29409 
29410 static void *
29411 icmp_kstat_init(netstackid_t stackid)
29412 {
29413 	kstat_t	*ksp;
29414 
29415 	icmp_named_kstat_t template = {
29416 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29417 		{ "inErrors",		KSTAT_DATA_UINT32 },
29418 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29419 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29420 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29421 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29422 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29423 		{ "inEchos",		KSTAT_DATA_UINT32 },
29424 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29425 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29426 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29427 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29428 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29429 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29430 		{ "outErrors",		KSTAT_DATA_UINT32 },
29431 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29432 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29433 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29434 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29435 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29436 		{ "outEchos",		KSTAT_DATA_UINT32 },
29437 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29438 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29439 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29440 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29441 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29442 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29443 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29444 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29445 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29446 		{ "outDrops",		KSTAT_DATA_UINT32 },
29447 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29448 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29449 	};
29450 
29451 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29452 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29453 	if (ksp == NULL || ksp->ks_data == NULL)
29454 		return (NULL);
29455 
29456 	bcopy(&template, ksp->ks_data, sizeof (template));
29457 
29458 	ksp->ks_update = icmp_kstat_update;
29459 	ksp->ks_private = (void *)(uintptr_t)stackid;
29460 
29461 	kstat_install(ksp);
29462 	return (ksp);
29463 }
29464 
29465 static void
29466 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29467 {
29468 	if (ksp != NULL) {
29469 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29470 		kstat_delete_netstack(ksp, stackid);
29471 	}
29472 }
29473 
29474 static int
29475 icmp_kstat_update(kstat_t *kp, int rw)
29476 {
29477 	icmp_named_kstat_t *icmpkp;
29478 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29479 	netstack_t	*ns;
29480 	ip_stack_t	*ipst;
29481 
29482 	if ((kp == NULL) || (kp->ks_data == NULL))
29483 		return (EIO);
29484 
29485 	if (rw == KSTAT_WRITE)
29486 		return (EACCES);
29487 
29488 	ns = netstack_find_by_stackid(stackid);
29489 	if (ns == NULL)
29490 		return (-1);
29491 	ipst = ns->netstack_ip;
29492 	if (ipst == NULL) {
29493 		netstack_rele(ns);
29494 		return (-1);
29495 	}
29496 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29497 
29498 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29499 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29500 	icmpkp->inDestUnreachs.value.ui32 =
29501 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29502 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29503 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29504 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29505 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29506 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29507 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29508 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29509 	icmpkp->inTimestampReps.value.ui32 =
29510 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29511 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29512 	icmpkp->inAddrMaskReps.value.ui32 =
29513 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29514 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29515 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29516 	icmpkp->outDestUnreachs.value.ui32 =
29517 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29518 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29519 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29520 	icmpkp->outSrcQuenchs.value.ui32 =
29521 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29522 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29523 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29524 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29525 	icmpkp->outTimestamps.value.ui32 =
29526 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29527 	icmpkp->outTimestampReps.value.ui32 =
29528 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29529 	icmpkp->outAddrMasks.value.ui32 =
29530 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29531 	icmpkp->outAddrMaskReps.value.ui32 =
29532 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29533 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29534 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29535 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29536 	icmpkp->outFragNeeded.value.ui32 =
29537 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29538 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29539 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29540 	icmpkp->inBadRedirects.value.ui32 =
29541 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29542 
29543 	netstack_rele(ns);
29544 	return (0);
29545 }
29546 
29547 /*
29548  * This is the fanout function for raw socket opened for SCTP.  Note
29549  * that it is called after SCTP checks that there is no socket which
29550  * wants a packet.  Then before SCTP handles this out of the blue packet,
29551  * this function is called to see if there is any raw socket for SCTP.
29552  * If there is and it is bound to the correct address, the packet will
29553  * be sent to that socket.  Note that only one raw socket can be bound to
29554  * a port.  This is assured in ipcl_sctp_hash_insert();
29555  */
29556 void
29557 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29558     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29559     zoneid_t zoneid)
29560 {
29561 	conn_t		*connp;
29562 	queue_t		*rq;
29563 	mblk_t		*first_mp;
29564 	boolean_t	secure;
29565 	ip6_t		*ip6h;
29566 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29567 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29568 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29569 	boolean_t	sctp_csum_err = B_FALSE;
29570 
29571 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29572 		sctp_csum_err = B_TRUE;
29573 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29574 	}
29575 
29576 	first_mp = mp;
29577 	if (mctl_present) {
29578 		mp = first_mp->b_cont;
29579 		secure = ipsec_in_is_secure(first_mp);
29580 		ASSERT(mp != NULL);
29581 	} else {
29582 		secure = B_FALSE;
29583 	}
29584 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29585 
29586 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29587 	if (connp == NULL) {
29588 		/*
29589 		 * Although raw sctp is not summed, OOB chunks must be.
29590 		 * Drop the packet here if the sctp checksum failed.
29591 		 */
29592 		if (sctp_csum_err) {
29593 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29594 			freemsg(first_mp);
29595 			return;
29596 		}
29597 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29598 		return;
29599 	}
29600 	rq = connp->conn_rq;
29601 	if (!canputnext(rq)) {
29602 		CONN_DEC_REF(connp);
29603 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29604 		freemsg(first_mp);
29605 		return;
29606 	}
29607 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29608 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29609 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29610 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29611 		if (first_mp == NULL) {
29612 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29613 			CONN_DEC_REF(connp);
29614 			return;
29615 		}
29616 	}
29617 	/*
29618 	 * We probably should not send M_CTL message up to
29619 	 * raw socket.
29620 	 */
29621 	if (mctl_present)
29622 		freeb(first_mp);
29623 
29624 	/* Initiate IPPF processing here if needed. */
29625 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29626 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29627 		ip_process(IPP_LOCAL_IN, &mp,
29628 		    recv_ill->ill_phyint->phyint_ifindex);
29629 		if (mp == NULL) {
29630 			CONN_DEC_REF(connp);
29631 			return;
29632 		}
29633 	}
29634 
29635 	if (connp->conn_recvif || connp->conn_recvslla ||
29636 	    ((connp->conn_ip_recvpktinfo ||
29637 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29638 	    (flags & IP_FF_IPINFO))) {
29639 		int in_flags = 0;
29640 
29641 		/*
29642 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29643 		 * IPF_RECVIF.
29644 		 */
29645 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29646 			in_flags = IPF_RECVIF;
29647 		}
29648 		if (connp->conn_recvslla) {
29649 			in_flags |= IPF_RECVSLLA;
29650 		}
29651 		if (isv4) {
29652 			mp = ip_add_info(mp, recv_ill, in_flags,
29653 			    IPCL_ZONEID(connp), ipst);
29654 		} else {
29655 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29656 			if (mp == NULL) {
29657 				BUMP_MIB(recv_ill->ill_ip_mib,
29658 				    ipIfStatsInDiscards);
29659 				CONN_DEC_REF(connp);
29660 				return;
29661 			}
29662 		}
29663 	}
29664 
29665 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29666 	/*
29667 	 * We are sending the IPSEC_IN message also up. Refer
29668 	 * to comments above this function.
29669 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29670 	 */
29671 	(connp->conn_recv)(connp, mp, NULL);
29672 	CONN_DEC_REF(connp);
29673 }
29674 
29675 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29676 {									\
29677 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29678 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29679 }
29680 /*
29681  * This function should be called only if all packet processing
29682  * including fragmentation is complete. Callers of this function
29683  * must set mp->b_prev to one of these values:
29684  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29685  * prior to handing over the mp as first argument to this function.
29686  *
29687  * If the ire passed by caller is incomplete, this function
29688  * queues the packet and if necessary, sends ARP request and bails.
29689  * If the ire passed is fully resolved, we simply prepend
29690  * the link-layer header to the packet, do ipsec hw acceleration
29691  * work if necessary, and send the packet out on the wire.
29692  *
29693  * NOTE: IPsec will only call this function with fully resolved
29694  * ires if hw acceleration is involved.
29695  * TODO list :
29696  * 	a Handle M_MULTIDATA so that
29697  *	  tcp_multisend->tcp_multisend_data can
29698  *	  call ip_xmit_v4 directly
29699  *	b Handle post-ARP work for fragments so that
29700  *	  ip_wput_frag can call this function.
29701  */
29702 ipxmit_state_t
29703 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
29704     boolean_t flow_ctl_enabled, conn_t *connp)
29705 {
29706 	nce_t		*arpce;
29707 	ipha_t		*ipha;
29708 	queue_t		*q;
29709 	int		ill_index;
29710 	mblk_t		*nxt_mp, *first_mp;
29711 	boolean_t	xmit_drop = B_FALSE;
29712 	ip_proc_t	proc;
29713 	ill_t		*out_ill;
29714 	int		pkt_len;
29715 
29716 	arpce = ire->ire_nce;
29717 	ASSERT(arpce != NULL);
29718 
29719 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29720 
29721 	mutex_enter(&arpce->nce_lock);
29722 	switch (arpce->nce_state) {
29723 	case ND_REACHABLE:
29724 		/* If there are other queued packets, queue this packet */
29725 		if (arpce->nce_qd_mp != NULL) {
29726 			if (mp != NULL)
29727 				nce_queue_mp_common(arpce, mp, B_FALSE);
29728 			mp = arpce->nce_qd_mp;
29729 		}
29730 		arpce->nce_qd_mp = NULL;
29731 		mutex_exit(&arpce->nce_lock);
29732 
29733 		/*
29734 		 * Flush the queue.  In the common case, where the
29735 		 * ARP is already resolved,  it will go through the
29736 		 * while loop only once.
29737 		 */
29738 		while (mp != NULL) {
29739 
29740 			nxt_mp = mp->b_next;
29741 			mp->b_next = NULL;
29742 			ASSERT(mp->b_datap->db_type != M_CTL);
29743 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29744 			/*
29745 			 * This info is needed for IPQOS to do COS marking
29746 			 * in ip_wput_attach_llhdr->ip_process.
29747 			 */
29748 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29749 			mp->b_prev = NULL;
29750 
29751 			/* set up ill index for outbound qos processing */
29752 			out_ill = ire_to_ill(ire);
29753 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29754 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29755 			    ill_index, &ipha);
29756 			if (first_mp == NULL) {
29757 				xmit_drop = B_TRUE;
29758 				BUMP_MIB(out_ill->ill_ip_mib,
29759 				    ipIfStatsOutDiscards);
29760 				goto next_mp;
29761 			}
29762 
29763 			/* non-ipsec hw accel case */
29764 			if (io == NULL || !io->ipsec_out_accelerated) {
29765 				/* send it */
29766 				q = ire->ire_stq;
29767 				if (proc == IPP_FWD_OUT) {
29768 					UPDATE_IB_PKT_COUNT(ire);
29769 				} else {
29770 					UPDATE_OB_PKT_COUNT(ire);
29771 				}
29772 				ire->ire_last_used_time = lbolt;
29773 
29774 				if (flow_ctl_enabled || canputnext(q)) {
29775 					if (proc == IPP_FWD_OUT) {
29776 
29777 					BUMP_MIB(out_ill->ill_ip_mib,
29778 					    ipIfStatsHCOutForwDatagrams);
29779 
29780 					}
29781 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29782 					    pkt_len);
29783 
29784 					DTRACE_IP7(send, mblk_t *, first_mp,
29785 					    conn_t *, NULL, void_ip_t *, ipha,
29786 					    __dtrace_ipsr_ill_t *, out_ill,
29787 					    ipha_t *, ipha, ip6_t *, NULL, int,
29788 					    0);
29789 
29790 					ILL_SEND_TX(out_ill,
29791 					    ire, connp, first_mp, 0, connp);
29792 				} else {
29793 					BUMP_MIB(out_ill->ill_ip_mib,
29794 					    ipIfStatsOutDiscards);
29795 					xmit_drop = B_TRUE;
29796 					freemsg(first_mp);
29797 				}
29798 			} else {
29799 				/*
29800 				 * Safety Pup says: make sure this
29801 				 *  is going to the right interface!
29802 				 */
29803 				ill_t *ill1 =
29804 				    (ill_t *)ire->ire_stq->q_ptr;
29805 				int ifindex =
29806 				    ill1->ill_phyint->phyint_ifindex;
29807 				if (ifindex !=
29808 				    io->ipsec_out_capab_ill_index) {
29809 					xmit_drop = B_TRUE;
29810 					freemsg(mp);
29811 				} else {
29812 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29813 					    pkt_len);
29814 
29815 					DTRACE_IP7(send, mblk_t *, first_mp,
29816 					    conn_t *, NULL, void_ip_t *, ipha,
29817 					    __dtrace_ipsr_ill_t *, ill1,
29818 					    ipha_t *, ipha, ip6_t *, NULL,
29819 					    int, 0);
29820 
29821 					ipsec_hw_putnext(ire->ire_stq, mp);
29822 				}
29823 			}
29824 next_mp:
29825 			mp = nxt_mp;
29826 		} /* while (mp != NULL) */
29827 		if (xmit_drop)
29828 			return (SEND_FAILED);
29829 		else
29830 			return (SEND_PASSED);
29831 
29832 	case ND_INITIAL:
29833 	case ND_INCOMPLETE:
29834 
29835 		/*
29836 		 * While we do send off packets to dests that
29837 		 * use fully-resolved CGTP routes, we do not
29838 		 * handle unresolved CGTP routes.
29839 		 */
29840 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29841 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29842 
29843 		if (mp != NULL) {
29844 			/* queue the packet */
29845 			nce_queue_mp_common(arpce, mp, B_FALSE);
29846 		}
29847 
29848 		if (arpce->nce_state == ND_INCOMPLETE) {
29849 			mutex_exit(&arpce->nce_lock);
29850 			DTRACE_PROBE3(ip__xmit__incomplete,
29851 			    (ire_t *), ire, (mblk_t *), mp,
29852 			    (ipsec_out_t *), io);
29853 			return (LOOKUP_IN_PROGRESS);
29854 		}
29855 
29856 		arpce->nce_state = ND_INCOMPLETE;
29857 		mutex_exit(&arpce->nce_lock);
29858 
29859 		/*
29860 		 * Note that ire_add() (called from ire_forward())
29861 		 * holds a ref on the ire until ARP is completed.
29862 		 */
29863 		ire_arpresolve(ire);
29864 		return (LOOKUP_IN_PROGRESS);
29865 	default:
29866 		ASSERT(0);
29867 		mutex_exit(&arpce->nce_lock);
29868 		return (LLHDR_RESLV_FAILED);
29869 	}
29870 }
29871 
29872 #undef	UPDATE_IP_MIB_OB_COUNTERS
29873 
29874 /*
29875  * Return B_TRUE if the buffers differ in length or content.
29876  * This is used for comparing extension header buffers.
29877  * Note that an extension header would be declared different
29878  * even if all that changed was the next header value in that header i.e.
29879  * what really changed is the next extension header.
29880  */
29881 boolean_t
29882 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29883     uint_t blen)
29884 {
29885 	if (!b_valid)
29886 		blen = 0;
29887 
29888 	if (alen != blen)
29889 		return (B_TRUE);
29890 	if (alen == 0)
29891 		return (B_FALSE);	/* Both zero length */
29892 	return (bcmp(abuf, bbuf, alen));
29893 }
29894 
29895 /*
29896  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29897  * Return B_FALSE if memory allocation fails - don't change any state!
29898  */
29899 boolean_t
29900 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29901     const void *src, uint_t srclen)
29902 {
29903 	void *dst;
29904 
29905 	if (!src_valid)
29906 		srclen = 0;
29907 
29908 	ASSERT(*dstlenp == 0);
29909 	if (src != NULL && srclen != 0) {
29910 		dst = mi_alloc(srclen, BPRI_MED);
29911 		if (dst == NULL)
29912 			return (B_FALSE);
29913 	} else {
29914 		dst = NULL;
29915 	}
29916 	if (*dstp != NULL)
29917 		mi_free(*dstp);
29918 	*dstp = dst;
29919 	*dstlenp = dst == NULL ? 0 : srclen;
29920 	return (B_TRUE);
29921 }
29922 
29923 /*
29924  * Replace what is in *dst, *dstlen with the source.
29925  * Assumes ip_allocbuf has already been called.
29926  */
29927 void
29928 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29929     const void *src, uint_t srclen)
29930 {
29931 	if (!src_valid)
29932 		srclen = 0;
29933 
29934 	ASSERT(*dstlenp == srclen);
29935 	if (src != NULL && srclen != 0)
29936 		bcopy(src, *dstp, srclen);
29937 }
29938 
29939 /*
29940  * Free the storage pointed to by the members of an ip6_pkt_t.
29941  */
29942 void
29943 ip6_pkt_free(ip6_pkt_t *ipp)
29944 {
29945 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29946 
29947 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29948 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29949 		ipp->ipp_hopopts = NULL;
29950 		ipp->ipp_hopoptslen = 0;
29951 	}
29952 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29953 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29954 		ipp->ipp_rtdstopts = NULL;
29955 		ipp->ipp_rtdstoptslen = 0;
29956 	}
29957 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29958 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29959 		ipp->ipp_dstopts = NULL;
29960 		ipp->ipp_dstoptslen = 0;
29961 	}
29962 	if (ipp->ipp_fields & IPPF_RTHDR) {
29963 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29964 		ipp->ipp_rthdr = NULL;
29965 		ipp->ipp_rthdrlen = 0;
29966 	}
29967 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29968 	    IPPF_RTHDR);
29969 }
29970 
29971 zoneid_t
29972 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
29973     zoneid_t lookup_zoneid)
29974 {
29975 	ire_t		*ire;
29976 	int		ire_flags = MATCH_IRE_TYPE;
29977 	zoneid_t	zoneid = ALL_ZONES;
29978 
29979 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
29980 		return (ALL_ZONES);
29981 
29982 	if (lookup_zoneid != ALL_ZONES)
29983 		ire_flags |= MATCH_IRE_ZONEONLY;
29984 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
29985 	    lookup_zoneid, NULL, ire_flags, ipst);
29986 	if (ire != NULL) {
29987 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
29988 		ire_refrele(ire);
29989 	}
29990 	return (zoneid);
29991 }
29992 
29993 zoneid_t
29994 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
29995     ip_stack_t *ipst, zoneid_t lookup_zoneid)
29996 {
29997 	ire_t		*ire;
29998 	int		ire_flags = MATCH_IRE_TYPE;
29999 	zoneid_t	zoneid = ALL_ZONES;
30000 	ipif_t		*ipif_arg = NULL;
30001 
30002 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30003 		return (ALL_ZONES);
30004 
30005 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30006 		ire_flags |= MATCH_IRE_ILL;
30007 		ipif_arg = ill->ill_ipif;
30008 	}
30009 	if (lookup_zoneid != ALL_ZONES)
30010 		ire_flags |= MATCH_IRE_ZONEONLY;
30011 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30012 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30013 	if (ire != NULL) {
30014 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30015 		ire_refrele(ire);
30016 	}
30017 	return (zoneid);
30018 }
30019 
30020 /*
30021  * IP obserability hook support functions.
30022  */
30023 
30024 static void
30025 ipobs_init(ip_stack_t *ipst)
30026 {
30027 	ipst->ips_ipobs_enabled = B_FALSE;
30028 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30029 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30030 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30031 	ipst->ips_ipobs_cb_nwalkers = 0;
30032 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30033 }
30034 
30035 static void
30036 ipobs_fini(ip_stack_t *ipst)
30037 {
30038 	ipobs_cb_t *cb;
30039 
30040 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30041 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30042 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30043 
30044 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30045 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30046 		kmem_free(cb, sizeof (*cb));
30047 	}
30048 	list_destroy(&ipst->ips_ipobs_cb_list);
30049 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30050 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30051 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30052 }
30053 
30054 void
30055 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30056     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30057 {
30058 	mblk_t *mp2;
30059 	ipobs_cb_t *ipobs_cb;
30060 	ipobs_hook_data_t *ihd;
30061 	uint64_t grifindex = 0;
30062 
30063 	ASSERT(DB_TYPE(mp) == M_DATA);
30064 
30065 	if (IS_UNDER_IPMP(ill))
30066 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
30067 
30068 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30069 	ipst->ips_ipobs_cb_nwalkers++;
30070 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30071 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30072 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30073 		mp2 = allocb(sizeof (ipobs_hook_data_t), BPRI_HI);
30074 		if (mp2 != NULL) {
30075 			ihd = (ipobs_hook_data_t *)mp2->b_rptr;
30076 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30077 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30078 				freemsg(mp2);
30079 				continue;
30080 			}
30081 			ihd->ihd_mp->b_rptr += hlen;
30082 			ihd->ihd_htype = htype;
30083 			ihd->ihd_ipver = ipver;
30084 			ihd->ihd_zsrc = zsrc;
30085 			ihd->ihd_zdst = zdst;
30086 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30087 			ihd->ihd_grifindex = grifindex;
30088 			ihd->ihd_stack = ipst->ips_netstack;
30089 			mp2->b_wptr += sizeof (*ihd);
30090 			ipobs_cb->ipobs_cbfunc(mp2);
30091 		}
30092 	}
30093 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30094 	ipst->ips_ipobs_cb_nwalkers--;
30095 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30096 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30097 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30098 }
30099 
30100 void
30101 ipobs_register_hook(netstack_t *ns, pfv_t func)
30102 {
30103 	ipobs_cb_t   *cb;
30104 	ip_stack_t *ipst = ns->netstack_ip;
30105 
30106 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30107 
30108 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30109 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30110 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30111 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30112 
30113 	cb->ipobs_cbfunc = func;
30114 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30115 	ipst->ips_ipobs_enabled = B_TRUE;
30116 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30117 }
30118 
30119 void
30120 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30121 {
30122 	ipobs_cb_t	*curcb;
30123 	ip_stack_t	*ipst = ns->netstack_ip;
30124 
30125 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30126 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30127 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30128 
30129 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30130 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30131 		if (func == curcb->ipobs_cbfunc) {
30132 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30133 			kmem_free(curcb, sizeof (*curcb));
30134 			break;
30135 		}
30136 	}
30137 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30138 		ipst->ips_ipobs_enabled = B_FALSE;
30139 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30140 }
30141