xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision 9d12795f87b63c2e39e87bff369182edd34677d3)
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 (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 1990 Mentat Inc.
25  * Copyright (c) 2012 Joyent, Inc. All rights reserved.
26  * Copyright (c) 2014, OmniTI Computer Consulting, Inc. All rights reserved.
27  */
28 
29 #include <sys/types.h>
30 #include <sys/stream.h>
31 #include <sys/dlpi.h>
32 #include <sys/stropts.h>
33 #include <sys/sysmacros.h>
34 #include <sys/strsubr.h>
35 #include <sys/strlog.h>
36 #include <sys/strsun.h>
37 #include <sys/zone.h>
38 #define	_SUN_TPI_VERSION 2
39 #include <sys/tihdr.h>
40 #include <sys/xti_inet.h>
41 #include <sys/ddi.h>
42 #include <sys/suntpi.h>
43 #include <sys/cmn_err.h>
44 #include <sys/debug.h>
45 #include <sys/kobj.h>
46 #include <sys/modctl.h>
47 #include <sys/atomic.h>
48 #include <sys/policy.h>
49 #include <sys/priv.h>
50 #include <sys/taskq.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <sys/mac.h>
60 #include <net/if.h>
61 #include <net/if_arp.h>
62 #include <net/route.h>
63 #include <sys/sockio.h>
64 #include <netinet/in.h>
65 #include <net/if_dl.h>
66 
67 #include <inet/common.h>
68 #include <inet/mi.h>
69 #include <inet/mib2.h>
70 #include <inet/nd.h>
71 #include <inet/arp.h>
72 #include <inet/snmpcom.h>
73 #include <inet/optcom.h>
74 #include <inet/kstatcom.h>
75 
76 #include <netinet/igmp_var.h>
77 #include <netinet/ip6.h>
78 #include <netinet/icmp6.h>
79 #include <netinet/sctp.h>
80 
81 #include <inet/ip.h>
82 #include <inet/ip_impl.h>
83 #include <inet/ip6.h>
84 #include <inet/ip6_asp.h>
85 #include <inet/tcp.h>
86 #include <inet/tcp_impl.h>
87 #include <inet/ip_multi.h>
88 #include <inet/ip_if.h>
89 #include <inet/ip_ire.h>
90 #include <inet/ip_ftable.h>
91 #include <inet/ip_rts.h>
92 #include <inet/ip_ndp.h>
93 #include <inet/ip_listutils.h>
94 #include <netinet/igmp.h>
95 #include <netinet/ip_mroute.h>
96 #include <inet/ipp_common.h>
97 
98 #include <net/pfkeyv2.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <inet/iptun/iptun_impl.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 #include <inet/ilb_ip.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/pattr.h>
115 #include <inet/ipclassifier.h>
116 #include <inet/sctp_ip.h>
117 #include <inet/sctp/sctp_impl.h>
118 #include <inet/udp_impl.h>
119 #include <inet/rawip_impl.h>
120 #include <inet/rts_impl.h>
121 
122 #include <sys/tsol/label.h>
123 #include <sys/tsol/tnet.h>
124 
125 #include <sys/squeue_impl.h>
126 #include <inet/ip_arp.h>
127 
128 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
129 
130 /*
131  * Values for squeue switch:
132  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
133  * IP_SQUEUE_ENTER: SQ_PROCESS
134  * IP_SQUEUE_FILL: SQ_FILL
135  */
136 int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */
137 
138 int ip_squeue_flag;
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 /* Include ire_testhidden and IRE_IF_CLONE routes */
180 #define	IRD_REPORT_ALL	0x01
181 
182 /*
183  * Cluster specific hooks. These should be NULL when booted as a non-cluster
184  */
185 
186 /*
187  * Hook functions to enable cluster networking
188  * On non-clustered systems these vectors must always be NULL.
189  *
190  * Hook function to Check ip specified ip address is a shared ip address
191  * in the cluster
192  *
193  */
194 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
195     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
196 
197 /*
198  * Hook function to generate cluster wide ip fragment identifier
199  */
200 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
201     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
202     void *args) = NULL;
203 
204 /*
205  * Hook function to generate cluster wide SPI.
206  */
207 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
208     void *) = NULL;
209 
210 /*
211  * Hook function to verify if the SPI is already utlized.
212  */
213 
214 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
215 
216 /*
217  * Hook function to delete the SPI from the cluster wide repository.
218  */
219 
220 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
221 
222 /*
223  * Hook function to inform the cluster when packet received on an IDLE SA
224  */
225 
226 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
227     in6_addr_t, in6_addr_t, void *) = NULL;
228 
229 /*
230  * Synchronization notes:
231  *
232  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
233  * MT level protection given by STREAMS. IP uses a combination of its own
234  * internal serialization mechanism and standard Solaris locking techniques.
235  * The internal serialization is per phyint.  This is used to serialize
236  * plumbing operations, IPMP operations, most set ioctls, 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 IPMP operations and processing of DLPI control
244  * messages received from drivers on a per phyint basis. This serialization is
245  * provided by the ipsq_t and primitives operating on this. Details can
246  * be found in ip_if.c above the core primitives operating on ipsq_t.
247  *
248  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
249  * Simiarly lookup of an ire by a thread also returns a refheld ire.
250  * In addition ipif's and ill's referenced by the ire are also indirectly
251  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
252  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
253  * address of an ipif has to go through the ipsq_t. This ensures that only
254  * one such exclusive operation proceeds at any time on the ipif. It then
255  * waits for all refcnts
256  * associated with this ipif to come down to zero. The address is changed
257  * only after the ipif has been quiesced. Then the ipif is brought up again.
258  * More details are described above the comment in ip_sioctl_flags.
259  *
260  * Packet processing is based mostly on IREs and are fully multi-threaded
261  * using standard Solaris MT techniques.
262  *
263  * There are explicit locks in IP to handle:
264  * - The ip_g_head list maintained by mi_open_link() and friends.
265  *
266  * - The reassembly data structures (one lock per hash bucket)
267  *
268  * - conn_lock is meant to protect conn_t fields. The fields actually
269  *   protected by conn_lock are documented in the conn_t definition.
270  *
271  * - ire_lock to protect some of the fields of the ire, IRE tables
272  *   (one lock per hash bucket). Refer to ip_ire.c for details.
273  *
274  * - ndp_g_lock and ncec_lock for protecting NCEs.
275  *
276  * - ill_lock protects fields of the ill and ipif. Details in ip.h
277  *
278  * - ill_g_lock: This is a global reader/writer lock. Protects the following
279  *	* The AVL tree based global multi list of all ills.
280  *	* The linked list of all ipifs of an ill
281  *	* The <ipsq-xop> mapping
282  *	* <ill-phyint> association
283  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
284  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
285  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
286  *   writer for the actual duration of the insertion/deletion/change.
287  *
288  * - ill_lock:  This is a per ill mutex.
289  *   It protects some members of the ill_t struct; see ip.h for details.
290  *   It also protects the <ill-phyint> assoc.
291  *   It also protects the list of ipifs hanging off the ill.
292  *
293  * - ipsq_lock: This is a per ipsq_t mutex lock.
294  *   This protects some members of the ipsq_t struct; see ip.h for details.
295  *   It also protects the <ipsq-ipxop> mapping
296  *
297  * - ipx_lock: This is a per ipxop_t mutex lock.
298  *   This protects some members of the ipxop_t struct; see ip.h for details.
299  *
300  * - phyint_lock: This is a per phyint mutex lock. Protects just the
301  *   phyint_flags
302  *
303  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
304  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
305  *   uniqueness check also done atomically.
306  *
307  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
308  *   group list linked by ill_usesrc_grp_next. It also protects the
309  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
310  *   group is being added or deleted.  This lock is taken as a reader when
311  *   walking the list/group(eg: to get the number of members in a usesrc group).
312  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
313  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
314  *   example, it is not necessary to take this lock in the initial portion
315  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
316  *   operations are executed exclusively and that ensures that the "usesrc
317  *   group state" cannot change. The "usesrc group state" change can happen
318  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
319  *
320  * Changing <ill-phyint>, <ipsq-xop> assocications:
321  *
322  * To change the <ill-phyint> association, the ill_g_lock must be held
323  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
324  * must be held.
325  *
326  * To change the <ipsq-xop> association, the ill_g_lock must be held as
327  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
328  * This is only done when ills are added or removed from IPMP groups.
329  *
330  * To add or delete an ipif from the list of ipifs hanging off the ill,
331  * ill_g_lock (writer) and ill_lock must be held and the thread must be
332  * a writer on the associated ipsq.
333  *
334  * To add or delete an ill to the system, the ill_g_lock must be held as
335  * writer and the thread must be a writer on the associated ipsq.
336  *
337  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
338  * must be a writer on the associated ipsq.
339  *
340  * Lock hierarchy
341  *
342  * Some lock hierarchy scenarios are listed below.
343  *
344  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
345  * ill_g_lock -> ill_lock(s) -> phyint_lock
346  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
347  * ill_g_lock -> ip_addr_avail_lock
348  * conn_lock -> irb_lock -> ill_lock -> ire_lock
349  * ill_g_lock -> ip_g_nd_lock
350  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
351  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
352  * arl_lock -> ill_lock
353  * ips_ire_dep_lock -> irb_lock
354  *
355  * When more than 1 ill lock is needed to be held, all ill lock addresses
356  * are sorted on address and locked starting from highest addressed lock
357  * downward.
358  *
359  * Multicast scenarios
360  * ips_ill_g_lock -> ill_mcast_lock
361  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
362  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
363  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
364  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
365  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
366  *
367  * IPsec scenarios
368  *
369  * ipsa_lock -> ill_g_lock -> ill_lock
370  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
371  *
372  * Trusted Solaris scenarios
373  *
374  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
375  * igsa_lock -> gcdb_lock
376  * gcgrp_rwlock -> ire_lock
377  * gcgrp_rwlock -> gcdb_lock
378  *
379  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
380  *
381  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
382  * sq_lock -> conn_lock -> QLOCK(q)
383  * ill_lock -> ft_lock -> fe_lock
384  *
385  * Routing/forwarding table locking notes:
386  *
387  * Lock acquisition order: Radix tree lock, irb_lock.
388  * Requirements:
389  * i.  Walker must not hold any locks during the walker callback.
390  * ii  Walker must not see a truncated tree during the walk because of any node
391  *     deletion.
392  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
393  *     in many places in the code to walk the irb list. Thus even if all the
394  *     ires in a bucket have been deleted, we still can't free the radix node
395  *     until the ires have actually been inactive'd (freed).
396  *
397  * Tree traversal - Need to hold the global tree lock in read mode.
398  * Before dropping the global tree lock, need to either increment the ire_refcnt
399  * to ensure that the radix node can't be deleted.
400  *
401  * Tree add - Need to hold the global tree lock in write mode to add a
402  * radix node. To prevent the node from being deleted, increment the
403  * irb_refcnt, after the node is added to the tree. The ire itself is
404  * added later while holding the irb_lock, but not the tree lock.
405  *
406  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
407  * All associated ires must be inactive (i.e. freed), and irb_refcnt
408  * must be zero.
409  *
410  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
411  * global tree lock (read mode) for traversal.
412  *
413  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
414  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
415  *
416  * IPsec notes :
417  *
418  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
419  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
420  * ip_xmit_attr_t has the
421  * information used by the IPsec code for applying the right level of
422  * protection. The information initialized by IP in the ip_xmit_attr_t
423  * is determined by the per-socket policy or global policy in the system.
424  * For inbound datagrams, the ip_recv_attr_t
425  * 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  * For fully connected sockets i.e dst, src [addr, port] is known,
433  * conn_policy_cached is set indicating that policy has been cached.
434  * conn_in_enforce_policy may or may not be set depending on whether
435  * there is a global policy match or per-socket policy match.
436  * Policy inheriting happpens in ip_policy_set once the destination is known.
437  * Once the right policy is set on the conn_t, policy cannot change for
438  * this socket. This makes life simpler for TCP (UDP ?) where
439  * re-transmissions go out with the same policy. For symmetry, policy
440  * is cached for fully connected UDP sockets also. Thus if policy is cached,
441  * it also implies that policy is latched i.e policy cannot change
442  * on these sockets. As we have the right policy on the conn, we don't
443  * have to lookup global policy for every outbound and inbound datagram
444  * and thus serving as an optimization. Note that a global policy change
445  * does not affect fully connected sockets if they have policy. If fully
446  * connected sockets did not have any policy associated with it, global
447  * policy change may affect them.
448  *
449  * IP Flow control notes:
450  * ---------------------
451  * Non-TCP streams are flow controlled by IP. The way this is accomplished
452  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
453  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
454  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
455  * functions.
456  *
457  * Per Tx ring udp flow control:
458  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
459  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
460  *
461  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
462  * To achieve best performance, outgoing traffic need to be fanned out among
463  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
464  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
465  * the address of connp as fanout hint to mac_tx(). Under flow controlled
466  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
467  * cookie points to a specific Tx ring that is blocked. The cookie is used to
468  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
469  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
470  * connp's. The drain list is not a single list but a configurable number of
471  * lists.
472  *
473  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
474  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
475  * which is equal to 128. This array in turn contains a pointer to idl_t[],
476  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
477  * list will point to the list of connp's that are flow controlled.
478  *
479  *                      ---------------   -------   -------   -------
480  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
481  *                   |  ---------------   -------   -------   -------
482  *                   |  ---------------   -------   -------   -------
483  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
484  * ----------------  |  ---------------   -------   -------   -------
485  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
486  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
487  *                   |  ---------------   -------   -------   -------
488  *                   .        .              .         .         .
489  *                   |  ---------------   -------   -------   -------
490  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
491  *                      ---------------   -------   -------   -------
492  *                      ---------------   -------   -------   -------
493  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
494  *                   |  ---------------   -------   -------   -------
495  *                   |  ---------------   -------   -------   -------
496  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
497  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
498  * ----------------  |        .              .         .         .
499  *                   |  ---------------   -------   -------   -------
500  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
501  *                      ---------------   -------   -------   -------
502  *     .....
503  * ----------------
504  * |idl_tx_list[n]|-> ...
505  * ----------------
506  *
507  * When mac_tx() returns a cookie, the cookie is hashed into an index into
508  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
509  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
510  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
511  * Further, conn_blocked is set to indicate that the conn is blocked.
512  *
513  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
514  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
515  * is again hashed to locate the appropriate idl_tx_list, which is then
516  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
517  * the drain list and calls conn_drain_remove() to clear flow control (via
518  * calling su_txq_full() or clearing QFULL), and remove the conn from the
519  * drain list.
520  *
521  * Note that the drain list is not a single list but a (configurable) array of
522  * lists (8 elements by default).  Synchronization between drain insertion and
523  * flow control wakeup is handled by using idl_txl->txl_lock, and only
524  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
525  *
526  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
527  * On the send side, if the packet cannot be sent down to the driver by IP
528  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
529  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
530  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
531  * control has been relieved, the blocked conns in the 0'th drain list are
532  * drained as in the non-STREAMS case.
533  *
534  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
535  * is done when the conn is inserted into the drain list (conn_drain_insert())
536  * and cleared when the conn is removed from the it (conn_drain_remove()).
537  *
538  * IPQOS notes:
539  *
540  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
541  * and IPQoS modules. IPPF includes hooks in IP at different control points
542  * (callout positions) which direct packets to IPQoS modules for policy
543  * processing. Policies, if present, are global.
544  *
545  * The callout positions are located in the following paths:
546  *		o local_in (packets destined for this host)
547  *		o local_out (packets orginating from this host )
548  *		o fwd_in  (packets forwarded by this m/c - inbound)
549  *		o fwd_out (packets forwarded by this m/c - outbound)
550  * Hooks at these callout points can be enabled/disabled using the ndd variable
551  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
552  * By default all the callout positions are enabled.
553  *
554  * Outbound (local_out)
555  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
556  *
557  * Inbound (local_in)
558  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
559  *
560  * Forwarding (in and out)
561  * Hooks are placed in ire_recv_forward_v4/v6.
562  *
563  * IP Policy Framework processing (IPPF processing)
564  * Policy processing for a packet is initiated by ip_process, which ascertains
565  * that the classifier (ipgpc) is loaded and configured, failing which the
566  * packet resumes normal processing in IP. If the clasifier is present, the
567  * packet is acted upon by one or more IPQoS modules (action instances), per
568  * filters configured in ipgpc and resumes normal IP processing thereafter.
569  * An action instance can drop a packet in course of its processing.
570  *
571  * Zones notes:
572  *
573  * The partitioning rules for networking are as follows:
574  * 1) Packets coming from a zone must have a source address belonging to that
575  * zone.
576  * 2) Packets coming from a zone can only be sent on a physical interface on
577  * which the zone has an IP address.
578  * 3) Between two zones on the same machine, packet delivery is only allowed if
579  * there's a matching route for the destination and zone in the forwarding
580  * table.
581  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
582  * different zones can bind to the same port with the wildcard address
583  * (INADDR_ANY).
584  *
585  * The granularity of interface partitioning is at the logical interface level.
586  * Therefore, every zone has its own IP addresses, and incoming packets can be
587  * attributed to a zone unambiguously. A logical interface is placed into a zone
588  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
589  * structure. Rule (1) is implemented by modifying the source address selection
590  * algorithm so that the list of eligible addresses is filtered based on the
591  * sending process zone.
592  *
593  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
594  * across all zones, depending on their type. Here is the break-up:
595  *
596  * IRE type				Shared/exclusive
597  * --------				----------------
598  * IRE_BROADCAST			Exclusive
599  * IRE_DEFAULT (default routes)		Shared (*)
600  * IRE_LOCAL				Exclusive (x)
601  * IRE_LOOPBACK				Exclusive
602  * IRE_PREFIX (net routes)		Shared (*)
603  * IRE_IF_NORESOLVER (interface routes)	Exclusive
604  * IRE_IF_RESOLVER (interface routes)	Exclusive
605  * IRE_IF_CLONE (interface routes)	Exclusive
606  * IRE_HOST (host routes)		Shared (*)
607  *
608  * (*) A zone can only use a default or off-subnet route if the gateway is
609  * directly reachable from the zone, that is, if the gateway's address matches
610  * one of the zone's logical interfaces.
611  *
612  * (x) IRE_LOCAL are handled a bit differently.
613  * When ip_restrict_interzone_loopback is set (the default),
614  * ire_route_recursive restricts loopback using an IRE_LOCAL
615  * between zone to the case when L2 would have conceptually looped the packet
616  * back, i.e. the loopback which is required since neither Ethernet drivers
617  * nor Ethernet hardware loops them back. This is the case when the normal
618  * routes (ignoring IREs with different zoneids) would send out the packet on
619  * the same ill as the ill with which is IRE_LOCAL is associated.
620  *
621  * Multiple zones can share a common broadcast address; typically all zones
622  * share the 255.255.255.255 address. Incoming as well as locally originated
623  * broadcast packets must be dispatched to all the zones on the broadcast
624  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
625  * since some zones may not be on the 10.16.72/24 network. To handle this, each
626  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
627  * sent to every zone that has an IRE_BROADCAST entry for the destination
628  * address on the input ill, see ip_input_broadcast().
629  *
630  * Applications in different zones can join the same multicast group address.
631  * The same logic applies for multicast as for broadcast. ip_input_multicast
632  * dispatches packets to all zones that have members on the physical interface.
633  */
634 
635 /*
636  * Squeue Fanout flags:
637  *	0: No fanout.
638  *	1: Fanout across all squeues
639  */
640 boolean_t	ip_squeue_fanout = 0;
641 
642 /*
643  * Maximum dups allowed per packet.
644  */
645 uint_t ip_max_frag_dups = 10;
646 
647 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
648 		    cred_t *credp, boolean_t isv6);
649 static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);
650 
651 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
652 static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
653 static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
654     ip_recv_attr_t *);
655 static void	icmp_options_update(ipha_t *);
656 static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
657 static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
658 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
659 static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
660     ip_recv_attr_t *);
661 static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
662 static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
663     ip_recv_attr_t *);
664 
665 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
666 char		*ip_dot_addr(ipaddr_t, char *);
667 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
668 int		ip_close(queue_t *, int);
669 static char	*ip_dot_saddr(uchar_t *, char *);
670 static void	ip_lrput(queue_t *, mblk_t *);
671 ipaddr_t	ip_net_mask(ipaddr_t);
672 char		*ip_nv_lookup(nv_t *, int);
673 void	ip_rput(queue_t *, mblk_t *);
674 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
675 		    void *dummy_arg);
676 int		ip_snmp_get(queue_t *, mblk_t *, int, boolean_t);
677 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
678 		    mib2_ipIfStatsEntry_t *, ip_stack_t *, boolean_t);
679 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
680 		    ip_stack_t *, boolean_t);
681 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *,
682 		    boolean_t);
683 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
687 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
688 		    ip_stack_t *ipst, boolean_t);
689 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
690 		    ip_stack_t *ipst, boolean_t);
691 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
692 		    ip_stack_t *ipst);
693 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
694 		    ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
698 		    ip_stack_t *ipst);
699 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
700 		    ip_stack_t *ipst);
701 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
702 		    ip_stack_t *ipst);
703 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
704 		    ip_stack_t *ipst);
705 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
706 		    ip_stack_t *ipst);
707 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
708 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
709 static int	ip_snmp_get2_v4_media(ncec_t *, iproutedata_t *);
710 static int	ip_snmp_get2_v6_media(ncec_t *, iproutedata_t *);
711 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
712 
713 static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
714 		    mblk_t *);
715 
716 static void	conn_drain_init(ip_stack_t *);
717 static void	conn_drain_fini(ip_stack_t *);
718 static void	conn_drain(conn_t *connp, boolean_t closing);
719 
720 static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
721 static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);
722 
723 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
724 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
725 static void	ip_stack_fini(netstackid_t stackid, void *arg);
726 
727 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
728     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
729     ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
730     const in6_addr_t *);
731 
732 static int	ip_squeue_switch(int);
733 
734 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
735 static void	ip_kstat_fini(netstackid_t, kstat_t *);
736 static int	ip_kstat_update(kstat_t *kp, int rw);
737 static void	*icmp_kstat_init(netstackid_t);
738 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
739 static int	icmp_kstat_update(kstat_t *kp, int rw);
740 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
741 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
742 
743 static void	ipobs_init(ip_stack_t *);
744 static void	ipobs_fini(ip_stack_t *);
745 
746 static int	ip_tp_cpu_update(cpu_setup_t, int, void *);
747 
748 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
749 
750 static long ip_rput_pullups;
751 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
752 
753 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
754 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
755 
756 int	ip_debug;
757 
758 /*
759  * Multirouting/CGTP stuff
760  */
761 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
762 
763 /*
764  * IP tunables related declarations. Definitions are in ip_tunables.c
765  */
766 extern mod_prop_info_t ip_propinfo_tbl[];
767 extern int ip_propinfo_count;
768 
769 /*
770  * Table of IP ioctls encoding the various properties of the ioctl and
771  * indexed based on the last byte of the ioctl command. Occasionally there
772  * is a clash, and there is more than 1 ioctl with the same last byte.
773  * In such a case 1 ioctl is encoded in the ndx table and the remaining
774  * ioctls are encoded in the misc table. An entry in the ndx table is
775  * retrieved by indexing on the last byte of the ioctl command and comparing
776  * the ioctl command with the value in the ndx table. In the event of a
777  * mismatch the misc table is then searched sequentially for the desired
778  * ioctl command.
779  *
780  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
781  */
782 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
783 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
784 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
785 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
786 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
787 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
788 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
789 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
790 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
791 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
792 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
793 
794 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
795 			MISC_CMD, ip_siocaddrt, NULL },
796 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
797 			MISC_CMD, ip_siocdelrt, NULL },
798 
799 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
800 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
801 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
802 			IF_CMD, ip_sioctl_get_addr, NULL },
803 
804 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
805 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
806 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
807 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },
808 
809 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
810 			IPI_PRIV | IPI_WR,
811 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
812 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
813 			IPI_MODOK | IPI_GET_CMD,
814 			IF_CMD, ip_sioctl_get_flags, NULL },
815 
816 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
817 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
818 
819 	/* copyin size cannot be coded for SIOCGIFCONF */
820 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
821 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
822 
823 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
824 			IF_CMD, ip_sioctl_mtu, NULL },
825 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
826 			IF_CMD, ip_sioctl_get_mtu, NULL },
827 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
828 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
829 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
830 			IF_CMD, ip_sioctl_brdaddr, NULL },
831 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
832 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
833 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
834 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
835 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
836 			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
837 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
838 			IF_CMD, ip_sioctl_metric, NULL },
839 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
840 
841 	/* See 166-168 below for extended SIOC*XARP ioctls */
842 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
843 			ARP_CMD, ip_sioctl_arp, NULL },
844 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
845 			ARP_CMD, ip_sioctl_arp, NULL },
846 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
847 			ARP_CMD, ip_sioctl_arp, NULL },
848 
849 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
850 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
851 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
852 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
853 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
854 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
855 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
856 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
857 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
858 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
859 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
860 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
861 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
862 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
863 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
864 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
865 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
866 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
867 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
868 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
869 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
870 
871 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
872 			MISC_CMD, if_unitsel, if_unitsel_restart },
873 
874 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
875 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
876 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
877 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
878 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
879 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
880 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
881 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
882 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
883 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
884 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
885 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
886 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
887 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
888 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
889 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
890 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
891 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
892 
893 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
894 			IPI_PRIV | IPI_WR | IPI_MODOK,
895 			IF_CMD, ip_sioctl_sifname, NULL },
896 
897 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
898 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
899 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
900 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
901 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
902 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
903 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
904 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
905 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
906 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
907 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
908 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
909 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
910 
911 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
912 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
913 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
914 			IF_CMD, ip_sioctl_get_muxid, NULL },
915 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
916 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },
917 
918 	/* Both if and lif variants share same func */
919 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
920 			IF_CMD, ip_sioctl_get_lifindex, NULL },
921 	/* Both if and lif variants share same func */
922 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
923 			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },
924 
925 	/* copyin size cannot be coded for SIOCGIFCONF */
926 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
927 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
928 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
929 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
930 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
931 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
932 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
933 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
934 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
935 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
936 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
937 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
938 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
939 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
940 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
941 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
942 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
943 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
944 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
945 
946 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
947 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
948 			ip_sioctl_removeif_restart },
949 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
950 			IPI_GET_CMD | IPI_PRIV | IPI_WR,
951 			LIF_CMD, ip_sioctl_addif, NULL },
952 #define	SIOCLIFADDR_NDX 112
953 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
954 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
955 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
956 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
957 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
958 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
959 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
960 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
961 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
962 			IPI_PRIV | IPI_WR,
963 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
964 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
965 			IPI_GET_CMD | IPI_MODOK,
966 			LIF_CMD, ip_sioctl_get_flags, NULL },
967 
968 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
969 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
970 
971 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
972 			ip_sioctl_get_lifconf, NULL },
973 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
974 			LIF_CMD, ip_sioctl_mtu, NULL },
975 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
976 			LIF_CMD, ip_sioctl_get_mtu, NULL },
977 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
978 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
979 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
980 			LIF_CMD, ip_sioctl_brdaddr, NULL },
981 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
982 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
983 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
984 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
985 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
986 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
987 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
988 			LIF_CMD, ip_sioctl_metric, NULL },
989 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
990 			IPI_PRIV | IPI_WR | IPI_MODOK,
991 			LIF_CMD, ip_sioctl_slifname,
992 			ip_sioctl_slifname_restart },
993 
994 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
995 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
996 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
997 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
998 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
999 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
1000 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1001 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
1002 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1003 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
1004 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1005 			LIF_CMD, ip_sioctl_token, NULL },
1006 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1007 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
1008 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1009 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1010 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1011 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
1012 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1013 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1014 
1015 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1016 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1017 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1018 			LIF_CMD, ip_siocdelndp_v6, NULL },
1019 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1020 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1021 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1022 			LIF_CMD, ip_siocsetndp_v6, NULL },
1023 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1024 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1025 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1026 			MISC_CMD, ip_sioctl_tonlink, NULL },
1027 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1028 			MISC_CMD, ip_sioctl_tmysite, NULL },
1029 	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 
1032 	/* Old *IPSECONFIG ioctls are now deprecated, now see spdsock.c */
1033 	/* 149 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 150 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 151 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 152 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 
1038 	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 
1040 	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
1041 			LIF_CMD, ip_sioctl_get_binding, NULL },
1042 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1043 			IPI_PRIV | IPI_WR,
1044 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1045 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1046 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
1047 	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
1048 			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },
1049 
1050 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1051 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 
1055 	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 
1057 	/* These are handled in ip_sioctl_copyin_setup itself */
1058 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1059 			MISC_CMD, NULL, NULL },
1060 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1061 			MISC_CMD, NULL, NULL },
1062 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1063 
1064 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1065 			ip_sioctl_get_lifconf, NULL },
1066 
1067 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1068 			XARP_CMD, ip_sioctl_arp, NULL },
1069 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
1070 			XARP_CMD, ip_sioctl_arp, NULL },
1071 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
1072 			XARP_CMD, ip_sioctl_arp, NULL },
1073 
1074 	/* SIOCPOPSOCKFS is not handled by IP */
1075 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1076 
1077 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1078 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
1079 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1080 			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
1081 			ip_sioctl_slifzone_restart },
1082 	/* 172-174 are SCTP ioctls and not handled by IP */
1083 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1085 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1087 			IPI_GET_CMD, LIF_CMD,
1088 			ip_sioctl_get_lifusesrc, 0 },
1089 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1090 			IPI_PRIV | IPI_WR,
1091 			LIF_CMD, ip_sioctl_slifusesrc,
1092 			NULL },
1093 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1094 			ip_sioctl_get_lifsrcof, NULL },
1095 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1096 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1097 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
1098 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1099 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1100 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1101 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
1102 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1103 	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* SIOCSENABLESDP is handled by SDP */
1105 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1106 	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
1107 	/* 185 */ { SIOCGIFHWADDR, sizeof (struct ifreq), IPI_GET_CMD,
1108 			IF_CMD, ip_sioctl_get_ifhwaddr, NULL },
1109 	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
1110 	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
1111 			ip_sioctl_ilb_cmd, NULL },
1112 	/* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
1113 	/* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
1114 	/* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
1115 			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
1116 	/* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1117 			LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart },
1118 	/* 192 */ { SIOCGLIFHWADDR, sizeof (struct lifreq), IPI_GET_CMD,
1119 			LIF_CMD, ip_sioctl_get_lifhwaddr, NULL }
1120 };
1121 
1122 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1123 
1124 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1125 	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1126 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1127 	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1128 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1129 	{ ND_GET,	0, 0, 0, NULL, NULL },
1130 	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
1131 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1132 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
1133 		MISC_CMD, mrt_ioctl},
1134 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
1135 		MISC_CMD, mrt_ioctl},
1136 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
1137 		MISC_CMD, mrt_ioctl}
1138 };
1139 
1140 int ip_misc_ioctl_count =
1141     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1142 
1143 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1144 					/* Settable in /etc/system */
1145 /* Defined in ip_ire.c */
1146 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1147 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1148 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1149 
1150 static nv_t	ire_nv_arr[] = {
1151 	{ IRE_BROADCAST, "BROADCAST" },
1152 	{ IRE_LOCAL, "LOCAL" },
1153 	{ IRE_LOOPBACK, "LOOPBACK" },
1154 	{ IRE_DEFAULT, "DEFAULT" },
1155 	{ IRE_PREFIX, "PREFIX" },
1156 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1157 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1158 	{ IRE_IF_CLONE, "IF_CLONE" },
1159 	{ IRE_HOST, "HOST" },
1160 	{ IRE_MULTICAST, "MULTICAST" },
1161 	{ IRE_NOROUTE, "NOROUTE" },
1162 	{ 0 }
1163 };
1164 
1165 nv_t	*ire_nv_tbl = ire_nv_arr;
1166 
1167 /* Simple ICMP IP Header Template */
1168 static ipha_t icmp_ipha = {
1169 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1170 };
1171 
1172 struct module_info ip_mod_info = {
1173 	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
1174 	IP_MOD_LOWAT
1175 };
1176 
1177 /*
1178  * Duplicate static symbols within a module confuses mdb; so we avoid the
1179  * problem by making the symbols here distinct from those in udp.c.
1180  */
1181 
1182 /*
1183  * Entry points for IP as a device and as a module.
1184  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1185  */
1186 static struct qinit iprinitv4 = {
1187 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1188 	&ip_mod_info
1189 };
1190 
1191 struct qinit iprinitv6 = {
1192 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1193 	&ip_mod_info
1194 };
1195 
1196 static struct qinit ipwinit = {
1197 	(pfi_t)ip_wput_nondata, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1198 	&ip_mod_info
1199 };
1200 
1201 static struct qinit iplrinit = {
1202 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1203 	&ip_mod_info
1204 };
1205 
1206 static struct qinit iplwinit = {
1207 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1208 	&ip_mod_info
1209 };
1210 
1211 /* For AF_INET aka /dev/ip */
1212 struct streamtab ipinfov4 = {
1213 	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
1214 };
1215 
1216 /* For AF_INET6 aka /dev/ip6 */
1217 struct streamtab ipinfov6 = {
1218 	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
1219 };
1220 
1221 #ifdef	DEBUG
1222 boolean_t skip_sctp_cksum = B_FALSE;
1223 #endif
1224 
1225 /*
1226  * Generate an ICMP fragmentation needed message.
1227  * When called from ip_output side a minimal ip_recv_attr_t needs to be
1228  * constructed by the caller.
1229  */
1230 void
1231 icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
1232 {
1233 	icmph_t	icmph;
1234 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1235 
1236 	mp = icmp_pkt_err_ok(mp, ira);
1237 	if (mp == NULL)
1238 		return;
1239 
1240 	bzero(&icmph, sizeof (icmph_t));
1241 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1242 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1243 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1244 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1245 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1246 
1247 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
1248 }
1249 
1250 /*
1251  * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
1252  * If the ICMP message is consumed by IP, i.e., it should not be delivered
1253  * to any IPPROTO_ICMP raw sockets, then it returns NULL.
1254  * Likewise, if the ICMP error is misformed (too short, etc), then it
1255  * returns NULL. The caller uses this to determine whether or not to send
1256  * to raw sockets.
1257  *
1258  * All error messages are passed to the matching transport stream.
1259  *
1260  * The following cases are handled by icmp_inbound:
1261  * 1) It needs to send a reply back and possibly delivering it
1262  *    to the "interested" upper clients.
1263  * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
1264  * 3) It needs to change some values in IP only.
1265  * 4) It needs to change some values in IP and upper layers e.g TCP
1266  *    by delivering an error to the upper layers.
1267  *
1268  * We handle the above three cases in the context of IPsec in the
1269  * following way :
1270  *
1271  * 1) Send the reply back in the same way as the request came in.
1272  *    If it came in encrypted, it goes out encrypted. If it came in
1273  *    clear, it goes out in clear. Thus, this will prevent chosen
1274  *    plain text attack.
1275  * 2) The client may or may not expect things to come in secure.
1276  *    If it comes in secure, the policy constraints are checked
1277  *    before delivering it to the upper layers. If it comes in
1278  *    clear, ipsec_inbound_accept_clear will decide whether to
1279  *    accept this in clear or not. In both the cases, if the returned
1280  *    message (IP header + 8 bytes) that caused the icmp message has
1281  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1282  *    sending up. If there are only 8 bytes of returned message, then
1283  *    upper client will not be notified.
1284  * 3) Check with global policy to see whether it matches the constaints.
1285  *    But this will be done only if icmp_accept_messages_in_clear is
1286  *    zero.
1287  * 4) If we need to change both in IP and ULP, then the decision taken
1288  *    while affecting the values in IP and while delivering up to TCP
1289  *    should be the same.
1290  *
1291  * 	There are two cases.
1292  *
1293  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1294  *	   failed), we will not deliver it to the ULP, even though they
1295  *	   are *willing* to accept in *clear*. This is fine as our global
1296  *	   disposition to icmp messages asks us reject the datagram.
1297  *
1298  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1299  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1300  *	   to deliver it to ULP (policy failed), it can lead to
1301  *	   consistency problems. The cases known at this time are
1302  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1303  *	   values :
1304  *
1305  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1306  *	     and Upper layer rejects. Then the communication will
1307  *	     come to a stop. This is solved by making similar decisions
1308  *	     at both levels. Currently, when we are unable to deliver
1309  *	     to the Upper Layer (due to policy failures) while IP has
1310  *	     adjusted dce_pmtu, the next outbound datagram would
1311  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1312  *	     will be with the right level of protection. Thus the right
1313  *	     value will be communicated even if we are not able to
1314  *	     communicate when we get from the wire initially. But this
1315  *	     assumes there would be at least one outbound datagram after
1316  *	     IP has adjusted its dce_pmtu value. To make things
1317  *	     simpler, we accept in clear after the validation of
1318  *	     AH/ESP headers.
1319  *
1320  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1321  *	     upper layer depending on the level of protection the upper
1322  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1323  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1324  *	     should be accepted in clear when the Upper layer expects secure.
1325  *	     Thus the communication may get aborted by some bad ICMP
1326  *	     packets.
1327  */
1328 mblk_t *
1329 icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
1330 {
1331 	icmph_t		*icmph;
1332 	ipha_t		*ipha;		/* Outer header */
1333 	int		ip_hdr_length;	/* Outer header length */
1334 	boolean_t	interested;
1335 	ipif_t		*ipif;
1336 	uint32_t	ts;
1337 	uint32_t	*tsp;
1338 	timestruc_t	now;
1339 	ill_t		*ill = ira->ira_ill;
1340 	ip_stack_t	*ipst = ill->ill_ipst;
1341 	zoneid_t	zoneid = ira->ira_zoneid;
1342 	int		len_needed;
1343 	mblk_t		*mp_ret = NULL;
1344 
1345 	ipha = (ipha_t *)mp->b_rptr;
1346 
1347 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1348 
1349 	ip_hdr_length = ira->ira_ip_hdr_length;
1350 	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
1351 		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
1352 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1353 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1354 			freemsg(mp);
1355 			return (NULL);
1356 		}
1357 		/* Last chance to get real. */
1358 		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
1359 		if (ipha == NULL) {
1360 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1361 			freemsg(mp);
1362 			return (NULL);
1363 		}
1364 	}
1365 
1366 	/* The IP header will always be a multiple of four bytes */
1367 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1368 	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
1369 	    icmph->icmph_code));
1370 
1371 	/*
1372 	 * We will set "interested" to "true" if we should pass a copy to
1373 	 * the transport or if we handle the packet locally.
1374 	 */
1375 	interested = B_FALSE;
1376 	switch (icmph->icmph_type) {
1377 	case ICMP_ECHO_REPLY:
1378 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1379 		break;
1380 	case ICMP_DEST_UNREACHABLE:
1381 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1382 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1383 		interested = B_TRUE;	/* Pass up to transport */
1384 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1385 		break;
1386 	case ICMP_SOURCE_QUENCH:
1387 		interested = B_TRUE;	/* Pass up to transport */
1388 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1389 		break;
1390 	case ICMP_REDIRECT:
1391 		if (!ipst->ips_ip_ignore_redirect)
1392 			interested = B_TRUE;
1393 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1394 		break;
1395 	case ICMP_ECHO_REQUEST:
1396 		/*
1397 		 * Whether to respond to echo requests that come in as IP
1398 		 * broadcasts or as IP multicast is subject to debate
1399 		 * (what isn't?).  We aim to please, you pick it.
1400 		 * Default is do it.
1401 		 */
1402 		if (ira->ira_flags & IRAF_MULTICAST) {
1403 			/* multicast: respond based on tunable */
1404 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1405 		} else if (ira->ira_flags & IRAF_BROADCAST) {
1406 			/* broadcast: respond based on tunable */
1407 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1408 		} else {
1409 			/* unicast: always respond */
1410 			interested = B_TRUE;
1411 		}
1412 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1413 		if (!interested) {
1414 			/* We never pass these to RAW sockets */
1415 			freemsg(mp);
1416 			return (NULL);
1417 		}
1418 
1419 		/* Check db_ref to make sure we can modify the packet. */
1420 		if (mp->b_datap->db_ref > 1) {
1421 			mblk_t	*mp1;
1422 
1423 			mp1 = copymsg(mp);
1424 			freemsg(mp);
1425 			if (!mp1) {
1426 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1427 				return (NULL);
1428 			}
1429 			mp = mp1;
1430 			ipha = (ipha_t *)mp->b_rptr;
1431 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1432 		}
1433 		icmph->icmph_type = ICMP_ECHO_REPLY;
1434 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1435 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1436 		return (NULL);
1437 
1438 	case ICMP_ROUTER_ADVERTISEMENT:
1439 	case ICMP_ROUTER_SOLICITATION:
1440 		break;
1441 	case ICMP_TIME_EXCEEDED:
1442 		interested = B_TRUE;	/* Pass up to transport */
1443 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1444 		break;
1445 	case ICMP_PARAM_PROBLEM:
1446 		interested = B_TRUE;	/* Pass up to transport */
1447 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1448 		break;
1449 	case ICMP_TIME_STAMP_REQUEST:
1450 		/* Response to Time Stamp Requests is local policy. */
1451 		if (ipst->ips_ip_g_resp_to_timestamp) {
1452 			if (ira->ira_flags & IRAF_MULTIBROADCAST)
1453 				interested =
1454 				    ipst->ips_ip_g_resp_to_timestamp_bcast;
1455 			else
1456 				interested = B_TRUE;
1457 		}
1458 		if (!interested) {
1459 			/* We never pass these to RAW sockets */
1460 			freemsg(mp);
1461 			return (NULL);
1462 		}
1463 
1464 		/* Make sure we have enough of the packet */
1465 		len_needed = ip_hdr_length + ICMPH_SIZE +
1466 		    3 * sizeof (uint32_t);
1467 
1468 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1469 			ipha = ip_pullup(mp, len_needed, ira);
1470 			if (ipha == NULL) {
1471 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1472 				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1473 				    mp, ill);
1474 				freemsg(mp);
1475 				return (NULL);
1476 			}
1477 			/* Refresh following the pullup. */
1478 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1479 		}
1480 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1481 		/* Check db_ref to make sure we can modify the packet. */
1482 		if (mp->b_datap->db_ref > 1) {
1483 			mblk_t	*mp1;
1484 
1485 			mp1 = copymsg(mp);
1486 			freemsg(mp);
1487 			if (!mp1) {
1488 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1489 				return (NULL);
1490 			}
1491 			mp = mp1;
1492 			ipha = (ipha_t *)mp->b_rptr;
1493 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1494 		}
1495 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1496 		tsp = (uint32_t *)&icmph[1];
1497 		tsp++;		/* Skip past 'originate time' */
1498 		/* Compute # of milliseconds since midnight */
1499 		gethrestime(&now);
1500 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1501 		    NSEC2MSEC(now.tv_nsec);
1502 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1503 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1504 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1505 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1506 		return (NULL);
1507 
1508 	case ICMP_TIME_STAMP_REPLY:
1509 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1510 		break;
1511 	case ICMP_INFO_REQUEST:
1512 		/* Per RFC 1122 3.2.2.7, ignore this. */
1513 	case ICMP_INFO_REPLY:
1514 		break;
1515 	case ICMP_ADDRESS_MASK_REQUEST:
1516 		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1517 			interested =
1518 			    ipst->ips_ip_respond_to_address_mask_broadcast;
1519 		} else {
1520 			interested = B_TRUE;
1521 		}
1522 		if (!interested) {
1523 			/* We never pass these to RAW sockets */
1524 			freemsg(mp);
1525 			return (NULL);
1526 		}
1527 		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
1528 		if (mp->b_wptr - mp->b_rptr < len_needed) {
1529 			ipha = ip_pullup(mp, len_needed, ira);
1530 			if (ipha == NULL) {
1531 				BUMP_MIB(ill->ill_ip_mib,
1532 				    ipIfStatsInTruncatedPkts);
1533 				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
1534 				    ill);
1535 				freemsg(mp);
1536 				return (NULL);
1537 			}
1538 			/* Refresh following the pullup. */
1539 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1540 		}
1541 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1542 		/* Check db_ref to make sure we can modify the packet. */
1543 		if (mp->b_datap->db_ref > 1) {
1544 			mblk_t	*mp1;
1545 
1546 			mp1 = copymsg(mp);
1547 			freemsg(mp);
1548 			if (!mp1) {
1549 				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1550 				return (NULL);
1551 			}
1552 			mp = mp1;
1553 			ipha = (ipha_t *)mp->b_rptr;
1554 			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1555 		}
1556 		/*
1557 		 * Need the ipif with the mask be the same as the source
1558 		 * address of the mask reply. For unicast we have a specific
1559 		 * ipif. For multicast/broadcast we only handle onlink
1560 		 * senders, and use the source address to pick an ipif.
1561 		 */
1562 		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
1563 		if (ipif == NULL) {
1564 			/* Broadcast or multicast */
1565 			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1566 			if (ipif == NULL) {
1567 				freemsg(mp);
1568 				return (NULL);
1569 			}
1570 		}
1571 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1572 		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
1573 		ipif_refrele(ipif);
1574 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1575 		icmp_send_reply_v4(mp, ipha, icmph, ira);
1576 		return (NULL);
1577 
1578 	case ICMP_ADDRESS_MASK_REPLY:
1579 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1580 		break;
1581 	default:
1582 		interested = B_TRUE;	/* Pass up to transport */
1583 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1584 		break;
1585 	}
1586 	/*
1587 	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
1588 	 * if there isn't one.
1589 	 */
1590 	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
1591 		/* If there is an ICMP client and we want one too, copy it. */
1592 
1593 		if (!interested) {
1594 			/* Caller will deliver to RAW sockets */
1595 			return (mp);
1596 		}
1597 		mp_ret = copymsg(mp);
1598 		if (mp_ret == NULL) {
1599 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1600 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1601 		}
1602 	} else if (!interested) {
1603 		/* Neither we nor raw sockets are interested. Drop packet now */
1604 		freemsg(mp);
1605 		return (NULL);
1606 	}
1607 
1608 	/*
1609 	 * ICMP error or redirect packet. Make sure we have enough of
1610 	 * the header and that db_ref == 1 since we might end up modifying
1611 	 * the packet.
1612 	 */
1613 	if (mp->b_cont != NULL) {
1614 		if (ip_pullup(mp, -1, ira) == NULL) {
1615 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1616 			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
1617 			    mp, ill);
1618 			freemsg(mp);
1619 			return (mp_ret);
1620 		}
1621 	}
1622 
1623 	if (mp->b_datap->db_ref > 1) {
1624 		mblk_t	*mp1;
1625 
1626 		mp1 = copymsg(mp);
1627 		if (mp1 == NULL) {
1628 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1629 			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
1630 			freemsg(mp);
1631 			return (mp_ret);
1632 		}
1633 		freemsg(mp);
1634 		mp = mp1;
1635 	}
1636 
1637 	/*
1638 	 * In case mp has changed, verify the message before any further
1639 	 * processes.
1640 	 */
1641 	ipha = (ipha_t *)mp->b_rptr;
1642 	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
1643 	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
1644 		freemsg(mp);
1645 		return (mp_ret);
1646 	}
1647 
1648 	switch (icmph->icmph_type) {
1649 	case ICMP_REDIRECT:
1650 		icmp_redirect_v4(mp, ipha, icmph, ira);
1651 		break;
1652 	case ICMP_DEST_UNREACHABLE:
1653 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1654 			/* Update DCE and adjust MTU is icmp header if needed */
1655 			icmp_inbound_too_big_v4(icmph, ira);
1656 		}
1657 		/* FALLTHRU */
1658 	default:
1659 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
1660 		break;
1661 	}
1662 	return (mp_ret);
1663 }
1664 
1665 /*
1666  * Send an ICMP echo, timestamp or address mask reply.
1667  * The caller has already updated the payload part of the packet.
1668  * We handle the ICMP checksum, IP source address selection and feed
1669  * the packet into ip_output_simple.
1670  */
1671 static void
1672 icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
1673     ip_recv_attr_t *ira)
1674 {
1675 	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
1676 	ill_t		*ill = ira->ira_ill;
1677 	ip_stack_t	*ipst = ill->ill_ipst;
1678 	ip_xmit_attr_t	ixas;
1679 
1680 	/* Send out an ICMP packet */
1681 	icmph->icmph_checksum = 0;
1682 	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
1683 	/* Reset time to live. */
1684 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1685 	{
1686 		/* Swap source and destination addresses */
1687 		ipaddr_t tmp;
1688 
1689 		tmp = ipha->ipha_src;
1690 		ipha->ipha_src = ipha->ipha_dst;
1691 		ipha->ipha_dst = tmp;
1692 	}
1693 	ipha->ipha_ident = 0;
1694 	if (!IS_SIMPLE_IPH(ipha))
1695 		icmp_options_update(ipha);
1696 
1697 	bzero(&ixas, sizeof (ixas));
1698 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
1699 	ixas.ixa_zoneid = ira->ira_zoneid;
1700 	ixas.ixa_cred = kcred;
1701 	ixas.ixa_cpid = NOPID;
1702 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
1703 	ixas.ixa_ifindex = 0;
1704 	ixas.ixa_ipst = ipst;
1705 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1706 
1707 	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
1708 		/*
1709 		 * This packet should go out the same way as it
1710 		 * came in i.e in clear, independent of the IPsec policy
1711 		 * for transmitting packets.
1712 		 */
1713 		ixas.ixa_flags |= IXAF_NO_IPSEC;
1714 	} else {
1715 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
1716 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1717 			/* Note: mp already consumed and ip_drop_packet done */
1718 			return;
1719 		}
1720 	}
1721 	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
1722 		/*
1723 		 * Not one or our addresses (IRE_LOCALs), thus we let
1724 		 * ip_output_simple pick the source.
1725 		 */
1726 		ipha->ipha_src = INADDR_ANY;
1727 		ixas.ixa_flags |= IXAF_SET_SOURCE;
1728 	}
1729 	/* Should we send with DF and use dce_pmtu? */
1730 	if (ipst->ips_ipv4_icmp_return_pmtu) {
1731 		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
1732 		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
1733 	}
1734 
1735 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
1736 
1737 	(void) ip_output_simple(mp, &ixas);
1738 	ixa_cleanup(&ixas);
1739 }
1740 
1741 /*
1742  * Verify the ICMP messages for either for ICMP error or redirect packet.
1743  * The caller should have fully pulled up the message. If it's a redirect
1744  * packet, only basic checks on IP header will be done; otherwise, verify
1745  * the packet by looking at the included ULP header.
1746  *
1747  * Called before icmp_inbound_error_fanout_v4 is called.
1748  */
1749 static boolean_t
1750 icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
1751 {
1752 	ill_t		*ill = ira->ira_ill;
1753 	int		hdr_length;
1754 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
1755 	conn_t		*connp;
1756 	ipha_t		*ipha;	/* Inner IP header */
1757 
1758 	ipha = (ipha_t *)&icmph[1];
1759 	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
1760 		goto truncated;
1761 
1762 	hdr_length = IPH_HDR_LENGTH(ipha);
1763 
1764 	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
1765 		goto discard_pkt;
1766 
1767 	if (hdr_length < sizeof (ipha_t))
1768 		goto truncated;
1769 
1770 	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
1771 		goto truncated;
1772 
1773 	/*
1774 	 * Stop here for ICMP_REDIRECT.
1775 	 */
1776 	if (icmph->icmph_type == ICMP_REDIRECT)
1777 		return (B_TRUE);
1778 
1779 	/*
1780 	 * ICMP errors only.
1781 	 */
1782 	switch (ipha->ipha_protocol) {
1783 	case IPPROTO_UDP:
1784 		/*
1785 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1786 		 * transport header.
1787 		 */
1788 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1789 		    mp->b_wptr)
1790 			goto truncated;
1791 		break;
1792 	case IPPROTO_TCP: {
1793 		tcpha_t		*tcpha;
1794 
1795 		/*
1796 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1797 		 * transport header.
1798 		 */
1799 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1800 		    mp->b_wptr)
1801 			goto truncated;
1802 
1803 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
1804 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
1805 		    ipst);
1806 		if (connp == NULL)
1807 			goto discard_pkt;
1808 
1809 		if ((connp->conn_verifyicmp != NULL) &&
1810 		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
1811 			CONN_DEC_REF(connp);
1812 			goto discard_pkt;
1813 		}
1814 		CONN_DEC_REF(connp);
1815 		break;
1816 	}
1817 	case IPPROTO_SCTP:
1818 		/*
1819 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
1820 		 * transport header.
1821 		 */
1822 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
1823 		    mp->b_wptr)
1824 			goto truncated;
1825 		break;
1826 	case IPPROTO_ESP:
1827 	case IPPROTO_AH:
1828 		break;
1829 	case IPPROTO_ENCAP:
1830 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
1831 		    mp->b_wptr)
1832 			goto truncated;
1833 		break;
1834 	default:
1835 		break;
1836 	}
1837 
1838 	return (B_TRUE);
1839 
1840 discard_pkt:
1841 	/* Bogus ICMP error. */
1842 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1843 	return (B_FALSE);
1844 
1845 truncated:
1846 	/* We pulled up everthing already. Must be truncated */
1847 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
1848 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
1849 	return (B_FALSE);
1850 }
1851 
1852 /* Table from RFC 1191 */
1853 static int icmp_frag_size_table[] =
1854 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
1855 
1856 /*
1857  * Process received ICMP Packet too big.
1858  * Just handles the DCE create/update, including using the above table of
1859  * PMTU guesses. The caller is responsible for validating the packet before
1860  * passing it in and also to fanout the ICMP error to any matching transport
1861  * conns. Assumes the message has been fully pulled up and verified.
1862  *
1863  * Before getting here, the caller has called icmp_inbound_verify_v4()
1864  * that should have verified with ULP to prevent undoing the changes we're
1865  * going to make to DCE. For example, TCP might have verified that the packet
1866  * which generated error is in the send window.
1867  *
1868  * In some cases modified this MTU in the ICMP header packet; the caller
1869  * should pass to the matching ULP after this returns.
1870  */
1871 static void
1872 icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
1873 {
1874 	dce_t		*dce;
1875 	int		old_mtu;
1876 	int		mtu, orig_mtu;
1877 	ipaddr_t	dst;
1878 	boolean_t	disable_pmtud;
1879 	ill_t		*ill = ira->ira_ill;
1880 	ip_stack_t	*ipst = ill->ill_ipst;
1881 	uint_t		hdr_length;
1882 	ipha_t		*ipha;
1883 
1884 	/* Caller already pulled up everything. */
1885 	ipha = (ipha_t *)&icmph[1];
1886 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
1887 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
1888 	ASSERT(ill != NULL);
1889 
1890 	hdr_length = IPH_HDR_LENGTH(ipha);
1891 
1892 	/*
1893 	 * We handle path MTU for source routed packets since the DCE
1894 	 * is looked up using the final destination.
1895 	 */
1896 	dst = ip_get_dst(ipha);
1897 
1898 	dce = dce_lookup_and_add_v4(dst, ipst);
1899 	if (dce == NULL) {
1900 		/* Couldn't add a unique one - ENOMEM */
1901 		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
1902 		    ntohl(dst)));
1903 		return;
1904 	}
1905 
1906 	/* Check for MTU discovery advice as described in RFC 1191 */
1907 	mtu = ntohs(icmph->icmph_du_mtu);
1908 	orig_mtu = mtu;
1909 	disable_pmtud = B_FALSE;
1910 
1911 	mutex_enter(&dce->dce_lock);
1912 	if (dce->dce_flags & DCEF_PMTU)
1913 		old_mtu = dce->dce_pmtu;
1914 	else
1915 		old_mtu = ill->ill_mtu;
1916 
1917 	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
1918 		uint32_t length;
1919 		int	i;
1920 
1921 		/*
1922 		 * Use the table from RFC 1191 to figure out
1923 		 * the next "plateau" based on the length in
1924 		 * the original IP packet.
1925 		 */
1926 		length = ntohs(ipha->ipha_length);
1927 		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
1928 		    uint32_t, length);
1929 		if (old_mtu <= length &&
1930 		    old_mtu >= length - hdr_length) {
1931 			/*
1932 			 * Handle broken BSD 4.2 systems that
1933 			 * return the wrong ipha_length in ICMP
1934 			 * errors.
1935 			 */
1936 			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
1937 			    length, old_mtu));
1938 			length -= hdr_length;
1939 		}
1940 		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
1941 			if (length > icmp_frag_size_table[i])
1942 				break;
1943 		}
1944 		if (i == A_CNT(icmp_frag_size_table)) {
1945 			/* Smaller than IP_MIN_MTU! */
1946 			ip1dbg(("Too big for packet size %d\n",
1947 			    length));
1948 			disable_pmtud = B_TRUE;
1949 			mtu = ipst->ips_ip_pmtu_min;
1950 		} else {
1951 			mtu = icmp_frag_size_table[i];
1952 			ip1dbg(("Calculated mtu %d, packet size %d, "
1953 			    "before %d\n", mtu, length, old_mtu));
1954 			if (mtu < ipst->ips_ip_pmtu_min) {
1955 				mtu = ipst->ips_ip_pmtu_min;
1956 				disable_pmtud = B_TRUE;
1957 			}
1958 		}
1959 	}
1960 	if (disable_pmtud)
1961 		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
1962 	else
1963 		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;
1964 
1965 	dce->dce_pmtu = MIN(old_mtu, mtu);
1966 	/* Prepare to send the new max frag size for the ULP. */
1967 	icmph->icmph_du_zero = 0;
1968 	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
1969 	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
1970 	    dce, int, orig_mtu, int, mtu);
1971 
1972 	/* We now have a PMTU for sure */
1973 	dce->dce_flags |= DCEF_PMTU;
1974 	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
1975 	mutex_exit(&dce->dce_lock);
1976 	/*
1977 	 * After dropping the lock the new value is visible to everyone.
1978 	 * Then we bump the generation number so any cached values reinspect
1979 	 * the dce_t.
1980 	 */
1981 	dce_increment_generation(dce);
1982 	dce_refrele(dce);
1983 }
1984 
1985 /*
1986  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
1987  * calls this function.
1988  */
1989 static mblk_t *
1990 icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
1991 {
1992 	int length;
1993 
1994 	ASSERT(mp->b_datap->db_type == M_DATA);
1995 
1996 	/* icmp_inbound_v4 has already pulled up the whole error packet */
1997 	ASSERT(mp->b_cont == NULL);
1998 
1999 	/*
2000 	 * The length that we want to overlay is the inner header
2001 	 * and what follows it.
2002 	 */
2003 	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);
2004 
2005 	/*
2006 	 * Overlay the inner header and whatever follows it over the
2007 	 * outer header.
2008 	 */
2009 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2010 
2011 	/* Adjust for what we removed */
2012 	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
2013 	return (mp);
2014 }
2015 
2016 /*
2017  * Try to pass the ICMP message upstream in case the ULP cares.
2018  *
2019  * If the packet that caused the ICMP error is secure, we send
2020  * it to AH/ESP to make sure that the attached packet has a
2021  * valid association. ipha in the code below points to the
2022  * IP header of the packet that caused the error.
2023  *
2024  * For IPsec cases, we let the next-layer-up (which has access to
2025  * cached policy on the conn_t, or can query the SPD directly)
2026  * subtract out any IPsec overhead if they must.  We therefore make no
2027  * adjustments here for IPsec overhead.
2028  *
2029  * IFN could have been generated locally or by some router.
2030  *
2031  * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
2032  * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
2033  *	    This happens because IP adjusted its value of MTU on an
2034  *	    earlier IFN message and could not tell the upper layer,
2035  *	    the new adjusted value of MTU e.g. Packet was encrypted
2036  *	    or there was not enough information to fanout to upper
2037  *	    layers. Thus on the next outbound datagram, ire_send_wire
2038  *	    generates the IFN, where IPsec processing has *not* been
2039  *	    done.
2040  *
2041  *	    Note that we retain ixa_fragsize across IPsec thus once
2042  *	    we have picking ixa_fragsize and entered ipsec_out_process we do
2043  *	    no change the fragsize even if the path MTU changes before
2044  *	    we reach ip_output_post_ipsec.
2045  *
2046  *	    In the local case, IRAF_LOOPBACK will be set indicating
2047  *	    that IFN was generated locally.
2048  *
2049  * ROUTER : IFN could be secure or non-secure.
2050  *
2051  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2052  *	      packet in error has AH/ESP headers to validate the AH/ESP
2053  *	      headers. AH/ESP will verify whether there is a valid SA or
2054  *	      not and send it back. We will fanout again if we have more
2055  *	      data in the packet.
2056  *
2057  *	      If the packet in error does not have AH/ESP, we handle it
2058  *	      like any other case.
2059  *
2060  *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
2061  *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
2062  *	      valid SA or not and send it back. We will fanout again if
2063  *	      we have more data in the packet.
2064  *
2065  *	      If the packet in error does not have AH/ESP, we handle it
2066  *	      like any other case.
2067  *
2068  * The caller must have called icmp_inbound_verify_v4.
2069  */
2070 static void
2071 icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
2072 {
2073 	uint16_t	*up;	/* Pointer to ports in ULP header */
2074 	uint32_t	ports;	/* reversed ports for fanout */
2075 	ipha_t		ripha;	/* With reversed addresses */
2076 	ipha_t		*ipha;  /* Inner IP header */
2077 	uint_t		hdr_length; /* Inner IP header length */
2078 	tcpha_t		*tcpha;
2079 	conn_t		*connp;
2080 	ill_t		*ill = ira->ira_ill;
2081 	ip_stack_t	*ipst = ill->ill_ipst;
2082 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
2083 	ill_t		*rill = ira->ira_rill;
2084 
2085 	/* Caller already pulled up everything. */
2086 	ipha = (ipha_t *)&icmph[1];
2087 	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
2088 	ASSERT(mp->b_cont == NULL);
2089 
2090 	hdr_length = IPH_HDR_LENGTH(ipha);
2091 	ira->ira_protocol = ipha->ipha_protocol;
2092 
2093 	/*
2094 	 * We need a separate IP header with the source and destination
2095 	 * addresses reversed to do fanout/classification because the ipha in
2096 	 * the ICMP error is in the form we sent it out.
2097 	 */
2098 	ripha.ipha_src = ipha->ipha_dst;
2099 	ripha.ipha_dst = ipha->ipha_src;
2100 	ripha.ipha_protocol = ipha->ipha_protocol;
2101 	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;
2102 
2103 	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
2104 	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2105 	    ntohl(ipha->ipha_dst),
2106 	    icmph->icmph_type, icmph->icmph_code));
2107 
2108 	switch (ipha->ipha_protocol) {
2109 	case IPPROTO_UDP:
2110 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2111 
2112 		/* Attempt to find a client stream based on port. */
2113 		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
2114 		    ntohs(up[0]), ntohs(up[1])));
2115 
2116 		/* Note that we send error to all matches. */
2117 		ira->ira_flags |= IRAF_ICMP_ERROR;
2118 		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
2119 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2120 		return;
2121 
2122 	case IPPROTO_TCP:
2123 		/*
2124 		 * Find a TCP client stream for this packet.
2125 		 * Note that we do a reverse lookup since the header is
2126 		 * in the form we sent it out.
2127 		 */
2128 		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
2129 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
2130 		    ipst);
2131 		if (connp == NULL)
2132 			goto discard_pkt;
2133 
2134 		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
2135 		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
2136 			mp = ipsec_check_inbound_policy(mp, connp,
2137 			    ipha, NULL, ira);
2138 			if (mp == NULL) {
2139 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2140 				/* Note that mp is NULL */
2141 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
2142 				CONN_DEC_REF(connp);
2143 				return;
2144 			}
2145 		}
2146 
2147 		ira->ira_flags |= IRAF_ICMP_ERROR;
2148 		ira->ira_ill = ira->ira_rill = NULL;
2149 		if (IPCL_IS_TCP(connp)) {
2150 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
2151 			    connp->conn_recvicmp, connp, ira, SQ_FILL,
2152 			    SQTAG_TCP_INPUT_ICMP_ERR);
2153 		} else {
2154 			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
2155 			(connp->conn_recv)(connp, mp, NULL, ira);
2156 			CONN_DEC_REF(connp);
2157 		}
2158 		ira->ira_ill = ill;
2159 		ira->ira_rill = rill;
2160 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2161 		return;
2162 
2163 	case IPPROTO_SCTP:
2164 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2165 		/* Find a SCTP client stream for this packet. */
2166 		((uint16_t *)&ports)[0] = up[1];
2167 		((uint16_t *)&ports)[1] = up[0];
2168 
2169 		ira->ira_flags |= IRAF_ICMP_ERROR;
2170 		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
2171 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2172 		return;
2173 
2174 	case IPPROTO_ESP:
2175 	case IPPROTO_AH:
2176 		if (!ipsec_loaded(ipss)) {
2177 			ip_proto_not_sup(mp, ira);
2178 			return;
2179 		}
2180 
2181 		if (ipha->ipha_protocol == IPPROTO_ESP)
2182 			mp = ipsecesp_icmp_error(mp, ira);
2183 		else
2184 			mp = ipsecah_icmp_error(mp, ira);
2185 		if (mp == NULL)
2186 			return;
2187 
2188 		/* Just in case ipsec didn't preserve the NULL b_cont */
2189 		if (mp->b_cont != NULL) {
2190 			if (!pullupmsg(mp, -1))
2191 				goto discard_pkt;
2192 		}
2193 
2194 		/*
2195 		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
2196 		 * correct, but we don't use them any more here.
2197 		 *
2198 		 * If succesful, the mp has been modified to not include
2199 		 * the ESP/AH header so we can fanout to the ULP's icmp
2200 		 * error handler.
2201 		 */
2202 		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2203 			goto truncated;
2204 
2205 		/* Verify the modified message before any further processes. */
2206 		ipha = (ipha_t *)mp->b_rptr;
2207 		hdr_length = IPH_HDR_LENGTH(ipha);
2208 		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2209 		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2210 			freemsg(mp);
2211 			return;
2212 		}
2213 
2214 		icmp_inbound_error_fanout_v4(mp, icmph, ira);
2215 		return;
2216 
2217 	case IPPROTO_ENCAP: {
2218 		/* Look for self-encapsulated packets that caused an error */
2219 		ipha_t *in_ipha;
2220 
2221 		/*
2222 		 * Caller has verified that length has to be
2223 		 * at least the size of IP header.
2224 		 */
2225 		ASSERT(hdr_length >= sizeof (ipha_t));
2226 		/*
2227 		 * Check the sanity of the inner IP header like
2228 		 * we did for the outer header.
2229 		 */
2230 		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2231 		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2232 			goto discard_pkt;
2233 		}
2234 		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2235 			goto discard_pkt;
2236 		}
2237 		/* Check for Self-encapsulated tunnels */
2238 		if (in_ipha->ipha_src == ipha->ipha_src &&
2239 		    in_ipha->ipha_dst == ipha->ipha_dst) {
2240 
2241 			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
2242 			    in_ipha);
2243 			if (mp == NULL)
2244 				goto discard_pkt;
2245 
2246 			/*
2247 			 * Just in case self_encap didn't preserve the NULL
2248 			 * b_cont
2249 			 */
2250 			if (mp->b_cont != NULL) {
2251 				if (!pullupmsg(mp, -1))
2252 					goto discard_pkt;
2253 			}
2254 			/*
2255 			 * Note that ira_pktlen and ira_ip_hdr_length are no
2256 			 * longer correct, but we don't use them any more here.
2257 			 */
2258 			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
2259 				goto truncated;
2260 
2261 			/*
2262 			 * Verify the modified message before any further
2263 			 * processes.
2264 			 */
2265 			ipha = (ipha_t *)mp->b_rptr;
2266 			hdr_length = IPH_HDR_LENGTH(ipha);
2267 			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
2268 			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
2269 				freemsg(mp);
2270 				return;
2271 			}
2272 
2273 			/*
2274 			 * The packet in error is self-encapsualted.
2275 			 * And we are finding it further encapsulated
2276 			 * which we could not have possibly generated.
2277 			 */
2278 			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2279 				goto discard_pkt;
2280 			}
2281 			icmp_inbound_error_fanout_v4(mp, icmph, ira);
2282 			return;
2283 		}
2284 		/* No self-encapsulated */
2285 		/* FALLTHRU */
2286 	}
2287 	case IPPROTO_IPV6:
2288 		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
2289 		    &ripha.ipha_dst, ipst)) != NULL) {
2290 			ira->ira_flags |= IRAF_ICMP_ERROR;
2291 			connp->conn_recvicmp(connp, mp, NULL, ira);
2292 			CONN_DEC_REF(connp);
2293 			ira->ira_flags &= ~IRAF_ICMP_ERROR;
2294 			return;
2295 		}
2296 		/*
2297 		 * No IP tunnel is interested, fallthrough and see
2298 		 * if a raw socket will want it.
2299 		 */
2300 		/* FALLTHRU */
2301 	default:
2302 		ira->ira_flags |= IRAF_ICMP_ERROR;
2303 		ip_fanout_proto_v4(mp, &ripha, ira);
2304 		ira->ira_flags &= ~IRAF_ICMP_ERROR;
2305 		return;
2306 	}
2307 	/* NOTREACHED */
2308 discard_pkt:
2309 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2310 	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
2311 	ip_drop_input("ipIfStatsInDiscards", mp, ill);
2312 	freemsg(mp);
2313 	return;
2314 
2315 truncated:
2316 	/* We pulled up everthing already. Must be truncated */
2317 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
2318 	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
2319 	freemsg(mp);
2320 }
2321 
2322 /*
2323  * Common IP options parser.
2324  *
2325  * Setup routine: fill in *optp with options-parsing state, then
2326  * tail-call ipoptp_next to return the first option.
2327  */
2328 uint8_t
2329 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2330 {
2331 	uint32_t totallen; /* total length of all options */
2332 
2333 	totallen = ipha->ipha_version_and_hdr_length -
2334 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2335 	totallen <<= 2;
2336 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2337 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2338 	optp->ipoptp_flags = 0;
2339 	return (ipoptp_next(optp));
2340 }
2341 
2342 /* Like above but without an ipha_t */
2343 uint8_t
2344 ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
2345 {
2346 	optp->ipoptp_next = opt;
2347 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2348 	optp->ipoptp_flags = 0;
2349 	return (ipoptp_next(optp));
2350 }
2351 
2352 /*
2353  * Common IP options parser: extract next option.
2354  */
2355 uint8_t
2356 ipoptp_next(ipoptp_t *optp)
2357 {
2358 	uint8_t *end = optp->ipoptp_end;
2359 	uint8_t *cur = optp->ipoptp_next;
2360 	uint8_t opt, len, pointer;
2361 
2362 	/*
2363 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2364 	 * has been corrupted.
2365 	 */
2366 	ASSERT(cur <= end);
2367 
2368 	if (cur == end)
2369 		return (IPOPT_EOL);
2370 
2371 	opt = cur[IPOPT_OPTVAL];
2372 
2373 	/*
2374 	 * Skip any NOP options.
2375 	 */
2376 	while (opt == IPOPT_NOP) {
2377 		cur++;
2378 		if (cur == end)
2379 			return (IPOPT_EOL);
2380 		opt = cur[IPOPT_OPTVAL];
2381 	}
2382 
2383 	if (opt == IPOPT_EOL)
2384 		return (IPOPT_EOL);
2385 
2386 	/*
2387 	 * Option requiring a length.
2388 	 */
2389 	if ((cur + 1) >= end) {
2390 		optp->ipoptp_flags |= IPOPTP_ERROR;
2391 		return (IPOPT_EOL);
2392 	}
2393 	len = cur[IPOPT_OLEN];
2394 	if (len < 2) {
2395 		optp->ipoptp_flags |= IPOPTP_ERROR;
2396 		return (IPOPT_EOL);
2397 	}
2398 	optp->ipoptp_cur = cur;
2399 	optp->ipoptp_len = len;
2400 	optp->ipoptp_next = cur + len;
2401 	if (cur + len > end) {
2402 		optp->ipoptp_flags |= IPOPTP_ERROR;
2403 		return (IPOPT_EOL);
2404 	}
2405 
2406 	/*
2407 	 * For the options which require a pointer field, make sure
2408 	 * its there, and make sure it points to either something
2409 	 * inside this option, or the end of the option.
2410 	 */
2411 	switch (opt) {
2412 	case IPOPT_RR:
2413 	case IPOPT_TS:
2414 	case IPOPT_LSRR:
2415 	case IPOPT_SSRR:
2416 		if (len <= IPOPT_OFFSET) {
2417 			optp->ipoptp_flags |= IPOPTP_ERROR;
2418 			return (opt);
2419 		}
2420 		pointer = cur[IPOPT_OFFSET];
2421 		if (pointer - 1 > len) {
2422 			optp->ipoptp_flags |= IPOPTP_ERROR;
2423 			return (opt);
2424 		}
2425 		break;
2426 	}
2427 
2428 	/*
2429 	 * Sanity check the pointer field based on the type of the
2430 	 * option.
2431 	 */
2432 	switch (opt) {
2433 	case IPOPT_RR:
2434 	case IPOPT_SSRR:
2435 	case IPOPT_LSRR:
2436 		if (pointer < IPOPT_MINOFF_SR)
2437 			optp->ipoptp_flags |= IPOPTP_ERROR;
2438 		break;
2439 	case IPOPT_TS:
2440 		if (pointer < IPOPT_MINOFF_IT)
2441 			optp->ipoptp_flags |= IPOPTP_ERROR;
2442 		/*
2443 		 * Note that the Internet Timestamp option also
2444 		 * contains two four bit fields (the Overflow field,
2445 		 * and the Flag field), which follow the pointer
2446 		 * field.  We don't need to check that these fields
2447 		 * fall within the length of the option because this
2448 		 * was implicitely done above.  We've checked that the
2449 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2450 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2451 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2452 		 */
2453 		ASSERT(len > IPOPT_POS_OV_FLG);
2454 		break;
2455 	}
2456 
2457 	return (opt);
2458 }
2459 
2460 /*
2461  * Use the outgoing IP header to create an IP_OPTIONS option the way
2462  * it was passed down from the application.
2463  *
2464  * This is compatible with BSD in that it returns
2465  * the reverse source route with the final destination
2466  * as the last entry. The first 4 bytes of the option
2467  * will contain the final destination.
2468  */
2469 int
2470 ip_opt_get_user(conn_t *connp, uchar_t *buf)
2471 {
2472 	ipoptp_t	opts;
2473 	uchar_t		*opt;
2474 	uint8_t		optval;
2475 	uint8_t		optlen;
2476 	uint32_t	len = 0;
2477 	uchar_t		*buf1 = buf;
2478 	uint32_t	totallen;
2479 	ipaddr_t	dst;
2480 	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;
2481 
2482 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
2483 		return (0);
2484 
2485 	totallen = ipp->ipp_ipv4_options_len;
2486 	if (totallen & 0x3)
2487 		return (0);
2488 
2489 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2490 	len += IP_ADDR_LEN;
2491 	bzero(buf1, IP_ADDR_LEN);
2492 
2493 	dst = connp->conn_faddr_v4;
2494 
2495 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
2496 	    optval != IPOPT_EOL;
2497 	    optval = ipoptp_next(&opts)) {
2498 		int	off;
2499 
2500 		opt = opts.ipoptp_cur;
2501 		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
2502 			break;
2503 		}
2504 		optlen = opts.ipoptp_len;
2505 
2506 		switch (optval) {
2507 		case IPOPT_SSRR:
2508 		case IPOPT_LSRR:
2509 
2510 			/*
2511 			 * Insert destination as the first entry in the source
2512 			 * route and move down the entries on step.
2513 			 * The last entry gets placed at buf1.
2514 			 */
2515 			buf[IPOPT_OPTVAL] = optval;
2516 			buf[IPOPT_OLEN] = optlen;
2517 			buf[IPOPT_OFFSET] = optlen;
2518 
2519 			off = optlen - IP_ADDR_LEN;
2520 			if (off < 0) {
2521 				/* No entries in source route */
2522 				break;
2523 			}
2524 			/* Last entry in source route if not already set */
2525 			if (dst == INADDR_ANY)
2526 				bcopy(opt + off, buf1, IP_ADDR_LEN);
2527 			off -= IP_ADDR_LEN;
2528 
2529 			while (off > 0) {
2530 				bcopy(opt + off,
2531 				    buf + off + IP_ADDR_LEN,
2532 				    IP_ADDR_LEN);
2533 				off -= IP_ADDR_LEN;
2534 			}
2535 			/* ipha_dst into first slot */
2536 			bcopy(&dst, buf + off + IP_ADDR_LEN,
2537 			    IP_ADDR_LEN);
2538 			buf += optlen;
2539 			len += optlen;
2540 			break;
2541 
2542 		default:
2543 			bcopy(opt, buf, optlen);
2544 			buf += optlen;
2545 			len += optlen;
2546 			break;
2547 		}
2548 	}
2549 done:
2550 	/* Pad the resulting options */
2551 	while (len & 0x3) {
2552 		*buf++ = IPOPT_EOL;
2553 		len++;
2554 	}
2555 	return (len);
2556 }
2557 
2558 /*
2559  * Update any record route or timestamp options to include this host.
2560  * Reverse any source route option.
2561  * This routine assumes that the options are well formed i.e. that they
2562  * have already been checked.
2563  */
2564 static void
2565 icmp_options_update(ipha_t *ipha)
2566 {
2567 	ipoptp_t	opts;
2568 	uchar_t		*opt;
2569 	uint8_t		optval;
2570 	ipaddr_t	src;		/* Our local address */
2571 	ipaddr_t	dst;
2572 
2573 	ip2dbg(("icmp_options_update\n"));
2574 	src = ipha->ipha_src;
2575 	dst = ipha->ipha_dst;
2576 
2577 	for (optval = ipoptp_first(&opts, ipha);
2578 	    optval != IPOPT_EOL;
2579 	    optval = ipoptp_next(&opts)) {
2580 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2581 		opt = opts.ipoptp_cur;
2582 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2583 		    optval, opts.ipoptp_len));
2584 		switch (optval) {
2585 			int off1, off2;
2586 		case IPOPT_SSRR:
2587 		case IPOPT_LSRR:
2588 			/*
2589 			 * Reverse the source route.  The first entry
2590 			 * should be the next to last one in the current
2591 			 * source route (the last entry is our address).
2592 			 * The last entry should be the final destination.
2593 			 */
2594 			off1 = IPOPT_MINOFF_SR - 1;
2595 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2596 			if (off2 < 0) {
2597 				/* No entries in source route */
2598 				ip1dbg((
2599 				    "icmp_options_update: bad src route\n"));
2600 				break;
2601 			}
2602 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
2603 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
2604 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
2605 			off2 -= IP_ADDR_LEN;
2606 
2607 			while (off1 < off2) {
2608 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
2609 				bcopy((char *)opt + off2, (char *)opt + off1,
2610 				    IP_ADDR_LEN);
2611 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
2612 				off1 += IP_ADDR_LEN;
2613 				off2 -= IP_ADDR_LEN;
2614 			}
2615 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
2616 			break;
2617 		}
2618 	}
2619 }
2620 
2621 /*
2622  * Process received ICMP Redirect messages.
2623  * Assumes the caller has verified that the headers are in the pulled up mblk.
2624  * Consumes mp.
2625  */
2626 static void
2627 icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
2628 {
2629 	ire_t		*ire, *nire;
2630 	ire_t		*prev_ire;
2631 	ipaddr_t  	src, dst, gateway;
2632 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2633 	ipha_t		*inner_ipha;	/* Inner IP header */
2634 
2635 	/* Caller already pulled up everything. */
2636 	inner_ipha = (ipha_t *)&icmph[1];
2637 	src = ipha->ipha_src;
2638 	dst = inner_ipha->ipha_dst;
2639 	gateway = icmph->icmph_rd_gateway;
2640 	/* Make sure the new gateway is reachable somehow. */
2641 	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
2642 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
2643 	/*
2644 	 * Make sure we had a route for the dest in question and that
2645 	 * that route was pointing to the old gateway (the source of the
2646 	 * redirect packet.)
2647 	 * We do longest match and then compare ire_gateway_addr below.
2648 	 */
2649 	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
2650 	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
2651 	/*
2652 	 * Check that
2653 	 *	the redirect was not from ourselves
2654 	 *	the new gateway and the old gateway are directly reachable
2655 	 */
2656 	if (prev_ire == NULL || ire == NULL ||
2657 	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
2658 	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
2659 	    !(ire->ire_type & IRE_IF_ALL) ||
2660 	    prev_ire->ire_gateway_addr != src) {
2661 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2662 		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
2663 		freemsg(mp);
2664 		if (ire != NULL)
2665 			ire_refrele(ire);
2666 		if (prev_ire != NULL)
2667 			ire_refrele(prev_ire);
2668 		return;
2669 	}
2670 
2671 	ire_refrele(prev_ire);
2672 	ire_refrele(ire);
2673 
2674 	/*
2675 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
2676 	 * require TOS routing
2677 	 */
2678 	switch (icmph->icmph_code) {
2679 	case 0:
2680 	case 1:
2681 		/* TODO: TOS specificity for cases 2 and 3 */
2682 	case 2:
2683 	case 3:
2684 		break;
2685 	default:
2686 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
2687 		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
2688 		freemsg(mp);
2689 		return;
2690 	}
2691 	/*
2692 	 * Create a Route Association.  This will allow us to remember that
2693 	 * someone we believe told us to use the particular gateway.
2694 	 */
2695 	ire = ire_create(
2696 	    (uchar_t *)&dst,			/* dest addr */
2697 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2698 	    (uchar_t *)&gateway,		/* gateway addr */
2699 	    IRE_HOST,
2700 	    NULL,				/* ill */
2701 	    ALL_ZONES,
2702 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
2703 	    NULL,				/* tsol_gc_t */
2704 	    ipst);
2705 
2706 	if (ire == NULL) {
2707 		freemsg(mp);
2708 		return;
2709 	}
2710 	nire = ire_add(ire);
2711 	/* Check if it was a duplicate entry */
2712 	if (nire != NULL && nire != ire) {
2713 		ASSERT(nire->ire_identical_ref > 1);
2714 		ire_delete(nire);
2715 		ire_refrele(nire);
2716 		nire = NULL;
2717 	}
2718 	ire = nire;
2719 	if (ire != NULL) {
2720 		ire_refrele(ire);		/* Held in ire_add */
2721 
2722 		/* tell routing sockets that we received a redirect */
2723 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
2724 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
2725 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
2726 	}
2727 
2728 	/*
2729 	 * Delete any existing IRE_HOST type redirect ires for this destination.
2730 	 * This together with the added IRE has the effect of
2731 	 * modifying an existing redirect.
2732 	 */
2733 	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
2734 	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
2735 	if (prev_ire != NULL) {
2736 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
2737 			ire_delete(prev_ire);
2738 		ire_refrele(prev_ire);
2739 	}
2740 
2741 	freemsg(mp);
2742 }
2743 
2744 /*
2745  * Generate an ICMP parameter problem message.
2746  * When called from ip_output side a minimal ip_recv_attr_t needs to be
2747  * constructed by the caller.
2748  */
2749 static void
2750 icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
2751 {
2752 	icmph_t	icmph;
2753 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2754 
2755 	mp = icmp_pkt_err_ok(mp, ira);
2756 	if (mp == NULL)
2757 		return;
2758 
2759 	bzero(&icmph, sizeof (icmph_t));
2760 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
2761 	icmph.icmph_pp_ptr = ptr;
2762 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
2763 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
2764 }
2765 
2766 /*
2767  * Build and ship an IPv4 ICMP message using the packet data in mp, and
2768  * the ICMP header pointed to by "stuff".  (May be called as writer.)
2769  * Note: assumes that icmp_pkt_err_ok has been called to verify that
2770  * an icmp error packet can be sent.
2771  * Assigns an appropriate source address to the packet. If ipha_dst is
2772  * one of our addresses use it for source. Otherwise let ip_output_simple
2773  * pick the source address.
2774  */
2775 static void
2776 icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
2777 {
2778 	ipaddr_t dst;
2779 	icmph_t	*icmph;
2780 	ipha_t	*ipha;
2781 	uint_t	len_needed;
2782 	size_t	msg_len;
2783 	mblk_t	*mp1;
2784 	ipaddr_t src;
2785 	ire_t	*ire;
2786 	ip_xmit_attr_t ixas;
2787 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
2788 
2789 	ipha = (ipha_t *)mp->b_rptr;
2790 
2791 	bzero(&ixas, sizeof (ixas));
2792 	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
2793 	ixas.ixa_zoneid = ira->ira_zoneid;
2794 	ixas.ixa_ifindex = 0;
2795 	ixas.ixa_ipst = ipst;
2796 	ixas.ixa_cred = kcred;
2797 	ixas.ixa_cpid = NOPID;
2798 	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
2799 	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
2800 
2801 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
2802 		/*
2803 		 * Apply IPsec based on how IPsec was applied to
2804 		 * the packet that had the error.
2805 		 *
2806 		 * If it was an outbound packet that caused the ICMP
2807 		 * error, then the caller will have setup the IRA
2808 		 * appropriately.
2809 		 */
2810 		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
2811 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2812 			/* Note: mp already consumed and ip_drop_packet done */
2813 			return;
2814 		}
2815 	} else {
2816 		/*
2817 		 * This is in clear. The icmp message we are building
2818 		 * here should go out in clear, independent of our policy.
2819 		 */
2820 		ixas.ixa_flags |= IXAF_NO_IPSEC;
2821 	}
2822 
2823 	/* Remember our eventual destination */
2824 	dst = ipha->ipha_src;
2825 
2826 	/*
2827 	 * If the packet was for one of our unicast addresses, make
2828 	 * sure we respond with that as the source. Otherwise
2829 	 * have ip_output_simple pick the source address.
2830 	 */
2831 	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
2832 	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
2833 	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
2834 	if (ire != NULL) {
2835 		ire_refrele(ire);
2836 		src = ipha->ipha_dst;
2837 	} else {
2838 		src = INADDR_ANY;
2839 		ixas.ixa_flags |= IXAF_SET_SOURCE;
2840 	}
2841 
2842 	/*
2843 	 * Check if we can send back more then 8 bytes in addition to
2844 	 * the IP header.  We try to send 64 bytes of data and the internal
2845 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
2846 	 */
2847 	len_needed = IPH_HDR_LENGTH(ipha);
2848 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
2849 	    ipha->ipha_protocol == IPPROTO_IPV6) {
2850 		if (!pullupmsg(mp, -1)) {
2851 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
2852 			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
2853 			freemsg(mp);
2854 			return;
2855 		}
2856 		ipha = (ipha_t *)mp->b_rptr;
2857 
2858 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2859 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
2860 			    len_needed));
2861 		} else {
2862 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
2863 
2864 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
2865 			len_needed += ip_hdr_length_v6(mp, ip6h);
2866 		}
2867 	}
2868 	len_needed += ipst->ips_ip_icmp_return;
2869 	msg_len = msgdsize(mp);
2870 	if (msg_len > len_needed) {
2871 		(void) adjmsg(mp, len_needed - msg_len);
2872 		msg_len = len_needed;
2873 	}
2874 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
2875 	if (mp1 == NULL) {
2876 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
2877 		freemsg(mp);
2878 		return;
2879 	}
2880 	mp1->b_cont = mp;
2881 	mp = mp1;
2882 
2883 	/*
2884 	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
2885 	 * node generates be accepted in peace by all on-host destinations.
2886 	 * If we do NOT assume that all on-host destinations trust
2887 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
2888 	 * (Look for IXAF_TRUSTED_ICMP).
2889 	 */
2890 	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;
2891 
2892 	ipha = (ipha_t *)mp->b_rptr;
2893 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
2894 	*ipha = icmp_ipha;
2895 	ipha->ipha_src = src;
2896 	ipha->ipha_dst = dst;
2897 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2898 	msg_len += sizeof (icmp_ipha) + len;
2899 	if (msg_len > IP_MAXPACKET) {
2900 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
2901 		msg_len = IP_MAXPACKET;
2902 	}
2903 	ipha->ipha_length = htons((uint16_t)msg_len);
2904 	icmph = (icmph_t *)&ipha[1];
2905 	bcopy(stuff, icmph, len);
2906 	icmph->icmph_checksum = 0;
2907 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
2908 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2909 
2910 	(void) ip_output_simple(mp, &ixas);
2911 	ixa_cleanup(&ixas);
2912 }
2913 
2914 /*
2915  * Determine if an ICMP error packet can be sent given the rate limit.
2916  * The limit consists of an average frequency (icmp_pkt_err_interval measured
2917  * in milliseconds) and a burst size. Burst size number of packets can
2918  * be sent arbitrarely closely spaced.
2919  * The state is tracked using two variables to implement an approximate
2920  * token bucket filter:
2921  *	icmp_pkt_err_last - lbolt value when the last burst started
2922  *	icmp_pkt_err_sent - number of packets sent in current burst
2923  */
2924 boolean_t
2925 icmp_err_rate_limit(ip_stack_t *ipst)
2926 {
2927 	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
2928 	uint_t refilled; /* Number of packets refilled in tbf since last */
2929 	/* Guard against changes by loading into local variable */
2930 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
2931 
2932 	if (err_interval == 0)
2933 		return (B_FALSE);
2934 
2935 	if (ipst->ips_icmp_pkt_err_last > now) {
2936 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
2937 		ipst->ips_icmp_pkt_err_last = 0;
2938 		ipst->ips_icmp_pkt_err_sent = 0;
2939 	}
2940 	/*
2941 	 * If we are in a burst update the token bucket filter.
2942 	 * Update the "last" time to be close to "now" but make sure
2943 	 * we don't loose precision.
2944 	 */
2945 	if (ipst->ips_icmp_pkt_err_sent != 0) {
2946 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
2947 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
2948 			ipst->ips_icmp_pkt_err_sent = 0;
2949 		} else {
2950 			ipst->ips_icmp_pkt_err_sent -= refilled;
2951 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
2952 		}
2953 	}
2954 	if (ipst->ips_icmp_pkt_err_sent == 0) {
2955 		/* Start of new burst */
2956 		ipst->ips_icmp_pkt_err_last = now;
2957 	}
2958 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
2959 		ipst->ips_icmp_pkt_err_sent++;
2960 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
2961 		    ipst->ips_icmp_pkt_err_sent));
2962 		return (B_FALSE);
2963 	}
2964 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
2965 	return (B_TRUE);
2966 }
2967 
2968 /*
2969  * Check if it is ok to send an IPv4 ICMP error packet in
2970  * response to the IPv4 packet in mp.
2971  * Free the message and return null if no
2972  * ICMP error packet should be sent.
2973  */
2974 static mblk_t *
2975 icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
2976 {
2977 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
2978 	icmph_t	*icmph;
2979 	ipha_t	*ipha;
2980 	uint_t	len_needed;
2981 
2982 	if (!mp)
2983 		return (NULL);
2984 	ipha = (ipha_t *)mp->b_rptr;
2985 	if (ip_csum_hdr(ipha)) {
2986 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
2987 		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
2988 		freemsg(mp);
2989 		return (NULL);
2990 	}
2991 	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
2992 	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
2993 	    CLASSD(ipha->ipha_dst) ||
2994 	    CLASSD(ipha->ipha_src) ||
2995 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
2996 		/* Note: only errors to the fragment with offset 0 */
2997 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
2998 		freemsg(mp);
2999 		return (NULL);
3000 	}
3001 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3002 		/*
3003 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3004 		 * errors in response to any ICMP errors.
3005 		 */
3006 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3007 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3008 			if (!pullupmsg(mp, len_needed)) {
3009 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3010 				freemsg(mp);
3011 				return (NULL);
3012 			}
3013 			ipha = (ipha_t *)mp->b_rptr;
3014 		}
3015 		icmph = (icmph_t *)
3016 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3017 		switch (icmph->icmph_type) {
3018 		case ICMP_DEST_UNREACHABLE:
3019 		case ICMP_SOURCE_QUENCH:
3020 		case ICMP_TIME_EXCEEDED:
3021 		case ICMP_PARAM_PROBLEM:
3022 		case ICMP_REDIRECT:
3023 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3024 			freemsg(mp);
3025 			return (NULL);
3026 		default:
3027 			break;
3028 		}
3029 	}
3030 	/*
3031 	 * If this is a labeled system, then check to see if we're allowed to
3032 	 * send a response to this particular sender.  If not, then just drop.
3033 	 */
3034 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
3035 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3036 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3037 		freemsg(mp);
3038 		return (NULL);
3039 	}
3040 	if (icmp_err_rate_limit(ipst)) {
3041 		/*
3042 		 * Only send ICMP error packets every so often.
3043 		 * This should be done on a per port/source basis,
3044 		 * but for now this will suffice.
3045 		 */
3046 		freemsg(mp);
3047 		return (NULL);
3048 	}
3049 	return (mp);
3050 }
3051 
3052 /*
3053  * Called when a packet was sent out the same link that it arrived on.
3054  * Check if it is ok to send a redirect and then send it.
3055  */
3056 void
3057 ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
3058     ip_recv_attr_t *ira)
3059 {
3060 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
3061 	ipaddr_t	src, nhop;
3062 	mblk_t		*mp1;
3063 	ire_t		*nhop_ire;
3064 
3065 	/*
3066 	 * Check the source address to see if it originated
3067 	 * on the same logical subnet it is going back out on.
3068 	 * If so, we should be able to send it a redirect.
3069 	 * Avoid sending a redirect if the destination
3070 	 * is directly connected (i.e., we matched an IRE_ONLINK),
3071 	 * or if the packet was source routed out this interface.
3072 	 *
3073 	 * We avoid sending a redirect if the
3074 	 * destination is directly connected
3075 	 * because it is possible that multiple
3076 	 * IP subnets may have been configured on
3077 	 * the link, and the source may not
3078 	 * be on the same subnet as ip destination,
3079 	 * even though they are on the same
3080 	 * physical link.
3081 	 */
3082 	if ((ire->ire_type & IRE_ONLINK) ||
3083 	    ip_source_routed(ipha, ipst))
3084 		return;
3085 
3086 	nhop_ire = ire_nexthop(ire);
3087 	if (nhop_ire == NULL)
3088 		return;
3089 
3090 	nhop = nhop_ire->ire_addr;
3091 
3092 	if (nhop_ire->ire_type & IRE_IF_CLONE) {
3093 		ire_t	*ire2;
3094 
3095 		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
3096 		mutex_enter(&nhop_ire->ire_lock);
3097 		ire2 = nhop_ire->ire_dep_parent;
3098 		if (ire2 != NULL)
3099 			ire_refhold(ire2);
3100 		mutex_exit(&nhop_ire->ire_lock);
3101 		ire_refrele(nhop_ire);
3102 		nhop_ire = ire2;
3103 	}
3104 	if (nhop_ire == NULL)
3105 		return;
3106 
3107 	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));
3108 
3109 	src = ipha->ipha_src;
3110 
3111 	/*
3112 	 * We look at the interface ire for the nexthop,
3113 	 * to see if ipha_src is in the same subnet
3114 	 * as the nexthop.
3115 	 */
3116 	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
3117 		/*
3118 		 * The source is directly connected.
3119 		 */
3120 		mp1 = copymsg(mp);
3121 		if (mp1 != NULL) {
3122 			icmp_send_redirect(mp1, nhop, ira);
3123 		}
3124 	}
3125 	ire_refrele(nhop_ire);
3126 }
3127 
3128 /*
3129  * Generate an ICMP redirect message.
3130  */
3131 static void
3132 icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
3133 {
3134 	icmph_t	icmph;
3135 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3136 
3137 	mp = icmp_pkt_err_ok(mp, ira);
3138 	if (mp == NULL)
3139 		return;
3140 
3141 	bzero(&icmph, sizeof (icmph_t));
3142 	icmph.icmph_type = ICMP_REDIRECT;
3143 	icmph.icmph_code = 1;
3144 	icmph.icmph_rd_gateway = gateway;
3145 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3146 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3147 }
3148 
3149 /*
3150  * Generate an ICMP time exceeded message.
3151  */
3152 void
3153 icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3154 {
3155 	icmph_t	icmph;
3156 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3157 
3158 	mp = icmp_pkt_err_ok(mp, ira);
3159 	if (mp == NULL)
3160 		return;
3161 
3162 	bzero(&icmph, sizeof (icmph_t));
3163 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3164 	icmph.icmph_code = code;
3165 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3166 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3167 }
3168 
3169 /*
3170  * Generate an ICMP unreachable message.
3171  * When called from ip_output side a minimal ip_recv_attr_t needs to be
3172  * constructed by the caller.
3173  */
3174 void
3175 icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
3176 {
3177 	icmph_t	icmph;
3178 	ip_stack_t *ipst = ira->ira_ill->ill_ipst;
3179 
3180 	mp = icmp_pkt_err_ok(mp, ira);
3181 	if (mp == NULL)
3182 		return;
3183 
3184 	bzero(&icmph, sizeof (icmph_t));
3185 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3186 	icmph.icmph_code = code;
3187 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3188 	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
3189 }
3190 
3191 /*
3192  * Latch in the IPsec state for a stream based the policy in the listener
3193  * and the actions in the ip_recv_attr_t.
3194  * Called directly from TCP and SCTP.
3195  */
3196 boolean_t
3197 ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
3198 {
3199 	ASSERT(lconnp->conn_policy != NULL);
3200 	ASSERT(connp->conn_policy == NULL);
3201 
3202 	IPPH_REFHOLD(lconnp->conn_policy);
3203 	connp->conn_policy = lconnp->conn_policy;
3204 
3205 	if (ira->ira_ipsec_action != NULL) {
3206 		if (connp->conn_latch == NULL) {
3207 			connp->conn_latch = iplatch_create();
3208 			if (connp->conn_latch == NULL)
3209 				return (B_FALSE);
3210 		}
3211 		ipsec_latch_inbound(connp, ira);
3212 	}
3213 	return (B_TRUE);
3214 }
3215 
3216 /*
3217  * Verify whether or not the IP address is a valid local address.
3218  * Could be a unicast, including one for a down interface.
3219  * If allow_mcbc then a multicast or broadcast address is also
3220  * acceptable.
3221  *
3222  * In the case of a broadcast/multicast address, however, the
3223  * upper protocol is expected to reset the src address
3224  * to zero when we return IPVL_MCAST/IPVL_BCAST so that
3225  * no packets are emitted with broadcast/multicast address as
3226  * source address (that violates hosts requirements RFC 1122)
3227  * The addresses valid for bind are:
3228  *	(1) - INADDR_ANY (0)
3229  *	(2) - IP address of an UP interface
3230  *	(3) - IP address of a DOWN interface
3231  *	(4) - valid local IP broadcast addresses. In this case
3232  *	the conn will only receive packets destined to
3233  *	the specified broadcast address.
3234  *	(5) - a multicast address. In this case
3235  *	the conn will only receive packets destined to
3236  *	the specified multicast address. Note: the
3237  *	application still has to issue an
3238  *	IP_ADD_MEMBERSHIP socket option.
3239  *
3240  * In all the above cases, the bound address must be valid in the current zone.
3241  * When the address is loopback, multicast or broadcast, there might be many
3242  * matching IREs so bind has to look up based on the zone.
3243  */
3244 ip_laddr_t
3245 ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
3246     ip_stack_t *ipst, boolean_t allow_mcbc)
3247 {
3248 	ire_t *src_ire;
3249 
3250 	ASSERT(src_addr != INADDR_ANY);
3251 
3252 	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
3253 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);
3254 
3255 	/*
3256 	 * If an address other than in6addr_any is requested,
3257 	 * we verify that it is a valid address for bind
3258 	 * Note: Following code is in if-else-if form for
3259 	 * readability compared to a condition check.
3260 	 */
3261 	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
3262 		/*
3263 		 * (2) Bind to address of local UP interface
3264 		 */
3265 		ire_refrele(src_ire);
3266 		return (IPVL_UNICAST_UP);
3267 	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
3268 		/*
3269 		 * (4) Bind to broadcast address
3270 		 */
3271 		ire_refrele(src_ire);
3272 		if (allow_mcbc)
3273 			return (IPVL_BCAST);
3274 		else
3275 			return (IPVL_BAD);
3276 	} else if (CLASSD(src_addr)) {
3277 		/* (5) bind to multicast address. */
3278 		if (src_ire != NULL)
3279 			ire_refrele(src_ire);
3280 
3281 		if (allow_mcbc)
3282 			return (IPVL_MCAST);
3283 		else
3284 			return (IPVL_BAD);
3285 	} else {
3286 		ipif_t *ipif;
3287 
3288 		/*
3289 		 * (3) Bind to address of local DOWN interface?
3290 		 * (ipif_lookup_addr() looks up all interfaces
3291 		 * but we do not get here for UP interfaces
3292 		 * - case (2) above)
3293 		 */
3294 		if (src_ire != NULL)
3295 			ire_refrele(src_ire);
3296 
3297 		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
3298 		if (ipif == NULL)
3299 			return (IPVL_BAD);
3300 
3301 		/* Not a useful source? */
3302 		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
3303 			ipif_refrele(ipif);
3304 			return (IPVL_BAD);
3305 		}
3306 		ipif_refrele(ipif);
3307 		return (IPVL_UNICAST_DOWN);
3308 	}
3309 }
3310 
3311 /*
3312  * Insert in the bind fanout for IPv4 and IPv6.
3313  * The caller should already have used ip_laddr_verify_v*() before calling
3314  * this.
3315  */
3316 int
3317 ip_laddr_fanout_insert(conn_t *connp)
3318 {
3319 	int		error;
3320 
3321 	/*
3322 	 * Allow setting new policies. For example, disconnects result
3323 	 * in us being called. As we would have set conn_policy_cached
3324 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
3325 	 * can change after the disconnect.
3326 	 */
3327 	connp->conn_policy_cached = B_FALSE;
3328 
3329 	error = ipcl_bind_insert(connp);
3330 	if (error != 0) {
3331 		if (connp->conn_anon_port) {
3332 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
3333 			    connp->conn_mlp_type, connp->conn_proto,
3334 			    ntohs(connp->conn_lport), B_FALSE);
3335 		}
3336 		connp->conn_mlp_type = mlptSingle;
3337 	}
3338 	return (error);
3339 }
3340 
3341 /*
3342  * Verify that both the source and destination addresses are valid. If
3343  * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
3344  * i.e. have no route to it.  Protocols like TCP want to verify destination
3345  * reachability, while tunnels do not.
3346  *
3347  * Determine the route, the interface, and (optionally) the source address
3348  * to use to reach a given destination.
3349  * Note that we allow connect to broadcast and multicast addresses when
3350  * IPDF_ALLOW_MCBC is set.
3351  * first_hop and dst_addr are normally the same, but if source routing
3352  * they will differ; in that case the first_hop is what we'll use for the
3353  * routing lookup but the dce and label checks will be done on dst_addr,
3354  *
3355  * If uinfo is set, then we fill in the best available information
3356  * we have for the destination. This is based on (in priority order) any
3357  * metrics and path MTU stored in a dce_t, route metrics, and finally the
3358  * ill_mtu/ill_mc_mtu.
3359  *
3360  * Tsol note: If we have a source route then dst_addr != firsthop. But we
3361  * always do the label check on dst_addr.
3362  */
3363 int
3364 ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
3365     ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
3366 {
3367 	ire_t		*ire = NULL;
3368 	int		error = 0;
3369 	ipaddr_t	setsrc;				/* RTF_SETSRC */
3370 	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
3371 	ip_stack_t	*ipst = ixa->ixa_ipst;
3372 	dce_t		*dce;
3373 	uint_t		pmtu;
3374 	uint_t		generation;
3375 	nce_t		*nce;
3376 	ill_t		*ill = NULL;
3377 	boolean_t	multirt = B_FALSE;
3378 
3379 	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);
3380 
3381 	/*
3382 	 * We never send to zero; the ULPs map it to the loopback address.
3383 	 * We can't allow it since we use zero to mean unitialized in some
3384 	 * places.
3385 	 */
3386 	ASSERT(dst_addr != INADDR_ANY);
3387 
3388 	if (is_system_labeled()) {
3389 		ts_label_t *tsl = NULL;
3390 
3391 		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
3392 		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
3393 		if (error != 0)
3394 			return (error);
3395 		if (tsl != NULL) {
3396 			/* Update the label */
3397 			ip_xmit_attr_replace_tsl(ixa, tsl);
3398 		}
3399 	}
3400 
3401 	setsrc = INADDR_ANY;
3402 	/*
3403 	 * Select a route; For IPMP interfaces, we would only select
3404 	 * a "hidden" route (i.e., going through a specific under_ill)
3405 	 * if ixa_ifindex has been specified.
3406 	 */
3407 	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
3408 	    &generation, &setsrc, &error, &multirt);
3409 	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
3410 	if (error != 0)
3411 		goto bad_addr;
3412 
3413 	/*
3414 	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
3415 	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
3416 	 * Otherwise the destination needn't be reachable.
3417 	 *
3418 	 * If we match on a reject or black hole, then we've got a
3419 	 * local failure.  May as well fail out the connect() attempt,
3420 	 * since it's never going to succeed.
3421 	 */
3422 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
3423 		/*
3424 		 * If we're verifying destination reachability, we always want
3425 		 * to complain here.
3426 		 *
3427 		 * If we're not verifying destination reachability but the
3428 		 * destination has a route, we still want to fail on the
3429 		 * temporary address and broadcast address tests.
3430 		 *
3431 		 * In both cases do we let the code continue so some reasonable
3432 		 * information is returned to the caller. That enables the
3433 		 * caller to use (and even cache) the IRE. conn_ip_ouput will
3434 		 * use the generation mismatch path to check for the unreachable
3435 		 * case thereby avoiding any specific check in the main path.
3436 		 */
3437 		ASSERT(generation == IRE_GENERATION_VERIFY);
3438 		if (flags & IPDF_VERIFY_DST) {
3439 			/*
3440 			 * Set errno but continue to set up ixa_ire to be
3441 			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
3442 			 * That allows callers to use ip_output to get an
3443 			 * ICMP error back.
3444 			 */
3445 			if (!(ire->ire_type & IRE_HOST))
3446 				error = ENETUNREACH;
3447 			else
3448 				error = EHOSTUNREACH;
3449 		}
3450 	}
3451 
3452 	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
3453 	    !(flags & IPDF_ALLOW_MCBC)) {
3454 		ire_refrele(ire);
3455 		ire = ire_reject(ipst, B_FALSE);
3456 		generation = IRE_GENERATION_VERIFY;
3457 		error = ENETUNREACH;
3458 	}
3459 
3460 	/* Cache things */
3461 	if (ixa->ixa_ire != NULL)
3462 		ire_refrele_notr(ixa->ixa_ire);
3463 #ifdef DEBUG
3464 	ire_refhold_notr(ire);
3465 	ire_refrele(ire);
3466 #endif
3467 	ixa->ixa_ire = ire;
3468 	ixa->ixa_ire_generation = generation;
3469 
3470 	/*
3471 	 * Ensure that ixa_dce is always set any time that ixa_ire is set,
3472 	 * since some callers will send a packet to conn_ip_output() even if
3473 	 * there's an error.
3474 	 */
3475 	if (flags & IPDF_UNIQUE_DCE) {
3476 		/* Fallback to the default dce if allocation fails */
3477 		dce = dce_lookup_and_add_v4(dst_addr, ipst);
3478 		if (dce != NULL)
3479 			generation = dce->dce_generation;
3480 		else
3481 			dce = dce_lookup_v4(dst_addr, ipst, &generation);
3482 	} else {
3483 		dce = dce_lookup_v4(dst_addr, ipst, &generation);
3484 	}
3485 	ASSERT(dce != NULL);
3486 	if (ixa->ixa_dce != NULL)
3487 		dce_refrele_notr(ixa->ixa_dce);
3488 #ifdef DEBUG
3489 	dce_refhold_notr(dce);
3490 	dce_refrele(dce);
3491 #endif
3492 	ixa->ixa_dce = dce;
3493 	ixa->ixa_dce_generation = generation;
3494 
3495 	/*
3496 	 * For multicast with multirt we have a flag passed back from
3497 	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
3498 	 * possible multicast address.
3499 	 * We also need a flag for multicast since we can't check
3500 	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
3501 	 */
3502 	if (multirt) {
3503 		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
3504 		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
3505 	} else {
3506 		ixa->ixa_postfragfn = ire->ire_postfragfn;
3507 		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
3508 	}
3509 	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3510 		/* Get an nce to cache. */
3511 		nce = ire_to_nce(ire, firsthop, NULL);
3512 		if (nce == NULL) {
3513 			/* Allocation failure? */
3514 			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3515 		} else {
3516 			if (ixa->ixa_nce != NULL)
3517 				nce_refrele(ixa->ixa_nce);
3518 			ixa->ixa_nce = nce;
3519 		}
3520 	}
3521 
3522 	/*
3523 	 * If the source address is a loopback address, the
3524 	 * destination had best be local or multicast.
3525 	 * If we are sending to an IRE_LOCAL using a loopback source then
3526 	 * it had better be the same zoneid.
3527 	 */
3528 	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
3529 		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
3530 			ire = NULL;	/* Stored in ixa_ire */
3531 			error = EADDRNOTAVAIL;
3532 			goto bad_addr;
3533 		}
3534 		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
3535 			ire = NULL;	/* Stored in ixa_ire */
3536 			error = EADDRNOTAVAIL;
3537 			goto bad_addr;
3538 		}
3539 	}
3540 	if (ire->ire_type & IRE_BROADCAST) {
3541 		/*
3542 		 * If the ULP didn't have a specified source, then we
3543 		 * make sure we reselect the source when sending
3544 		 * broadcasts out different interfaces.
3545 		 */
3546 		if (flags & IPDF_SELECT_SRC)
3547 			ixa->ixa_flags |= IXAF_SET_SOURCE;
3548 		else
3549 			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
3550 	}
3551 
3552 	/*
3553 	 * Does the caller want us to pick a source address?
3554 	 */
3555 	if (flags & IPDF_SELECT_SRC) {
3556 		ipaddr_t	src_addr;
3557 
3558 		/*
3559 		 * We use use ire_nexthop_ill to avoid the under ipmp
3560 		 * interface for source address selection. Note that for ipmp
3561 		 * probe packets, ixa_ifindex would have been specified, and
3562 		 * the ip_select_route() invocation would have picked an ire
3563 		 * will ire_ill pointing at an under interface.
3564 		 */
3565 		ill = ire_nexthop_ill(ire);
3566 
3567 		/* If unreachable we have no ill but need some source */
3568 		if (ill == NULL) {
3569 			src_addr = htonl(INADDR_LOOPBACK);
3570 			/* Make sure we look for a better source address */
3571 			generation = SRC_GENERATION_VERIFY;
3572 		} else {
3573 			error = ip_select_source_v4(ill, setsrc, dst_addr,
3574 			    ixa->ixa_multicast_ifaddr, zoneid,
3575 			    ipst, &src_addr, &generation, NULL);
3576 			if (error != 0) {
3577 				ire = NULL;	/* Stored in ixa_ire */
3578 				goto bad_addr;
3579 			}
3580 		}
3581 
3582 		/*
3583 		 * We allow the source address to to down.
3584 		 * However, we check that we don't use the loopback address
3585 		 * as a source when sending out on the wire.
3586 		 */
3587 		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
3588 		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
3589 		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
3590 			ire = NULL;	/* Stored in ixa_ire */
3591 			error = EADDRNOTAVAIL;
3592 			goto bad_addr;
3593 		}
3594 
3595 		*src_addrp = src_addr;
3596 		ixa->ixa_src_generation = generation;
3597 	}
3598 
3599 	/*
3600 	 * Make sure we don't leave an unreachable ixa_nce in place
3601 	 * since ip_select_route is used when we unplumb i.e., remove
3602 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3603 	 */
3604 	nce = ixa->ixa_nce;
3605 	if (nce != NULL && nce->nce_is_condemned) {
3606 		nce_refrele(nce);
3607 		ixa->ixa_nce = NULL;
3608 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3609 	}
3610 
3611 	/*
3612 	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
3613 	 * However, we can't do it for IPv4 multicast or broadcast.
3614 	 */
3615 	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
3616 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3617 
3618 	/*
3619 	 * Set initial value for fragmentation limit. Either conn_ip_output
3620 	 * or ULP might updates it when there are routing changes.
3621 	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
3622 	 */
3623 	pmtu = ip_get_pmtu(ixa);
3624 	ixa->ixa_fragsize = pmtu;
3625 	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
3626 	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
3627 		ixa->ixa_pmtu = pmtu;
3628 
3629 	/*
3630 	 * Extract information useful for some transports.
3631 	 * First we look for DCE metrics. Then we take what we have in
3632 	 * the metrics in the route, where the offlink is used if we have
3633 	 * one.
3634 	 */
3635 	if (uinfo != NULL) {
3636 		bzero(uinfo, sizeof (*uinfo));
3637 
3638 		if (dce->dce_flags & DCEF_UINFO)
3639 			*uinfo = dce->dce_uinfo;
3640 
3641 		rts_merge_metrics(uinfo, &ire->ire_metrics);
3642 
3643 		/* Allow ire_metrics to decrease the path MTU from above */
3644 		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
3645 			uinfo->iulp_mtu = pmtu;
3646 
3647 		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
3648 		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
3649 		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
3650 	}
3651 
3652 	if (ill != NULL)
3653 		ill_refrele(ill);
3654 
3655 	return (error);
3656 
3657 bad_addr:
3658 	if (ire != NULL)
3659 		ire_refrele(ire);
3660 
3661 	if (ill != NULL)
3662 		ill_refrele(ill);
3663 
3664 	/*
3665 	 * Make sure we don't leave an unreachable ixa_nce in place
3666 	 * since ip_select_route is used when we unplumb i.e., remove
3667 	 * references on ixa_ire, ixa_nce, and ixa_dce.
3668 	 */
3669 	nce = ixa->ixa_nce;
3670 	if (nce != NULL && nce->nce_is_condemned) {
3671 		nce_refrele(nce);
3672 		ixa->ixa_nce = NULL;
3673 		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
3674 	}
3675 
3676 	return (error);
3677 }
3678 
3679 
3680 /*
3681  * Get the base MTU for the case when path MTU discovery is not used.
3682  * Takes the MTU of the IRE into account.
3683  */
3684 uint_t
3685 ip_get_base_mtu(ill_t *ill, ire_t *ire)
3686 {
3687 	uint_t mtu;
3688 	uint_t iremtu = ire->ire_metrics.iulp_mtu;
3689 
3690 	if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST))
3691 		mtu = ill->ill_mc_mtu;
3692 	else
3693 		mtu = ill->ill_mtu;
3694 
3695 	if (iremtu != 0 && iremtu < mtu)
3696 		mtu = iremtu;
3697 
3698 	return (mtu);
3699 }
3700 
3701 /*
3702  * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
3703  * Assumes that ixa_ire, dce, and nce have already been set up.
3704  *
3705  * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
3706  * We avoid path MTU discovery if it is disabled with ndd.
3707  * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
3708  *
3709  * NOTE: We also used to turn it off for source routed packets. That
3710  * is no longer required since the dce is per final destination.
3711  */
3712 uint_t
3713 ip_get_pmtu(ip_xmit_attr_t *ixa)
3714 {
3715 	ip_stack_t	*ipst = ixa->ixa_ipst;
3716 	dce_t		*dce;
3717 	nce_t		*nce;
3718 	ire_t		*ire;
3719 	uint_t		pmtu;
3720 
3721 	ire = ixa->ixa_ire;
3722 	dce = ixa->ixa_dce;
3723 	nce = ixa->ixa_nce;
3724 
3725 	/*
3726 	 * If path MTU discovery has been turned off by ndd, then we ignore
3727 	 * any dce_pmtu and for IPv4 we will not set DF.
3728 	 */
3729 	if (!ipst->ips_ip_path_mtu_discovery)
3730 		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;
3731 
3732 	pmtu = IP_MAXPACKET;
3733 	/*
3734 	 * Decide whether whether IPv4 sets DF
3735 	 * For IPv6 "no DF" means to use the 1280 mtu
3736 	 */
3737 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3738 		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3739 	} else {
3740 		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3741 		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
3742 			pmtu = IPV6_MIN_MTU;
3743 	}
3744 
3745 	/* Check if the PMTU is to old before we use it */
3746 	if ((dce->dce_flags & DCEF_PMTU) &&
3747 	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
3748 	    ipst->ips_ip_pathmtu_interval) {
3749 		/*
3750 		 * Older than 20 minutes. Drop the path MTU information.
3751 		 */
3752 		mutex_enter(&dce->dce_lock);
3753 		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
3754 		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
3755 		mutex_exit(&dce->dce_lock);
3756 		dce_increment_generation(dce);
3757 	}
3758 
3759 	/* The metrics on the route can lower the path MTU */
3760 	if (ire->ire_metrics.iulp_mtu != 0 &&
3761 	    ire->ire_metrics.iulp_mtu < pmtu)
3762 		pmtu = ire->ire_metrics.iulp_mtu;
3763 
3764 	/*
3765 	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
3766 	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
3767 	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
3768 	 */
3769 	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
3770 		if (dce->dce_flags & DCEF_PMTU) {
3771 			if (dce->dce_pmtu < pmtu)
3772 				pmtu = dce->dce_pmtu;
3773 
3774 			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
3775 				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
3776 				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
3777 			} else {
3778 				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3779 				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3780 			}
3781 		} else {
3782 			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
3783 			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
3784 		}
3785 	}
3786 
3787 	/*
3788 	 * If we have an IRE_LOCAL we use the loopback mtu instead of
3789 	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
3790 	 * mtu as IRE_LOOPBACK.
3791 	 */
3792 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3793 		uint_t loopback_mtu;
3794 
3795 		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
3796 		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;
3797 
3798 		if (loopback_mtu < pmtu)
3799 			pmtu = loopback_mtu;
3800 	} else if (nce != NULL) {
3801 		/*
3802 		 * Make sure we don't exceed the interface MTU.
3803 		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
3804 		 * an ill. We'd use the above IP_MAXPACKET in that case just
3805 		 * to tell the transport something larger than zero.
3806 		 */
3807 		if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST)) {
3808 			if (nce->nce_common->ncec_ill->ill_mc_mtu < pmtu)
3809 				pmtu = nce->nce_common->ncec_ill->ill_mc_mtu;
3810 			if (nce->nce_common->ncec_ill != nce->nce_ill &&
3811 			    nce->nce_ill->ill_mc_mtu < pmtu) {
3812 				/*
3813 				 * for interfaces in an IPMP group, the mtu of
3814 				 * the nce_ill (under_ill) could be different
3815 				 * from the mtu of the ncec_ill, so we take the
3816 				 * min of the two.
3817 				 */
3818 				pmtu = nce->nce_ill->ill_mc_mtu;
3819 			}
3820 		} else {
3821 			if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
3822 				pmtu = nce->nce_common->ncec_ill->ill_mtu;
3823 			if (nce->nce_common->ncec_ill != nce->nce_ill &&
3824 			    nce->nce_ill->ill_mtu < pmtu) {
3825 				/*
3826 				 * for interfaces in an IPMP group, the mtu of
3827 				 * the nce_ill (under_ill) could be different
3828 				 * from the mtu of the ncec_ill, so we take the
3829 				 * min of the two.
3830 				 */
3831 				pmtu = nce->nce_ill->ill_mtu;
3832 			}
3833 		}
3834 	}
3835 
3836 	/*
3837 	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
3838 	 * Only applies to IPv6.
3839 	 */
3840 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3841 		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
3842 			switch (ixa->ixa_use_min_mtu) {
3843 			case IPV6_USE_MIN_MTU_MULTICAST:
3844 				if (ire->ire_type & IRE_MULTICAST)
3845 					pmtu = IPV6_MIN_MTU;
3846 				break;
3847 			case IPV6_USE_MIN_MTU_ALWAYS:
3848 				pmtu = IPV6_MIN_MTU;
3849 				break;
3850 			case IPV6_USE_MIN_MTU_NEVER:
3851 				break;
3852 			}
3853 		} else {
3854 			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
3855 			if (ire->ire_type & IRE_MULTICAST)
3856 				pmtu = IPV6_MIN_MTU;
3857 		}
3858 	}
3859 
3860 	/*
3861 	 * After receiving an ICMPv6 "packet too big" message with a
3862 	 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
3863 	 * will insert a 8-byte fragment header in every packet. We compensate
3864 	 * for those cases by returning a smaller path MTU to the ULP.
3865 	 *
3866 	 * In the case of CGTP then ip_output will add a fragment header.
3867 	 * Make sure there is room for it by telling a smaller number
3868 	 * to the transport.
3869 	 *
3870 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3871 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3872 	 * which is the size of the packets it can send.
3873 	 */
3874 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3875 		if ((dce->dce_flags & DCEF_TOO_SMALL_PMTU) ||
3876 		    (ire->ire_flags & RTF_MULTIRT) ||
3877 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3878 			pmtu -= sizeof (ip6_frag_t);
3879 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3880 		}
3881 	}
3882 
3883 	return (pmtu);
3884 }
3885 
3886 /*
3887  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3888  * the final piece where we don't.  Return a pointer to the first mblk in the
3889  * result, and update the pointer to the next mblk to chew on.  If anything
3890  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3891  * NULL pointer.
3892  */
3893 mblk_t *
3894 ip_carve_mp(mblk_t **mpp, ssize_t len)
3895 {
3896 	mblk_t	*mp0;
3897 	mblk_t	*mp1;
3898 	mblk_t	*mp2;
3899 
3900 	if (!len || !mpp || !(mp0 = *mpp))
3901 		return (NULL);
3902 	/* If we aren't going to consume the first mblk, we need a dup. */
3903 	if (mp0->b_wptr - mp0->b_rptr > len) {
3904 		mp1 = dupb(mp0);
3905 		if (mp1) {
3906 			/* Partition the data between the two mblks. */
3907 			mp1->b_wptr = mp1->b_rptr + len;
3908 			mp0->b_rptr = mp1->b_wptr;
3909 			/*
3910 			 * after adjustments if mblk not consumed is now
3911 			 * unaligned, try to align it. If this fails free
3912 			 * all messages and let upper layer recover.
3913 			 */
3914 			if (!OK_32PTR(mp0->b_rptr)) {
3915 				if (!pullupmsg(mp0, -1)) {
3916 					freemsg(mp0);
3917 					freemsg(mp1);
3918 					*mpp = NULL;
3919 					return (NULL);
3920 				}
3921 			}
3922 		}
3923 		return (mp1);
3924 	}
3925 	/* Eat through as many mblks as we need to get len bytes. */
3926 	len -= mp0->b_wptr - mp0->b_rptr;
3927 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3928 		if (mp2->b_wptr - mp2->b_rptr > len) {
3929 			/*
3930 			 * We won't consume the entire last mblk.  Like
3931 			 * above, dup and partition it.
3932 			 */
3933 			mp1->b_cont = dupb(mp2);
3934 			mp1 = mp1->b_cont;
3935 			if (!mp1) {
3936 				/*
3937 				 * Trouble.  Rather than go to a lot of
3938 				 * trouble to clean up, we free the messages.
3939 				 * This won't be any worse than losing it on
3940 				 * the wire.
3941 				 */
3942 				freemsg(mp0);
3943 				freemsg(mp2);
3944 				*mpp = NULL;
3945 				return (NULL);
3946 			}
3947 			mp1->b_wptr = mp1->b_rptr + len;
3948 			mp2->b_rptr = mp1->b_wptr;
3949 			/*
3950 			 * after adjustments if mblk not consumed is now
3951 			 * unaligned, try to align it. If this fails free
3952 			 * all messages and let upper layer recover.
3953 			 */
3954 			if (!OK_32PTR(mp2->b_rptr)) {
3955 				if (!pullupmsg(mp2, -1)) {
3956 					freemsg(mp0);
3957 					freemsg(mp2);
3958 					*mpp = NULL;
3959 					return (NULL);
3960 				}
3961 			}
3962 			*mpp = mp2;
3963 			return (mp0);
3964 		}
3965 		/* Decrement len by the amount we just got. */
3966 		len -= mp2->b_wptr - mp2->b_rptr;
3967 	}
3968 	/*
3969 	 * len should be reduced to zero now.  If not our caller has
3970 	 * screwed up.
3971 	 */
3972 	if (len) {
3973 		/* Shouldn't happen! */
3974 		freemsg(mp0);
3975 		*mpp = NULL;
3976 		return (NULL);
3977 	}
3978 	/*
3979 	 * We consumed up to exactly the end of an mblk.  Detach the part
3980 	 * we are returning from the rest of the chain.
3981 	 */
3982 	mp1->b_cont = NULL;
3983 	*mpp = mp2;
3984 	return (mp0);
3985 }
3986 
3987 /* The ill stream is being unplumbed. Called from ip_close */
3988 int
3989 ip_modclose(ill_t *ill)
3990 {
3991 	boolean_t success;
3992 	ipsq_t	*ipsq;
3993 	ipif_t	*ipif;
3994 	queue_t	*q = ill->ill_rq;
3995 	ip_stack_t	*ipst = ill->ill_ipst;
3996 	int	i;
3997 	arl_ill_common_t *ai = ill->ill_common;
3998 
3999 	/*
4000 	 * The punlink prior to this may have initiated a capability
4001 	 * negotiation. But ipsq_enter will block until that finishes or
4002 	 * times out.
4003 	 */
4004 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
4005 
4006 	/*
4007 	 * Open/close/push/pop is guaranteed to be single threaded
4008 	 * per stream by STREAMS. FS guarantees that all references
4009 	 * from top are gone before close is called. So there can't
4010 	 * be another close thread that has set CONDEMNED on this ill.
4011 	 * and cause ipsq_enter to return failure.
4012 	 */
4013 	ASSERT(success);
4014 	ipsq = ill->ill_phyint->phyint_ipsq;
4015 
4016 	/*
4017 	 * Mark it condemned. No new reference will be made to this ill.
4018 	 * Lookup functions will return an error. Threads that try to
4019 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4020 	 * that the refcnt will drop down to zero.
4021 	 */
4022 	mutex_enter(&ill->ill_lock);
4023 	ill->ill_state_flags |= ILL_CONDEMNED;
4024 	for (ipif = ill->ill_ipif; ipif != NULL;
4025 	    ipif = ipif->ipif_next) {
4026 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4027 	}
4028 	/*
4029 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4030 	 * returns  error if ILL_CONDEMNED is set
4031 	 */
4032 	cv_broadcast(&ill->ill_cv);
4033 	mutex_exit(&ill->ill_lock);
4034 
4035 	/*
4036 	 * Send all the deferred DLPI messages downstream which came in
4037 	 * during the small window right before ipsq_enter(). We do this
4038 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4039 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4040 	 */
4041 	ill_dlpi_send_deferred(ill);
4042 
4043 	/*
4044 	 * Shut down fragmentation reassembly.
4045 	 * ill_frag_timer won't start a timer again.
4046 	 * Now cancel any existing timer
4047 	 */
4048 	(void) untimeout(ill->ill_frag_timer_id);
4049 	(void) ill_frag_timeout(ill, 0);
4050 
4051 	/*
4052 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4053 	 * this ill. Then wait for the refcnts to drop to zero.
4054 	 * ill_is_freeable checks whether the ill is really quiescent.
4055 	 * Then make sure that threads that are waiting to enter the
4056 	 * ipsq have seen the error returned by ipsq_enter and have
4057 	 * gone away. Then we call ill_delete_tail which does the
4058 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4059 	 */
4060 	ill_delete(ill);
4061 	mutex_enter(&ill->ill_lock);
4062 	while (!ill_is_freeable(ill))
4063 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4064 
4065 	while (ill->ill_waiters)
4066 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4067 
4068 	mutex_exit(&ill->ill_lock);
4069 
4070 	/*
4071 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4072 	 * it held until the end of the function since the cleanup
4073 	 * below needs to be able to use the ip_stack_t.
4074 	 */
4075 	netstack_hold(ipst->ips_netstack);
4076 
4077 	/* qprocsoff is done via ill_delete_tail */
4078 	ill_delete_tail(ill);
4079 	/*
4080 	 * synchronously wait for arp stream to unbind. After this, we
4081 	 * cannot get any data packets up from the driver.
4082 	 */
4083 	arp_unbind_complete(ill);
4084 	ASSERT(ill->ill_ipst == NULL);
4085 
4086 	/*
4087 	 * Walk through all conns and qenable those that have queued data.
4088 	 * Close synchronization needs this to
4089 	 * be done to ensure that all upper layers blocked
4090 	 * due to flow control to the closing device
4091 	 * get unblocked.
4092 	 */
4093 	ip1dbg(("ip_wsrv: walking\n"));
4094 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4095 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4096 	}
4097 
4098 	/*
4099 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4100 	 * stream is being torn down before ARP was plumbed (e.g.,
4101 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4102 	 * an error
4103 	 */
4104 	if (ai != NULL) {
4105 		ASSERT(!ill->ill_isv6);
4106 		mutex_enter(&ai->ai_lock);
4107 		ai->ai_ill = NULL;
4108 		if (ai->ai_arl == NULL) {
4109 			mutex_destroy(&ai->ai_lock);
4110 			kmem_free(ai, sizeof (*ai));
4111 		} else {
4112 			cv_signal(&ai->ai_ill_unplumb_done);
4113 			mutex_exit(&ai->ai_lock);
4114 		}
4115 	}
4116 
4117 	mutex_enter(&ipst->ips_ip_mi_lock);
4118 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4119 	mutex_exit(&ipst->ips_ip_mi_lock);
4120 
4121 	/*
4122 	 * credp could be null if the open didn't succeed and ip_modopen
4123 	 * itself calls ip_close.
4124 	 */
4125 	if (ill->ill_credp != NULL)
4126 		crfree(ill->ill_credp);
4127 
4128 	mutex_destroy(&ill->ill_saved_ire_lock);
4129 	mutex_destroy(&ill->ill_lock);
4130 	rw_destroy(&ill->ill_mcast_lock);
4131 	mutex_destroy(&ill->ill_mcast_serializer);
4132 	list_destroy(&ill->ill_nce);
4133 
4134 	/*
4135 	 * Now we are done with the module close pieces that
4136 	 * need the netstack_t.
4137 	 */
4138 	netstack_rele(ipst->ips_netstack);
4139 
4140 	mi_close_free((IDP)ill);
4141 	q->q_ptr = WR(q)->q_ptr = NULL;
4142 
4143 	ipsq_exit(ipsq);
4144 
4145 	return (0);
4146 }
4147 
4148 /*
4149  * This is called as part of close() for IP, UDP, ICMP, and RTS
4150  * in order to quiesce the conn.
4151  */
4152 void
4153 ip_quiesce_conn(conn_t *connp)
4154 {
4155 	boolean_t	drain_cleanup_reqd = B_FALSE;
4156 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4157 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4158 	ip_stack_t	*ipst;
4159 
4160 	ASSERT(!IPCL_IS_TCP(connp));
4161 	ipst = connp->conn_netstack->netstack_ip;
4162 
4163 	/*
4164 	 * Mark the conn as closing, and this conn must not be
4165 	 * inserted in future into any list. Eg. conn_drain_insert(),
4166 	 * won't insert this conn into the conn_drain_list.
4167 	 *
4168 	 * conn_idl, and conn_ilg cannot get set henceforth.
4169 	 */
4170 	mutex_enter(&connp->conn_lock);
4171 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4172 	connp->conn_state_flags |= CONN_CLOSING;
4173 	if (connp->conn_idl != NULL)
4174 		drain_cleanup_reqd = B_TRUE;
4175 	if (connp->conn_oper_pending_ill != NULL)
4176 		conn_ioctl_cleanup_reqd = B_TRUE;
4177 	if (connp->conn_dhcpinit_ill != NULL) {
4178 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4179 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4180 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4181 		connp->conn_dhcpinit_ill = NULL;
4182 	}
4183 	if (connp->conn_ilg != NULL)
4184 		ilg_cleanup_reqd = B_TRUE;
4185 	mutex_exit(&connp->conn_lock);
4186 
4187 	if (conn_ioctl_cleanup_reqd)
4188 		conn_ioctl_cleanup(connp);
4189 
4190 	if (is_system_labeled() && connp->conn_anon_port) {
4191 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4192 		    connp->conn_mlp_type, connp->conn_proto,
4193 		    ntohs(connp->conn_lport), B_FALSE);
4194 		connp->conn_anon_port = 0;
4195 	}
4196 	connp->conn_mlp_type = mlptSingle;
4197 
4198 	/*
4199 	 * Remove this conn from any fanout list it is on.
4200 	 * and then wait for any threads currently operating
4201 	 * on this endpoint to finish
4202 	 */
4203 	ipcl_hash_remove(connp);
4204 
4205 	/*
4206 	 * Remove this conn from the drain list, and do any other cleanup that
4207 	 * may be required.  (TCP conns are never flow controlled, and
4208 	 * conn_idl will be NULL.)
4209 	 */
4210 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4211 		idl_t *idl = connp->conn_idl;
4212 
4213 		mutex_enter(&idl->idl_lock);
4214 		conn_drain(connp, B_TRUE);
4215 		mutex_exit(&idl->idl_lock);
4216 	}
4217 
4218 	if (connp == ipst->ips_ip_g_mrouter)
4219 		(void) ip_mrouter_done(ipst);
4220 
4221 	if (ilg_cleanup_reqd)
4222 		ilg_delete_all(connp);
4223 
4224 	/*
4225 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4226 	 * callers from write side can't be there now because close
4227 	 * is in progress. The only other caller is ipcl_walk
4228 	 * which checks for the condemned flag.
4229 	 */
4230 	mutex_enter(&connp->conn_lock);
4231 	connp->conn_state_flags |= CONN_CONDEMNED;
4232 	while (connp->conn_ref != 1)
4233 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4234 	connp->conn_state_flags |= CONN_QUIESCED;
4235 	mutex_exit(&connp->conn_lock);
4236 }
4237 
4238 /* ARGSUSED */
4239 int
4240 ip_close(queue_t *q, int flags)
4241 {
4242 	conn_t		*connp;
4243 
4244 	/*
4245 	 * Call the appropriate delete routine depending on whether this is
4246 	 * a module or device.
4247 	 */
4248 	if (WR(q)->q_next != NULL) {
4249 		/* This is a module close */
4250 		return (ip_modclose((ill_t *)q->q_ptr));
4251 	}
4252 
4253 	connp = q->q_ptr;
4254 	ip_quiesce_conn(connp);
4255 
4256 	qprocsoff(q);
4257 
4258 	/*
4259 	 * Now we are truly single threaded on this stream, and can
4260 	 * delete the things hanging off the connp, and finally the connp.
4261 	 * We removed this connp from the fanout list, it cannot be
4262 	 * accessed thru the fanouts, and we already waited for the
4263 	 * conn_ref to drop to 0. We are already in close, so
4264 	 * there cannot be any other thread from the top. qprocsoff
4265 	 * has completed, and service has completed or won't run in
4266 	 * future.
4267 	 */
4268 	ASSERT(connp->conn_ref == 1);
4269 
4270 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4271 
4272 	connp->conn_ref--;
4273 	ipcl_conn_destroy(connp);
4274 
4275 	q->q_ptr = WR(q)->q_ptr = NULL;
4276 	return (0);
4277 }
4278 
4279 /*
4280  * Wapper around putnext() so that ip_rts_request can merely use
4281  * conn_recv.
4282  */
4283 /*ARGSUSED2*/
4284 static void
4285 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4286 {
4287 	conn_t *connp = (conn_t *)arg1;
4288 
4289 	putnext(connp->conn_rq, mp);
4290 }
4291 
4292 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4293 /* ARGSUSED */
4294 static void
4295 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4296 {
4297 	freemsg(mp);
4298 }
4299 
4300 /*
4301  * Called when the module is about to be unloaded
4302  */
4303 void
4304 ip_ddi_destroy(void)
4305 {
4306 	/* This needs to be called before destroying any transports. */
4307 	mutex_enter(&cpu_lock);
4308 	unregister_cpu_setup_func(ip_tp_cpu_update, NULL);
4309 	mutex_exit(&cpu_lock);
4310 
4311 	tnet_fini();
4312 
4313 	icmp_ddi_g_destroy();
4314 	rts_ddi_g_destroy();
4315 	udp_ddi_g_destroy();
4316 	sctp_ddi_g_destroy();
4317 	tcp_ddi_g_destroy();
4318 	ilb_ddi_g_destroy();
4319 	dce_g_destroy();
4320 	ipsec_policy_g_destroy();
4321 	ipcl_g_destroy();
4322 	ip_net_g_destroy();
4323 	ip_ire_g_fini();
4324 	inet_minor_destroy(ip_minor_arena_sa);
4325 #if defined(_LP64)
4326 	inet_minor_destroy(ip_minor_arena_la);
4327 #endif
4328 
4329 #ifdef DEBUG
4330 	list_destroy(&ip_thread_list);
4331 	rw_destroy(&ip_thread_rwlock);
4332 	tsd_destroy(&ip_thread_data);
4333 #endif
4334 
4335 	netstack_unregister(NS_IP);
4336 }
4337 
4338 /*
4339  * First step in cleanup.
4340  */
4341 /* ARGSUSED */
4342 static void
4343 ip_stack_shutdown(netstackid_t stackid, void *arg)
4344 {
4345 	ip_stack_t *ipst = (ip_stack_t *)arg;
4346 	kt_did_t ktid;
4347 
4348 #ifdef NS_DEBUG
4349 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4350 #endif
4351 
4352 	/*
4353 	 * Perform cleanup for special interfaces (loopback and IPMP).
4354 	 */
4355 	ip_interface_cleanup(ipst);
4356 
4357 	/*
4358 	 * The *_hook_shutdown()s start the process of notifying any
4359 	 * consumers that things are going away.... nothing is destroyed.
4360 	 */
4361 	ipv4_hook_shutdown(ipst);
4362 	ipv6_hook_shutdown(ipst);
4363 	arp_hook_shutdown(ipst);
4364 
4365 	mutex_enter(&ipst->ips_capab_taskq_lock);
4366 	ktid = ipst->ips_capab_taskq_thread->t_did;
4367 	ipst->ips_capab_taskq_quit = B_TRUE;
4368 	cv_signal(&ipst->ips_capab_taskq_cv);
4369 	mutex_exit(&ipst->ips_capab_taskq_lock);
4370 
4371 	/*
4372 	 * In rare occurrences, particularly on virtual hardware where CPUs can
4373 	 * be de-scheduled, the thread that we just signaled will not run until
4374 	 * after we have gotten through parts of ip_stack_fini. If that happens
4375 	 * then we'll try to grab the ips_capab_taskq_lock as part of returning
4376 	 * from cv_wait which no longer exists.
4377 	 */
4378 	thread_join(ktid);
4379 }
4380 
4381 /*
4382  * Free the IP stack instance.
4383  */
4384 static void
4385 ip_stack_fini(netstackid_t stackid, void *arg)
4386 {
4387 	ip_stack_t *ipst = (ip_stack_t *)arg;
4388 	int ret;
4389 
4390 #ifdef NS_DEBUG
4391 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4392 #endif
4393 	/*
4394 	 * At this point, all of the notifications that the events and
4395 	 * protocols are going away have been run, meaning that we can
4396 	 * now set about starting to clean things up.
4397 	 */
4398 	ipobs_fini(ipst);
4399 	ipv4_hook_destroy(ipst);
4400 	ipv6_hook_destroy(ipst);
4401 	arp_hook_destroy(ipst);
4402 	ip_net_destroy(ipst);
4403 
4404 	ipmp_destroy(ipst);
4405 
4406 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4407 	ipst->ips_ip_mibkp = NULL;
4408 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4409 	ipst->ips_icmp_mibkp = NULL;
4410 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4411 	ipst->ips_ip_kstat = NULL;
4412 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4413 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4414 	ipst->ips_ip6_kstat = NULL;
4415 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4416 
4417 	kmem_free(ipst->ips_propinfo_tbl,
4418 	    ip_propinfo_count * sizeof (mod_prop_info_t));
4419 	ipst->ips_propinfo_tbl = NULL;
4420 
4421 	dce_stack_destroy(ipst);
4422 	ip_mrouter_stack_destroy(ipst);
4423 
4424 	ret = untimeout(ipst->ips_igmp_timeout_id);
4425 	if (ret == -1) {
4426 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4427 	} else {
4428 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4429 		ipst->ips_igmp_timeout_id = 0;
4430 	}
4431 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4432 	if (ret == -1) {
4433 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4434 	} else {
4435 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4436 		ipst->ips_igmp_slowtimeout_id = 0;
4437 	}
4438 	ret = untimeout(ipst->ips_mld_timeout_id);
4439 	if (ret == -1) {
4440 		ASSERT(ipst->ips_mld_timeout_id == 0);
4441 	} else {
4442 		ASSERT(ipst->ips_mld_timeout_id != 0);
4443 		ipst->ips_mld_timeout_id = 0;
4444 	}
4445 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4446 	if (ret == -1) {
4447 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4448 	} else {
4449 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4450 		ipst->ips_mld_slowtimeout_id = 0;
4451 	}
4452 
4453 	ip_ire_fini(ipst);
4454 	ip6_asp_free(ipst);
4455 	conn_drain_fini(ipst);
4456 	ipcl_destroy(ipst);
4457 
4458 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4459 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4460 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4461 	ipst->ips_ndp4 = NULL;
4462 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4463 	ipst->ips_ndp6 = NULL;
4464 
4465 	if (ipst->ips_loopback_ksp != NULL) {
4466 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4467 		ipst->ips_loopback_ksp = NULL;
4468 	}
4469 
4470 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4471 	cv_destroy(&ipst->ips_capab_taskq_cv);
4472 
4473 	rw_destroy(&ipst->ips_srcid_lock);
4474 
4475 	mutex_destroy(&ipst->ips_ip_mi_lock);
4476 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4477 
4478 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4479 	mutex_destroy(&ipst->ips_mld_timer_lock);
4480 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4481 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4482 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4483 	rw_destroy(&ipst->ips_ill_g_lock);
4484 
4485 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4486 	ipst->ips_phyint_g_list = NULL;
4487 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4488 	ipst->ips_ill_g_heads = NULL;
4489 
4490 	ldi_ident_release(ipst->ips_ldi_ident);
4491 	kmem_free(ipst, sizeof (*ipst));
4492 }
4493 
4494 /*
4495  * This function is called from the TSD destructor, and is used to debug
4496  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4497  * details.
4498  */
4499 static void
4500 ip_thread_exit(void *phash)
4501 {
4502 	th_hash_t *thh = phash;
4503 
4504 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4505 	list_remove(&ip_thread_list, thh);
4506 	rw_exit(&ip_thread_rwlock);
4507 	mod_hash_destroy_hash(thh->thh_hash);
4508 	kmem_free(thh, sizeof (*thh));
4509 }
4510 
4511 /*
4512  * Called when the IP kernel module is loaded into the kernel
4513  */
4514 void
4515 ip_ddi_init(void)
4516 {
4517 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4518 
4519 	/*
4520 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4521 	 * initial devices: ip, ip6, tcp, tcp6.
4522 	 */
4523 	/*
4524 	 * If this is a 64-bit kernel, then create two separate arenas -
4525 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4526 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4527 	 */
4528 	ip_minor_arena_la = NULL;
4529 	ip_minor_arena_sa = NULL;
4530 #if defined(_LP64)
4531 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4532 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4533 		cmn_err(CE_PANIC,
4534 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4535 	}
4536 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4537 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4538 		cmn_err(CE_PANIC,
4539 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4540 	}
4541 #else
4542 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4543 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4544 		cmn_err(CE_PANIC,
4545 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4546 	}
4547 #endif
4548 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4549 
4550 	ipcl_g_init();
4551 	ip_ire_g_init();
4552 	ip_net_g_init();
4553 
4554 #ifdef DEBUG
4555 	tsd_create(&ip_thread_data, ip_thread_exit);
4556 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4557 	list_create(&ip_thread_list, sizeof (th_hash_t),
4558 	    offsetof(th_hash_t, thh_link));
4559 #endif
4560 	ipsec_policy_g_init();
4561 	tcp_ddi_g_init();
4562 	sctp_ddi_g_init();
4563 	dce_g_init();
4564 
4565 	/*
4566 	 * We want to be informed each time a stack is created or
4567 	 * destroyed in the kernel, so we can maintain the
4568 	 * set of udp_stack_t's.
4569 	 */
4570 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4571 	    ip_stack_fini);
4572 
4573 	tnet_init();
4574 
4575 	udp_ddi_g_init();
4576 	rts_ddi_g_init();
4577 	icmp_ddi_g_init();
4578 	ilb_ddi_g_init();
4579 
4580 	/* This needs to be called after all transports are initialized. */
4581 	mutex_enter(&cpu_lock);
4582 	register_cpu_setup_func(ip_tp_cpu_update, NULL);
4583 	mutex_exit(&cpu_lock);
4584 }
4585 
4586 /*
4587  * Initialize the IP stack instance.
4588  */
4589 static void *
4590 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4591 {
4592 	ip_stack_t	*ipst;
4593 	size_t		arrsz;
4594 	major_t		major;
4595 
4596 #ifdef NS_DEBUG
4597 	printf("ip_stack_init(stack %d)\n", stackid);
4598 #endif
4599 
4600 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4601 	ipst->ips_netstack = ns;
4602 
4603 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4604 	    KM_SLEEP);
4605 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4606 	    KM_SLEEP);
4607 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4608 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4609 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4610 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4611 
4612 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4613 	ipst->ips_igmp_deferred_next = INFINITY;
4614 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4615 	ipst->ips_mld_deferred_next = INFINITY;
4616 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4617 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4618 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4619 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4620 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4621 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4622 
4623 	ipcl_init(ipst);
4624 	ip_ire_init(ipst);
4625 	ip6_asp_init(ipst);
4626 	ipif_init(ipst);
4627 	conn_drain_init(ipst);
4628 	ip_mrouter_stack_init(ipst);
4629 	dce_stack_init(ipst);
4630 
4631 	ipst->ips_ip_multirt_log_interval = 1000;
4632 
4633 	ipst->ips_ill_index = 1;
4634 
4635 	ipst->ips_saved_ip_forwarding = -1;
4636 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4637 
4638 	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4639 	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4640 	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4641 
4642 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4643 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4644 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4645 	ipst->ips_ip6_kstat =
4646 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4647 
4648 	ipst->ips_ip_src_id = 1;
4649 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4650 
4651 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4652 
4653 	ip_net_init(ipst, ns);
4654 	ipv4_hook_init(ipst);
4655 	ipv6_hook_init(ipst);
4656 	arp_hook_init(ipst);
4657 	ipmp_init(ipst);
4658 	ipobs_init(ipst);
4659 
4660 	/*
4661 	 * Create the taskq dispatcher thread and initialize related stuff.
4662 	 */
4663 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4664 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4665 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4666 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4667 
4668 	major = mod_name_to_major(INET_NAME);
4669 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4670 	return (ipst);
4671 }
4672 
4673 /*
4674  * Allocate and initialize a DLPI template of the specified length.  (May be
4675  * called as writer.)
4676  */
4677 mblk_t *
4678 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4679 {
4680 	mblk_t	*mp;
4681 
4682 	mp = allocb(len, BPRI_MED);
4683 	if (!mp)
4684 		return (NULL);
4685 
4686 	/*
4687 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4688 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4689 	 * that other DLPI are M_PROTO.
4690 	 */
4691 	if (prim == DL_INFO_REQ) {
4692 		mp->b_datap->db_type = M_PCPROTO;
4693 	} else {
4694 		mp->b_datap->db_type = M_PROTO;
4695 	}
4696 
4697 	mp->b_wptr = mp->b_rptr + len;
4698 	bzero(mp->b_rptr, len);
4699 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4700 	return (mp);
4701 }
4702 
4703 /*
4704  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4705  */
4706 mblk_t *
4707 ip_dlnotify_alloc(uint_t notification, uint_t data)
4708 {
4709 	dl_notify_ind_t	*notifyp;
4710 	mblk_t		*mp;
4711 
4712 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4713 		return (NULL);
4714 
4715 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4716 	notifyp->dl_notification = notification;
4717 	notifyp->dl_data = data;
4718 	return (mp);
4719 }
4720 
4721 mblk_t *
4722 ip_dlnotify_alloc2(uint_t notification, uint_t data1, uint_t data2)
4723 {
4724 	dl_notify_ind_t	*notifyp;
4725 	mblk_t		*mp;
4726 
4727 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4728 		return (NULL);
4729 
4730 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4731 	notifyp->dl_notification = notification;
4732 	notifyp->dl_data1 = data1;
4733 	notifyp->dl_data2 = data2;
4734 	return (mp);
4735 }
4736 
4737 /*
4738  * Debug formatting routine.  Returns a character string representation of the
4739  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4740  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4741  *
4742  * Once the ndd table-printing interfaces are removed, this can be changed to
4743  * standard dotted-decimal form.
4744  */
4745 char *
4746 ip_dot_addr(ipaddr_t addr, char *buf)
4747 {
4748 	uint8_t *ap = (uint8_t *)&addr;
4749 
4750 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4751 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4752 	return (buf);
4753 }
4754 
4755 /*
4756  * Write the given MAC address as a printable string in the usual colon-
4757  * separated format.
4758  */
4759 const char *
4760 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4761 {
4762 	char *bp;
4763 
4764 	if (alen == 0 || buflen < 4)
4765 		return ("?");
4766 	bp = buf;
4767 	for (;;) {
4768 		/*
4769 		 * If there are more MAC address bytes available, but we won't
4770 		 * have any room to print them, then add "..." to the string
4771 		 * instead.  See below for the 'magic number' explanation.
4772 		 */
4773 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4774 			(void) strcpy(bp, "...");
4775 			break;
4776 		}
4777 		(void) sprintf(bp, "%02x", *addr++);
4778 		bp += 2;
4779 		if (--alen == 0)
4780 			break;
4781 		*bp++ = ':';
4782 		buflen -= 3;
4783 		/*
4784 		 * At this point, based on the first 'if' statement above,
4785 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4786 		 * buflen >= 4.  The first case leaves room for the final "xx"
4787 		 * number and trailing NUL byte.  The second leaves room for at
4788 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4789 		 * that statement.
4790 		 */
4791 	}
4792 	return (buf);
4793 }
4794 
4795 /*
4796  * Called when it is conceptually a ULP that would sent the packet
4797  * e.g., port unreachable and protocol unreachable. Check that the packet
4798  * would have passed the IPsec global policy before sending the error.
4799  *
4800  * Send an ICMP error after patching up the packet appropriately.
4801  * Uses ip_drop_input and bumps the appropriate MIB.
4802  */
4803 void
4804 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4805     ip_recv_attr_t *ira)
4806 {
4807 	ipha_t		*ipha;
4808 	boolean_t	secure;
4809 	ill_t		*ill = ira->ira_ill;
4810 	ip_stack_t	*ipst = ill->ill_ipst;
4811 	netstack_t	*ns = ipst->ips_netstack;
4812 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4813 
4814 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4815 
4816 	/*
4817 	 * We are generating an icmp error for some inbound packet.
4818 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4819 	 * Before we generate an error, check with global policy
4820 	 * to see whether this is allowed to enter the system. As
4821 	 * there is no "conn", we are checking with global policy.
4822 	 */
4823 	ipha = (ipha_t *)mp->b_rptr;
4824 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4825 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4826 		if (mp == NULL)
4827 			return;
4828 	}
4829 
4830 	/* We never send errors for protocols that we do implement */
4831 	if (ira->ira_protocol == IPPROTO_ICMP ||
4832 	    ira->ira_protocol == IPPROTO_IGMP) {
4833 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4834 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4835 		freemsg(mp);
4836 		return;
4837 	}
4838 	/*
4839 	 * Have to correct checksum since
4840 	 * the packet might have been
4841 	 * fragmented and the reassembly code in ip_rput
4842 	 * does not restore the IP checksum.
4843 	 */
4844 	ipha->ipha_hdr_checksum = 0;
4845 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4846 
4847 	switch (icmp_type) {
4848 	case ICMP_DEST_UNREACHABLE:
4849 		switch (icmp_code) {
4850 		case ICMP_PROTOCOL_UNREACHABLE:
4851 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4852 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4853 			break;
4854 		case ICMP_PORT_UNREACHABLE:
4855 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4856 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4857 			break;
4858 		}
4859 
4860 		icmp_unreachable(mp, icmp_code, ira);
4861 		break;
4862 	default:
4863 #ifdef DEBUG
4864 		panic("ip_fanout_send_icmp_v4: wrong type");
4865 		/*NOTREACHED*/
4866 #else
4867 		freemsg(mp);
4868 		break;
4869 #endif
4870 	}
4871 }
4872 
4873 /*
4874  * Used to send an ICMP error message when a packet is received for
4875  * a protocol that is not supported. The mblk passed as argument
4876  * is consumed by this function.
4877  */
4878 void
4879 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4880 {
4881 	ipha_t		*ipha;
4882 
4883 	ipha = (ipha_t *)mp->b_rptr;
4884 	if (ira->ira_flags & IRAF_IS_IPV4) {
4885 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4886 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4887 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4888 	} else {
4889 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4890 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4891 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
4892 	}
4893 }
4894 
4895 /*
4896  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4897  * Handles IPv4 and IPv6.
4898  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4899  * Caller is responsible for dropping references to the conn.
4900  */
4901 void
4902 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4903     ip_recv_attr_t *ira)
4904 {
4905 	ill_t		*ill = ira->ira_ill;
4906 	ip_stack_t	*ipst = ill->ill_ipst;
4907 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
4908 	boolean_t	secure;
4909 	uint_t		protocol = ira->ira_protocol;
4910 	iaflags_t	iraflags = ira->ira_flags;
4911 	queue_t		*rq;
4912 
4913 	secure = iraflags & IRAF_IPSEC_SECURE;
4914 
4915 	rq = connp->conn_rq;
4916 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4917 		switch (protocol) {
4918 		case IPPROTO_ICMPV6:
4919 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4920 			break;
4921 		case IPPROTO_ICMP:
4922 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4923 			break;
4924 		default:
4925 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4926 			break;
4927 		}
4928 		freemsg(mp);
4929 		return;
4930 	}
4931 
4932 	ASSERT(!(IPCL_IS_IPTUN(connp)));
4933 
4934 	if (((iraflags & IRAF_IS_IPV4) ?
4935 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4936 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4937 	    secure) {
4938 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
4939 		    ip6h, ira);
4940 		if (mp == NULL) {
4941 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4942 			/* Note that mp is NULL */
4943 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4944 			return;
4945 		}
4946 	}
4947 
4948 	if (iraflags & IRAF_ICMP_ERROR) {
4949 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
4950 	} else {
4951 		ill_t *rill = ira->ira_rill;
4952 
4953 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4954 		ira->ira_ill = ira->ira_rill = NULL;
4955 		/* Send it upstream */
4956 		(connp->conn_recv)(connp, mp, NULL, ira);
4957 		ira->ira_ill = ill;
4958 		ira->ira_rill = rill;
4959 	}
4960 }
4961 
4962 /*
4963  * Handle protocols with which IP is less intimate.  There
4964  * can be more than one stream bound to a particular
4965  * protocol.  When this is the case, normally each one gets a copy
4966  * of any incoming packets.
4967  *
4968  * IPsec NOTE :
4969  *
4970  * Don't allow a secure packet going up a non-secure connection.
4971  * We don't allow this because
4972  *
4973  * 1) Reply might go out in clear which will be dropped at
4974  *    the sending side.
4975  * 2) If the reply goes out in clear it will give the
4976  *    adversary enough information for getting the key in
4977  *    most of the cases.
4978  *
4979  * Moreover getting a secure packet when we expect clear
4980  * implies that SA's were added without checking for
4981  * policy on both ends. This should not happen once ISAKMP
4982  * is used to negotiate SAs as SAs will be added only after
4983  * verifying the policy.
4984  *
4985  * Zones notes:
4986  * Earlier in ip_input on a system with multiple shared-IP zones we
4987  * duplicate the multicast and broadcast packets and send them up
4988  * with each explicit zoneid that exists on that ill.
4989  * This means that here we can match the zoneid with SO_ALLZONES being special.
4990  */
4991 void
4992 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
4993 {
4994 	mblk_t		*mp1;
4995 	ipaddr_t	laddr;
4996 	conn_t		*connp, *first_connp, *next_connp;
4997 	connf_t		*connfp;
4998 	ill_t		*ill = ira->ira_ill;
4999 	ip_stack_t	*ipst = ill->ill_ipst;
5000 
5001 	laddr = ipha->ipha_dst;
5002 
5003 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
5004 	mutex_enter(&connfp->connf_lock);
5005 	connp = connfp->connf_head;
5006 	for (connp = connfp->connf_head; connp != NULL;
5007 	    connp = connp->conn_next) {
5008 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5009 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5010 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5011 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
5012 			break;
5013 		}
5014 	}
5015 
5016 	if (connp == NULL) {
5017 		/*
5018 		 * No one bound to these addresses.  Is
5019 		 * there a client that wants all
5020 		 * unclaimed datagrams?
5021 		 */
5022 		mutex_exit(&connfp->connf_lock);
5023 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5024 		    ICMP_PROTOCOL_UNREACHABLE, ira);
5025 		return;
5026 	}
5027 
5028 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5029 
5030 	CONN_INC_REF(connp);
5031 	first_connp = connp;
5032 	connp = connp->conn_next;
5033 
5034 	for (;;) {
5035 		while (connp != NULL) {
5036 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5037 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5038 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5039 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5040 			    ira, connp)))
5041 				break;
5042 			connp = connp->conn_next;
5043 		}
5044 
5045 		if (connp == NULL) {
5046 			/* No more interested clients */
5047 			connp = first_connp;
5048 			break;
5049 		}
5050 		if (((mp1 = dupmsg(mp)) == NULL) &&
5051 		    ((mp1 = copymsg(mp)) == NULL)) {
5052 			/* Memory allocation failed */
5053 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5054 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5055 			connp = first_connp;
5056 			break;
5057 		}
5058 
5059 		CONN_INC_REF(connp);
5060 		mutex_exit(&connfp->connf_lock);
5061 
5062 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5063 		    ira);
5064 
5065 		mutex_enter(&connfp->connf_lock);
5066 		/* Follow the next pointer before releasing the conn. */
5067 		next_connp = connp->conn_next;
5068 		CONN_DEC_REF(connp);
5069 		connp = next_connp;
5070 	}
5071 
5072 	/* Last one.  Send it upstream. */
5073 	mutex_exit(&connfp->connf_lock);
5074 
5075 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5076 
5077 	CONN_DEC_REF(connp);
5078 }
5079 
5080 /*
5081  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5082  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5083  * is not consumed.
5084  *
5085  * One of three things can happen, all of which affect the passed-in mblk:
5086  *
5087  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5088  *
5089  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5090  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5091  *
5092  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5093  */
5094 mblk_t *
5095 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5096 {
5097 	int shift, plen, iph_len;
5098 	ipha_t *ipha;
5099 	udpha_t *udpha;
5100 	uint32_t *spi;
5101 	uint32_t esp_ports;
5102 	uint8_t *orptr;
5103 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5104 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5105 
5106 	ipha = (ipha_t *)mp->b_rptr;
5107 	iph_len = ira->ira_ip_hdr_length;
5108 	plen = ira->ira_pktlen;
5109 
5110 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5111 		/*
5112 		 * Most likely a keepalive for the benefit of an intervening
5113 		 * NAT.  These aren't for us, per se, so drop it.
5114 		 *
5115 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5116 		 * byte packets (keepalives are 1-byte), but we'll drop them
5117 		 * also.
5118 		 */
5119 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5120 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5121 		return (NULL);
5122 	}
5123 
5124 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5125 		/* might as well pull it all up - it might be ESP. */
5126 		if (!pullupmsg(mp, -1)) {
5127 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5128 			    DROPPER(ipss, ipds_esp_nomem),
5129 			    &ipss->ipsec_dropper);
5130 			return (NULL);
5131 		}
5132 
5133 		ipha = (ipha_t *)mp->b_rptr;
5134 	}
5135 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5136 	if (*spi == 0) {
5137 		/* UDP packet - remove 0-spi. */
5138 		shift = sizeof (uint32_t);
5139 	} else {
5140 		/* ESP-in-UDP packet - reduce to ESP. */
5141 		ipha->ipha_protocol = IPPROTO_ESP;
5142 		shift = sizeof (udpha_t);
5143 	}
5144 
5145 	/* Fix IP header */
5146 	ira->ira_pktlen = (plen - shift);
5147 	ipha->ipha_length = htons(ira->ira_pktlen);
5148 	ipha->ipha_hdr_checksum = 0;
5149 
5150 	orptr = mp->b_rptr;
5151 	mp->b_rptr += shift;
5152 
5153 	udpha = (udpha_t *)(orptr + iph_len);
5154 	if (*spi == 0) {
5155 		ASSERT((uint8_t *)ipha == orptr);
5156 		udpha->uha_length = htons(plen - shift - iph_len);
5157 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5158 		esp_ports = 0;
5159 	} else {
5160 		esp_ports = *((uint32_t *)udpha);
5161 		ASSERT(esp_ports != 0);
5162 	}
5163 	ovbcopy(orptr, orptr + shift, iph_len);
5164 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5165 		ipha = (ipha_t *)(orptr + shift);
5166 
5167 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5168 		ira->ira_esp_udp_ports = esp_ports;
5169 		ip_fanout_v4(mp, ipha, ira);
5170 		return (NULL);
5171 	}
5172 	return (mp);
5173 }
5174 
5175 /*
5176  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5177  * Handles IPv4 and IPv6.
5178  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5179  * Caller is responsible for dropping references to the conn.
5180  */
5181 void
5182 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5183     ip_recv_attr_t *ira)
5184 {
5185 	ill_t		*ill = ira->ira_ill;
5186 	ip_stack_t	*ipst = ill->ill_ipst;
5187 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5188 	boolean_t	secure;
5189 	iaflags_t	iraflags = ira->ira_flags;
5190 
5191 	secure = iraflags & IRAF_IPSEC_SECURE;
5192 
5193 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5194 	    !canputnext(connp->conn_rq)) {
5195 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5196 		freemsg(mp);
5197 		return;
5198 	}
5199 
5200 	if (((iraflags & IRAF_IS_IPV4) ?
5201 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5202 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5203 	    secure) {
5204 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5205 		    ip6h, ira);
5206 		if (mp == NULL) {
5207 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5208 			/* Note that mp is NULL */
5209 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5210 			return;
5211 		}
5212 	}
5213 
5214 	/*
5215 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5216 	 * check. Only ip_fanout_v4 has that check.
5217 	 */
5218 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5219 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5220 	} else {
5221 		ill_t *rill = ira->ira_rill;
5222 
5223 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5224 		ira->ira_ill = ira->ira_rill = NULL;
5225 		/* Send it upstream */
5226 		(connp->conn_recv)(connp, mp, NULL, ira);
5227 		ira->ira_ill = ill;
5228 		ira->ira_rill = rill;
5229 	}
5230 }
5231 
5232 /*
5233  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5234  * (Unicast fanout is handled in ip_input_v4.)
5235  *
5236  * If SO_REUSEADDR is set all multicast and broadcast packets
5237  * will be delivered to all conns bound to the same port.
5238  *
5239  * If there is at least one matching AF_INET receiver, then we will
5240  * ignore any AF_INET6 receivers.
5241  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5242  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5243  * packets.
5244  *
5245  * Zones notes:
5246  * Earlier in ip_input on a system with multiple shared-IP zones we
5247  * duplicate the multicast and broadcast packets and send them up
5248  * with each explicit zoneid that exists on that ill.
5249  * This means that here we can match the zoneid with SO_ALLZONES being special.
5250  */
5251 void
5252 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5253     ip_recv_attr_t *ira)
5254 {
5255 	ipaddr_t	laddr;
5256 	in6_addr_t	v6faddr;
5257 	conn_t		*connp;
5258 	connf_t		*connfp;
5259 	ipaddr_t	faddr;
5260 	ill_t		*ill = ira->ira_ill;
5261 	ip_stack_t	*ipst = ill->ill_ipst;
5262 
5263 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5264 
5265 	laddr = ipha->ipha_dst;
5266 	faddr = ipha->ipha_src;
5267 
5268 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5269 	mutex_enter(&connfp->connf_lock);
5270 	connp = connfp->connf_head;
5271 
5272 	/*
5273 	 * If SO_REUSEADDR has been set on the first we send the
5274 	 * packet to all clients that have joined the group and
5275 	 * match the port.
5276 	 */
5277 	while (connp != NULL) {
5278 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5279 		    conn_wantpacket(connp, ira, ipha) &&
5280 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5281 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5282 			break;
5283 		connp = connp->conn_next;
5284 	}
5285 
5286 	if (connp == NULL)
5287 		goto notfound;
5288 
5289 	CONN_INC_REF(connp);
5290 
5291 	if (connp->conn_reuseaddr) {
5292 		conn_t		*first_connp = connp;
5293 		conn_t		*next_connp;
5294 		mblk_t		*mp1;
5295 
5296 		connp = connp->conn_next;
5297 		for (;;) {
5298 			while (connp != NULL) {
5299 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5300 				    fport, faddr) &&
5301 				    conn_wantpacket(connp, ira, ipha) &&
5302 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5303 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5304 				    ira, connp)))
5305 					break;
5306 				connp = connp->conn_next;
5307 			}
5308 			if (connp == NULL) {
5309 				/* No more interested clients */
5310 				connp = first_connp;
5311 				break;
5312 			}
5313 			if (((mp1 = dupmsg(mp)) == NULL) &&
5314 			    ((mp1 = copymsg(mp)) == NULL)) {
5315 				/* Memory allocation failed */
5316 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5317 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5318 				connp = first_connp;
5319 				break;
5320 			}
5321 			CONN_INC_REF(connp);
5322 			mutex_exit(&connfp->connf_lock);
5323 
5324 			IP_STAT(ipst, ip_udp_fanmb);
5325 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5326 			    NULL, ira);
5327 			mutex_enter(&connfp->connf_lock);
5328 			/* Follow the next pointer before releasing the conn */
5329 			next_connp = connp->conn_next;
5330 			CONN_DEC_REF(connp);
5331 			connp = next_connp;
5332 		}
5333 	}
5334 
5335 	/* Last one.  Send it upstream. */
5336 	mutex_exit(&connfp->connf_lock);
5337 	IP_STAT(ipst, ip_udp_fanmb);
5338 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5339 	CONN_DEC_REF(connp);
5340 	return;
5341 
5342 notfound:
5343 	mutex_exit(&connfp->connf_lock);
5344 	/*
5345 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5346 	 * have already been matched above, since they live in the IPv4
5347 	 * fanout tables. This implies we only need to
5348 	 * check for IPv6 in6addr_any endpoints here.
5349 	 * Thus we compare using ipv6_all_zeros instead of the destination
5350 	 * address, except for the multicast group membership lookup which
5351 	 * uses the IPv4 destination.
5352 	 */
5353 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5354 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5355 	mutex_enter(&connfp->connf_lock);
5356 	connp = connfp->connf_head;
5357 	/*
5358 	 * IPv4 multicast packet being delivered to an AF_INET6
5359 	 * in6addr_any endpoint.
5360 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5361 	 * and not conn_wantpacket_v6() since any multicast membership is
5362 	 * for an IPv4-mapped multicast address.
5363 	 */
5364 	while (connp != NULL) {
5365 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5366 		    fport, v6faddr) &&
5367 		    conn_wantpacket(connp, ira, ipha) &&
5368 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5369 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5370 			break;
5371 		connp = connp->conn_next;
5372 	}
5373 
5374 	if (connp == NULL) {
5375 		/*
5376 		 * No one bound to this port.  Is
5377 		 * there a client that wants all
5378 		 * unclaimed datagrams?
5379 		 */
5380 		mutex_exit(&connfp->connf_lock);
5381 
5382 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5383 		    NULL) {
5384 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5385 			ip_fanout_proto_v4(mp, ipha, ira);
5386 		} else {
5387 			/*
5388 			 * We used to attempt to send an icmp error here, but
5389 			 * since this is known to be a multicast packet
5390 			 * and we don't send icmp errors in response to
5391 			 * multicast, just drop the packet and give up sooner.
5392 			 */
5393 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5394 			freemsg(mp);
5395 		}
5396 		return;
5397 	}
5398 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5399 
5400 	/*
5401 	 * If SO_REUSEADDR has been set on the first we send the
5402 	 * packet to all clients that have joined the group and
5403 	 * match the port.
5404 	 */
5405 	if (connp->conn_reuseaddr) {
5406 		conn_t		*first_connp = connp;
5407 		conn_t		*next_connp;
5408 		mblk_t		*mp1;
5409 
5410 		CONN_INC_REF(connp);
5411 		connp = connp->conn_next;
5412 		for (;;) {
5413 			while (connp != NULL) {
5414 				if (IPCL_UDP_MATCH_V6(connp, lport,
5415 				    ipv6_all_zeros, fport, v6faddr) &&
5416 				    conn_wantpacket(connp, ira, ipha) &&
5417 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5418 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5419 				    ira, connp)))
5420 					break;
5421 				connp = connp->conn_next;
5422 			}
5423 			if (connp == NULL) {
5424 				/* No more interested clients */
5425 				connp = first_connp;
5426 				break;
5427 			}
5428 			if (((mp1 = dupmsg(mp)) == NULL) &&
5429 			    ((mp1 = copymsg(mp)) == NULL)) {
5430 				/* Memory allocation failed */
5431 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5432 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5433 				connp = first_connp;
5434 				break;
5435 			}
5436 			CONN_INC_REF(connp);
5437 			mutex_exit(&connfp->connf_lock);
5438 
5439 			IP_STAT(ipst, ip_udp_fanmb);
5440 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5441 			    NULL, ira);
5442 			mutex_enter(&connfp->connf_lock);
5443 			/* Follow the next pointer before releasing the conn */
5444 			next_connp = connp->conn_next;
5445 			CONN_DEC_REF(connp);
5446 			connp = next_connp;
5447 		}
5448 	}
5449 
5450 	/* Last one.  Send it upstream. */
5451 	mutex_exit(&connfp->connf_lock);
5452 	IP_STAT(ipst, ip_udp_fanmb);
5453 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5454 	CONN_DEC_REF(connp);
5455 }
5456 
5457 /*
5458  * Split an incoming packet's IPv4 options into the label and the other options.
5459  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5460  * clearing out any leftover label or options.
5461  * Otherwise it just makes ipp point into the packet.
5462  *
5463  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5464  */
5465 int
5466 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5467 {
5468 	uchar_t		*opt;
5469 	uint32_t	totallen;
5470 	uint32_t	optval;
5471 	uint32_t	optlen;
5472 
5473 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5474 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5475 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5476 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5477 
5478 	/*
5479 	 * Get length (in 4 byte octets) of IP header options.
5480 	 */
5481 	totallen = ipha->ipha_version_and_hdr_length -
5482 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5483 
5484 	if (totallen == 0) {
5485 		if (!allocate)
5486 			return (0);
5487 
5488 		/* Clear out anything from a previous packet */
5489 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5490 			kmem_free(ipp->ipp_ipv4_options,
5491 			    ipp->ipp_ipv4_options_len);
5492 			ipp->ipp_ipv4_options = NULL;
5493 			ipp->ipp_ipv4_options_len = 0;
5494 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5495 		}
5496 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5497 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5498 			ipp->ipp_label_v4 = NULL;
5499 			ipp->ipp_label_len_v4 = 0;
5500 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5501 		}
5502 		return (0);
5503 	}
5504 
5505 	totallen <<= 2;
5506 	opt = (uchar_t *)&ipha[1];
5507 	if (!is_system_labeled()) {
5508 
5509 	copyall:
5510 		if (!allocate) {
5511 			if (totallen != 0) {
5512 				ipp->ipp_ipv4_options = opt;
5513 				ipp->ipp_ipv4_options_len = totallen;
5514 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5515 			}
5516 			return (0);
5517 		}
5518 		/* Just copy all of options */
5519 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5520 			if (totallen == ipp->ipp_ipv4_options_len) {
5521 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5522 				return (0);
5523 			}
5524 			kmem_free(ipp->ipp_ipv4_options,
5525 			    ipp->ipp_ipv4_options_len);
5526 			ipp->ipp_ipv4_options = NULL;
5527 			ipp->ipp_ipv4_options_len = 0;
5528 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5529 		}
5530 		if (totallen == 0)
5531 			return (0);
5532 
5533 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5534 		if (ipp->ipp_ipv4_options == NULL)
5535 			return (ENOMEM);
5536 		ipp->ipp_ipv4_options_len = totallen;
5537 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5538 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5539 		return (0);
5540 	}
5541 
5542 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5543 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5544 		ipp->ipp_label_v4 = NULL;
5545 		ipp->ipp_label_len_v4 = 0;
5546 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5547 	}
5548 
5549 	/*
5550 	 * Search for CIPSO option.
5551 	 * We assume CIPSO is first in options if it is present.
5552 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5553 	 * prior to the CIPSO option.
5554 	 */
5555 	while (totallen != 0) {
5556 		switch (optval = opt[IPOPT_OPTVAL]) {
5557 		case IPOPT_EOL:
5558 			return (0);
5559 		case IPOPT_NOP:
5560 			optlen = 1;
5561 			break;
5562 		default:
5563 			if (totallen <= IPOPT_OLEN)
5564 				return (EINVAL);
5565 			optlen = opt[IPOPT_OLEN];
5566 			if (optlen < 2)
5567 				return (EINVAL);
5568 		}
5569 		if (optlen > totallen)
5570 			return (EINVAL);
5571 
5572 		switch (optval) {
5573 		case IPOPT_COMSEC:
5574 			if (!allocate) {
5575 				ipp->ipp_label_v4 = opt;
5576 				ipp->ipp_label_len_v4 = optlen;
5577 				ipp->ipp_fields |= IPPF_LABEL_V4;
5578 			} else {
5579 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5580 				    KM_NOSLEEP);
5581 				if (ipp->ipp_label_v4 == NULL)
5582 					return (ENOMEM);
5583 				ipp->ipp_label_len_v4 = optlen;
5584 				ipp->ipp_fields |= IPPF_LABEL_V4;
5585 				bcopy(opt, ipp->ipp_label_v4, optlen);
5586 			}
5587 			totallen -= optlen;
5588 			opt += optlen;
5589 
5590 			/* Skip padding bytes until we get to a multiple of 4 */
5591 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5592 				totallen--;
5593 				opt++;
5594 			}
5595 			/* Remaining as ipp_ipv4_options */
5596 			goto copyall;
5597 		}
5598 		totallen -= optlen;
5599 		opt += optlen;
5600 	}
5601 	/* No CIPSO found; return everything as ipp_ipv4_options */
5602 	totallen = ipha->ipha_version_and_hdr_length -
5603 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5604 	totallen <<= 2;
5605 	opt = (uchar_t *)&ipha[1];
5606 	goto copyall;
5607 }
5608 
5609 /*
5610  * Efficient versions of lookup for an IRE when we only
5611  * match the address.
5612  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5613  * Does not handle multicast addresses.
5614  */
5615 uint_t
5616 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5617 {
5618 	ire_t *ire;
5619 	uint_t result;
5620 
5621 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5622 	ASSERT(ire != NULL);
5623 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5624 		result = IRE_NOROUTE;
5625 	else
5626 		result = ire->ire_type;
5627 	ire_refrele(ire);
5628 	return (result);
5629 }
5630 
5631 /*
5632  * Efficient versions of lookup for an IRE when we only
5633  * match the address.
5634  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5635  * Does not handle multicast addresses.
5636  */
5637 uint_t
5638 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5639 {
5640 	ire_t *ire;
5641 	uint_t result;
5642 
5643 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5644 	ASSERT(ire != NULL);
5645 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5646 		result = IRE_NOROUTE;
5647 	else
5648 		result = ire->ire_type;
5649 	ire_refrele(ire);
5650 	return (result);
5651 }
5652 
5653 /*
5654  * Nobody should be sending
5655  * packets up this stream
5656  */
5657 static void
5658 ip_lrput(queue_t *q, mblk_t *mp)
5659 {
5660 	switch (mp->b_datap->db_type) {
5661 	case M_FLUSH:
5662 		/* Turn around */
5663 		if (*mp->b_rptr & FLUSHW) {
5664 			*mp->b_rptr &= ~FLUSHR;
5665 			qreply(q, mp);
5666 			return;
5667 		}
5668 		break;
5669 	}
5670 	freemsg(mp);
5671 }
5672 
5673 /* Nobody should be sending packets down this stream */
5674 /* ARGSUSED */
5675 void
5676 ip_lwput(queue_t *q, mblk_t *mp)
5677 {
5678 	freemsg(mp);
5679 }
5680 
5681 /*
5682  * Move the first hop in any source route to ipha_dst and remove that part of
5683  * the source route.  Called by other protocols.  Errors in option formatting
5684  * are ignored - will be handled by ip_output_options. Return the final
5685  * destination (either ipha_dst or the last entry in a source route.)
5686  */
5687 ipaddr_t
5688 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5689 {
5690 	ipoptp_t	opts;
5691 	uchar_t		*opt;
5692 	uint8_t		optval;
5693 	uint8_t		optlen;
5694 	ipaddr_t	dst;
5695 	int		i;
5696 	ip_stack_t	*ipst = ns->netstack_ip;
5697 
5698 	ip2dbg(("ip_massage_options\n"));
5699 	dst = ipha->ipha_dst;
5700 	for (optval = ipoptp_first(&opts, ipha);
5701 	    optval != IPOPT_EOL;
5702 	    optval = ipoptp_next(&opts)) {
5703 		opt = opts.ipoptp_cur;
5704 		switch (optval) {
5705 			uint8_t off;
5706 		case IPOPT_SSRR:
5707 		case IPOPT_LSRR:
5708 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5709 				ip1dbg(("ip_massage_options: bad src route\n"));
5710 				break;
5711 			}
5712 			optlen = opts.ipoptp_len;
5713 			off = opt[IPOPT_OFFSET];
5714 			off--;
5715 		redo_srr:
5716 			if (optlen < IP_ADDR_LEN ||
5717 			    off > optlen - IP_ADDR_LEN) {
5718 				/* End of source route */
5719 				ip1dbg(("ip_massage_options: end of SR\n"));
5720 				break;
5721 			}
5722 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5723 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5724 			    ntohl(dst)));
5725 			/*
5726 			 * Check if our address is present more than
5727 			 * once as consecutive hops in source route.
5728 			 * XXX verify per-interface ip_forwarding
5729 			 * for source route?
5730 			 */
5731 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5732 				off += IP_ADDR_LEN;
5733 				goto redo_srr;
5734 			}
5735 			if (dst == htonl(INADDR_LOOPBACK)) {
5736 				ip1dbg(("ip_massage_options: loopback addr in "
5737 				    "source route!\n"));
5738 				break;
5739 			}
5740 			/*
5741 			 * Update ipha_dst to be the first hop and remove the
5742 			 * first hop from the source route (by overwriting
5743 			 * part of the option with NOP options).
5744 			 */
5745 			ipha->ipha_dst = dst;
5746 			/* Put the last entry in dst */
5747 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5748 			    3;
5749 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5750 
5751 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5752 			    ntohl(dst)));
5753 			/* Move down and overwrite */
5754 			opt[IP_ADDR_LEN] = opt[0];
5755 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5756 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5757 			for (i = 0; i < IP_ADDR_LEN; i++)
5758 				opt[i] = IPOPT_NOP;
5759 			break;
5760 		}
5761 	}
5762 	return (dst);
5763 }
5764 
5765 /*
5766  * Return the network mask
5767  * associated with the specified address.
5768  */
5769 ipaddr_t
5770 ip_net_mask(ipaddr_t addr)
5771 {
5772 	uchar_t	*up = (uchar_t *)&addr;
5773 	ipaddr_t mask = 0;
5774 	uchar_t	*maskp = (uchar_t *)&mask;
5775 
5776 #if defined(__i386) || defined(__amd64)
5777 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5778 #endif
5779 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5780 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5781 #endif
5782 	if (CLASSD(addr)) {
5783 		maskp[0] = 0xF0;
5784 		return (mask);
5785 	}
5786 
5787 	/* We assume Class E default netmask to be 32 */
5788 	if (CLASSE(addr))
5789 		return (0xffffffffU);
5790 
5791 	if (addr == 0)
5792 		return (0);
5793 	maskp[0] = 0xFF;
5794 	if ((up[0] & 0x80) == 0)
5795 		return (mask);
5796 
5797 	maskp[1] = 0xFF;
5798 	if ((up[0] & 0xC0) == 0x80)
5799 		return (mask);
5800 
5801 	maskp[2] = 0xFF;
5802 	if ((up[0] & 0xE0) == 0xC0)
5803 		return (mask);
5804 
5805 	/* Otherwise return no mask */
5806 	return ((ipaddr_t)0);
5807 }
5808 
5809 /* Name/Value Table Lookup Routine */
5810 char *
5811 ip_nv_lookup(nv_t *nv, int value)
5812 {
5813 	if (!nv)
5814 		return (NULL);
5815 	for (; nv->nv_name; nv++) {
5816 		if (nv->nv_value == value)
5817 			return (nv->nv_name);
5818 	}
5819 	return ("unknown");
5820 }
5821 
5822 static int
5823 ip_wait_for_info_ack(ill_t *ill)
5824 {
5825 	int err;
5826 
5827 	mutex_enter(&ill->ill_lock);
5828 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5829 		/*
5830 		 * Return value of 0 indicates a pending signal.
5831 		 */
5832 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5833 		if (err == 0) {
5834 			mutex_exit(&ill->ill_lock);
5835 			return (EINTR);
5836 		}
5837 	}
5838 	mutex_exit(&ill->ill_lock);
5839 	/*
5840 	 * ip_rput_other could have set an error  in ill_error on
5841 	 * receipt of M_ERROR.
5842 	 */
5843 	return (ill->ill_error);
5844 }
5845 
5846 /*
5847  * This is a module open, i.e. this is a control stream for access
5848  * to a DLPI device.  We allocate an ill_t as the instance data in
5849  * this case.
5850  */
5851 static int
5852 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5853 {
5854 	ill_t	*ill;
5855 	int	err;
5856 	zoneid_t zoneid;
5857 	netstack_t *ns;
5858 	ip_stack_t *ipst;
5859 
5860 	/*
5861 	 * Prevent unprivileged processes from pushing IP so that
5862 	 * they can't send raw IP.
5863 	 */
5864 	if (secpolicy_net_rawaccess(credp) != 0)
5865 		return (EPERM);
5866 
5867 	ns = netstack_find_by_cred(credp);
5868 	ASSERT(ns != NULL);
5869 	ipst = ns->netstack_ip;
5870 	ASSERT(ipst != NULL);
5871 
5872 	/*
5873 	 * For exclusive stacks we set the zoneid to zero
5874 	 * to make IP operate as if in the global zone.
5875 	 */
5876 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5877 		zoneid = GLOBAL_ZONEID;
5878 	else
5879 		zoneid = crgetzoneid(credp);
5880 
5881 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5882 	q->q_ptr = WR(q)->q_ptr = ill;
5883 	ill->ill_ipst = ipst;
5884 	ill->ill_zoneid = zoneid;
5885 
5886 	/*
5887 	 * ill_init initializes the ill fields and then sends down
5888 	 * down a DL_INFO_REQ after calling qprocson.
5889 	 */
5890 	err = ill_init(q, ill);
5891 
5892 	if (err != 0) {
5893 		mi_free(ill);
5894 		netstack_rele(ipst->ips_netstack);
5895 		q->q_ptr = NULL;
5896 		WR(q)->q_ptr = NULL;
5897 		return (err);
5898 	}
5899 
5900 	/*
5901 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5902 	 *
5903 	 * ill_init initializes the ipsq marking this thread as
5904 	 * writer
5905 	 */
5906 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
5907 	err = ip_wait_for_info_ack(ill);
5908 	if (err == 0)
5909 		ill->ill_credp = credp;
5910 	else
5911 		goto fail;
5912 
5913 	crhold(credp);
5914 
5915 	mutex_enter(&ipst->ips_ip_mi_lock);
5916 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5917 	    sflag, credp);
5918 	mutex_exit(&ipst->ips_ip_mi_lock);
5919 fail:
5920 	if (err) {
5921 		(void) ip_close(q, 0);
5922 		return (err);
5923 	}
5924 	return (0);
5925 }
5926 
5927 /* For /dev/ip aka AF_INET open */
5928 int
5929 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5930 {
5931 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5932 }
5933 
5934 /* For /dev/ip6 aka AF_INET6 open */
5935 int
5936 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5937 {
5938 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5939 }
5940 
5941 /* IP open routine. */
5942 int
5943 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5944     boolean_t isv6)
5945 {
5946 	conn_t 		*connp;
5947 	major_t		maj;
5948 	zoneid_t	zoneid;
5949 	netstack_t	*ns;
5950 	ip_stack_t	*ipst;
5951 
5952 	/* Allow reopen. */
5953 	if (q->q_ptr != NULL)
5954 		return (0);
5955 
5956 	if (sflag & MODOPEN) {
5957 		/* This is a module open */
5958 		return (ip_modopen(q, devp, flag, sflag, credp));
5959 	}
5960 
5961 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5962 		/*
5963 		 * Non streams based socket looking for a stream
5964 		 * to access IP
5965 		 */
5966 		return (ip_helper_stream_setup(q, devp, flag, sflag,
5967 		    credp, isv6));
5968 	}
5969 
5970 	ns = netstack_find_by_cred(credp);
5971 	ASSERT(ns != NULL);
5972 	ipst = ns->netstack_ip;
5973 	ASSERT(ipst != NULL);
5974 
5975 	/*
5976 	 * For exclusive stacks we set the zoneid to zero
5977 	 * to make IP operate as if in the global zone.
5978 	 */
5979 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5980 		zoneid = GLOBAL_ZONEID;
5981 	else
5982 		zoneid = crgetzoneid(credp);
5983 
5984 	/*
5985 	 * We are opening as a device. This is an IP client stream, and we
5986 	 * allocate an conn_t as the instance data.
5987 	 */
5988 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
5989 
5990 	/*
5991 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
5992 	 * done by netstack_find_by_cred()
5993 	 */
5994 	netstack_rele(ipst->ips_netstack);
5995 
5996 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
5997 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
5998 	connp->conn_ixa->ixa_zoneid = zoneid;
5999 	connp->conn_zoneid = zoneid;
6000 
6001 	connp->conn_rq = q;
6002 	q->q_ptr = WR(q)->q_ptr = connp;
6003 
6004 	/* Minor tells us which /dev entry was opened */
6005 	if (isv6) {
6006 		connp->conn_family = AF_INET6;
6007 		connp->conn_ipversion = IPV6_VERSION;
6008 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
6009 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
6010 	} else {
6011 		connp->conn_family = AF_INET;
6012 		connp->conn_ipversion = IPV4_VERSION;
6013 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
6014 	}
6015 
6016 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
6017 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
6018 		connp->conn_minor_arena = ip_minor_arena_la;
6019 	} else {
6020 		/*
6021 		 * Either minor numbers in the large arena were exhausted
6022 		 * or a non socket application is doing the open.
6023 		 * Try to allocate from the small arena.
6024 		 */
6025 		if ((connp->conn_dev =
6026 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
6027 			/* CONN_DEC_REF takes care of netstack_rele() */
6028 			q->q_ptr = WR(q)->q_ptr = NULL;
6029 			CONN_DEC_REF(connp);
6030 			return (EBUSY);
6031 		}
6032 		connp->conn_minor_arena = ip_minor_arena_sa;
6033 	}
6034 
6035 	maj = getemajor(*devp);
6036 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
6037 
6038 	/*
6039 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
6040 	 */
6041 	connp->conn_cred = credp;
6042 	connp->conn_cpid = curproc->p_pid;
6043 	/* Cache things in ixa without an extra refhold */
6044 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
6045 	connp->conn_ixa->ixa_cred = connp->conn_cred;
6046 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
6047 	if (is_system_labeled())
6048 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
6049 
6050 	/*
6051 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6052 	 */
6053 	connp->conn_recv = ip_conn_input;
6054 	connp->conn_recvicmp = ip_conn_input_icmp;
6055 
6056 	crhold(connp->conn_cred);
6057 
6058 	/*
6059 	 * If the caller has the process-wide flag set, then default to MAC
6060 	 * exempt mode.  This allows read-down to unlabeled hosts.
6061 	 */
6062 	if (getpflags(NET_MAC_AWARE, credp) != 0)
6063 		connp->conn_mac_mode = CONN_MAC_AWARE;
6064 
6065 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6066 
6067 	connp->conn_rq = q;
6068 	connp->conn_wq = WR(q);
6069 
6070 	/* Non-zero default values */
6071 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6072 
6073 	/*
6074 	 * Make the conn globally visible to walkers
6075 	 */
6076 	ASSERT(connp->conn_ref == 1);
6077 	mutex_enter(&connp->conn_lock);
6078 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6079 	mutex_exit(&connp->conn_lock);
6080 
6081 	qprocson(q);
6082 
6083 	return (0);
6084 }
6085 
6086 /*
6087  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6088  * all of them are copied to the conn_t. If the req is "zero", the policy is
6089  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6090  * fields.
6091  * We keep only the latest setting of the policy and thus policy setting
6092  * is not incremental/cumulative.
6093  *
6094  * Requests to set policies with multiple alternative actions will
6095  * go through a different API.
6096  */
6097 int
6098 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6099 {
6100 	uint_t ah_req = 0;
6101 	uint_t esp_req = 0;
6102 	uint_t se_req = 0;
6103 	ipsec_act_t *actp = NULL;
6104 	uint_t nact;
6105 	ipsec_policy_head_t *ph;
6106 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6107 	int error = 0;
6108 	netstack_t	*ns = connp->conn_netstack;
6109 	ip_stack_t	*ipst = ns->netstack_ip;
6110 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6111 
6112 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6113 
6114 	/*
6115 	 * The IP_SEC_OPT option does not allow variable length parameters,
6116 	 * hence a request cannot be NULL.
6117 	 */
6118 	if (req == NULL)
6119 		return (EINVAL);
6120 
6121 	ah_req = req->ipsr_ah_req;
6122 	esp_req = req->ipsr_esp_req;
6123 	se_req = req->ipsr_self_encap_req;
6124 
6125 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6126 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6127 		return (EINVAL);
6128 
6129 	/*
6130 	 * Are we dealing with a request to reset the policy (i.e.
6131 	 * zero requests).
6132 	 */
6133 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6134 	    (esp_req & REQ_MASK) == 0 &&
6135 	    (se_req & REQ_MASK) == 0);
6136 
6137 	if (!is_pol_reset) {
6138 		/*
6139 		 * If we couldn't load IPsec, fail with "protocol
6140 		 * not supported".
6141 		 * IPsec may not have been loaded for a request with zero
6142 		 * policies, so we don't fail in this case.
6143 		 */
6144 		mutex_enter(&ipss->ipsec_loader_lock);
6145 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6146 			mutex_exit(&ipss->ipsec_loader_lock);
6147 			return (EPROTONOSUPPORT);
6148 		}
6149 		mutex_exit(&ipss->ipsec_loader_lock);
6150 
6151 		/*
6152 		 * Test for valid requests. Invalid algorithms
6153 		 * need to be tested by IPsec code because new
6154 		 * algorithms can be added dynamically.
6155 		 */
6156 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6157 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6158 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6159 			return (EINVAL);
6160 		}
6161 
6162 		/*
6163 		 * Only privileged users can issue these
6164 		 * requests.
6165 		 */
6166 		if (((ah_req & IPSEC_PREF_NEVER) ||
6167 		    (esp_req & IPSEC_PREF_NEVER) ||
6168 		    (se_req & IPSEC_PREF_NEVER)) &&
6169 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6170 			return (EPERM);
6171 		}
6172 
6173 		/*
6174 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6175 		 * are mutually exclusive.
6176 		 */
6177 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6178 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6179 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6180 			/* Both of them are set */
6181 			return (EINVAL);
6182 		}
6183 	}
6184 
6185 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6186 
6187 	/*
6188 	 * If we have already cached policies in conn_connect(), don't
6189 	 * let them change now. We cache policies for connections
6190 	 * whose src,dst [addr, port] is known.
6191 	 */
6192 	if (connp->conn_policy_cached) {
6193 		return (EINVAL);
6194 	}
6195 
6196 	/*
6197 	 * We have a zero policies, reset the connection policy if already
6198 	 * set. This will cause the connection to inherit the
6199 	 * global policy, if any.
6200 	 */
6201 	if (is_pol_reset) {
6202 		if (connp->conn_policy != NULL) {
6203 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6204 			connp->conn_policy = NULL;
6205 		}
6206 		connp->conn_in_enforce_policy = B_FALSE;
6207 		connp->conn_out_enforce_policy = B_FALSE;
6208 		return (0);
6209 	}
6210 
6211 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6212 	    ipst->ips_netstack);
6213 	if (ph == NULL)
6214 		goto enomem;
6215 
6216 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6217 	if (actp == NULL)
6218 		goto enomem;
6219 
6220 	/*
6221 	 * Always insert IPv4 policy entries, since they can also apply to
6222 	 * ipv6 sockets being used in ipv4-compat mode.
6223 	 */
6224 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6225 	    IPSEC_TYPE_INBOUND, ns))
6226 		goto enomem;
6227 	is_pol_inserted = B_TRUE;
6228 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6229 	    IPSEC_TYPE_OUTBOUND, ns))
6230 		goto enomem;
6231 
6232 	/*
6233 	 * We're looking at a v6 socket, also insert the v6-specific
6234 	 * entries.
6235 	 */
6236 	if (connp->conn_family == AF_INET6) {
6237 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6238 		    IPSEC_TYPE_INBOUND, ns))
6239 			goto enomem;
6240 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6241 		    IPSEC_TYPE_OUTBOUND, ns))
6242 			goto enomem;
6243 	}
6244 
6245 	ipsec_actvec_free(actp, nact);
6246 
6247 	/*
6248 	 * If the requests need security, set enforce_policy.
6249 	 * If the requests are IPSEC_PREF_NEVER, one should
6250 	 * still set conn_out_enforce_policy so that ip_set_destination
6251 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6252 	 * for connections that we don't cache policy in at connect time,
6253 	 * if global policy matches in ip_output_attach_policy, we
6254 	 * don't wrongly inherit global policy. Similarly, we need
6255 	 * to set conn_in_enforce_policy also so that we don't verify
6256 	 * policy wrongly.
6257 	 */
6258 	if ((ah_req & REQ_MASK) != 0 ||
6259 	    (esp_req & REQ_MASK) != 0 ||
6260 	    (se_req & REQ_MASK) != 0) {
6261 		connp->conn_in_enforce_policy = B_TRUE;
6262 		connp->conn_out_enforce_policy = B_TRUE;
6263 	}
6264 
6265 	return (error);
6266 #undef REQ_MASK
6267 
6268 	/*
6269 	 * Common memory-allocation-failure exit path.
6270 	 */
6271 enomem:
6272 	if (actp != NULL)
6273 		ipsec_actvec_free(actp, nact);
6274 	if (is_pol_inserted)
6275 		ipsec_polhead_flush(ph, ns);
6276 	return (ENOMEM);
6277 }
6278 
6279 /*
6280  * Set socket options for joining and leaving multicast groups.
6281  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6282  * The caller has already check that the option name is consistent with
6283  * the address family of the socket.
6284  */
6285 int
6286 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6287     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6288 {
6289 	int		*i1 = (int *)invalp;
6290 	int		error = 0;
6291 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6292 	struct ip_mreq	*v4_mreqp;
6293 	struct ipv6_mreq *v6_mreqp;
6294 	struct group_req *greqp;
6295 	ire_t *ire;
6296 	boolean_t done = B_FALSE;
6297 	ipaddr_t ifaddr;
6298 	in6_addr_t v6group;
6299 	uint_t ifindex;
6300 	boolean_t mcast_opt = B_TRUE;
6301 	mcast_record_t fmode;
6302 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6303 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6304 
6305 	switch (name) {
6306 	case IP_ADD_MEMBERSHIP:
6307 	case IPV6_JOIN_GROUP:
6308 		mcast_opt = B_FALSE;
6309 		/* FALLTHRU */
6310 	case MCAST_JOIN_GROUP:
6311 		fmode = MODE_IS_EXCLUDE;
6312 		optfn = ip_opt_add_group;
6313 		break;
6314 
6315 	case IP_DROP_MEMBERSHIP:
6316 	case IPV6_LEAVE_GROUP:
6317 		mcast_opt = B_FALSE;
6318 		/* FALLTHRU */
6319 	case MCAST_LEAVE_GROUP:
6320 		fmode = MODE_IS_INCLUDE;
6321 		optfn = ip_opt_delete_group;
6322 		break;
6323 	default:
6324 		ASSERT(0);
6325 	}
6326 
6327 	if (mcast_opt) {
6328 		struct sockaddr_in *sin;
6329 		struct sockaddr_in6 *sin6;
6330 
6331 		greqp = (struct group_req *)i1;
6332 		if (greqp->gr_group.ss_family == AF_INET) {
6333 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6334 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6335 		} else {
6336 			if (!inet6)
6337 				return (EINVAL);	/* Not on INET socket */
6338 
6339 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6340 			v6group = sin6->sin6_addr;
6341 		}
6342 		ifaddr = INADDR_ANY;
6343 		ifindex = greqp->gr_interface;
6344 	} else if (inet6) {
6345 		v6_mreqp = (struct ipv6_mreq *)i1;
6346 		v6group = v6_mreqp->ipv6mr_multiaddr;
6347 		ifaddr = INADDR_ANY;
6348 		ifindex = v6_mreqp->ipv6mr_interface;
6349 	} else {
6350 		v4_mreqp = (struct ip_mreq *)i1;
6351 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6352 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6353 		ifindex = 0;
6354 	}
6355 
6356 	/*
6357 	 * In the multirouting case, we need to replicate
6358 	 * the request on all interfaces that will take part
6359 	 * in replication.  We do so because multirouting is
6360 	 * reflective, thus we will probably receive multi-
6361 	 * casts on those interfaces.
6362 	 * The ip_multirt_apply_membership() succeeds if
6363 	 * the operation succeeds on at least one interface.
6364 	 */
6365 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6366 		ipaddr_t group;
6367 
6368 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6369 
6370 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6371 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6372 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6373 	} else {
6374 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6375 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6376 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6377 	}
6378 	if (ire != NULL) {
6379 		if (ire->ire_flags & RTF_MULTIRT) {
6380 			error = ip_multirt_apply_membership(optfn, ire, connp,
6381 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6382 			done = B_TRUE;
6383 		}
6384 		ire_refrele(ire);
6385 	}
6386 
6387 	if (!done) {
6388 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6389 		    fmode, &ipv6_all_zeros);
6390 	}
6391 	return (error);
6392 }
6393 
6394 /*
6395  * Set socket options for joining and leaving multicast groups
6396  * for specific sources.
6397  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6398  * The caller has already check that the option name is consistent with
6399  * the address family of the socket.
6400  */
6401 int
6402 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6403     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6404 {
6405 	int		*i1 = (int *)invalp;
6406 	int		error = 0;
6407 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6408 	struct ip_mreq_source *imreqp;
6409 	struct group_source_req *gsreqp;
6410 	in6_addr_t v6group, v6src;
6411 	uint32_t ifindex;
6412 	ipaddr_t ifaddr;
6413 	boolean_t mcast_opt = B_TRUE;
6414 	mcast_record_t fmode;
6415 	ire_t *ire;
6416 	boolean_t done = B_FALSE;
6417 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6418 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6419 
6420 	switch (name) {
6421 	case IP_BLOCK_SOURCE:
6422 		mcast_opt = B_FALSE;
6423 		/* FALLTHRU */
6424 	case MCAST_BLOCK_SOURCE:
6425 		fmode = MODE_IS_EXCLUDE;
6426 		optfn = ip_opt_add_group;
6427 		break;
6428 
6429 	case IP_UNBLOCK_SOURCE:
6430 		mcast_opt = B_FALSE;
6431 		/* FALLTHRU */
6432 	case MCAST_UNBLOCK_SOURCE:
6433 		fmode = MODE_IS_EXCLUDE;
6434 		optfn = ip_opt_delete_group;
6435 		break;
6436 
6437 	case IP_ADD_SOURCE_MEMBERSHIP:
6438 		mcast_opt = B_FALSE;
6439 		/* FALLTHRU */
6440 	case MCAST_JOIN_SOURCE_GROUP:
6441 		fmode = MODE_IS_INCLUDE;
6442 		optfn = ip_opt_add_group;
6443 		break;
6444 
6445 	case IP_DROP_SOURCE_MEMBERSHIP:
6446 		mcast_opt = B_FALSE;
6447 		/* FALLTHRU */
6448 	case MCAST_LEAVE_SOURCE_GROUP:
6449 		fmode = MODE_IS_INCLUDE;
6450 		optfn = ip_opt_delete_group;
6451 		break;
6452 	default:
6453 		ASSERT(0);
6454 	}
6455 
6456 	if (mcast_opt) {
6457 		gsreqp = (struct group_source_req *)i1;
6458 		ifindex = gsreqp->gsr_interface;
6459 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6460 			struct sockaddr_in *s;
6461 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6462 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6463 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6464 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6465 		} else {
6466 			struct sockaddr_in6 *s6;
6467 
6468 			if (!inet6)
6469 				return (EINVAL);	/* Not on INET socket */
6470 
6471 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6472 			v6group = s6->sin6_addr;
6473 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6474 			v6src = s6->sin6_addr;
6475 		}
6476 		ifaddr = INADDR_ANY;
6477 	} else {
6478 		imreqp = (struct ip_mreq_source *)i1;
6479 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6480 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6481 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6482 		ifindex = 0;
6483 	}
6484 
6485 	/*
6486 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6487 	 */
6488 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6489 		v6src = ipv6_all_zeros;
6490 
6491 	/*
6492 	 * In the multirouting case, we need to replicate
6493 	 * the request as noted in the mcast cases above.
6494 	 */
6495 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6496 		ipaddr_t group;
6497 
6498 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6499 
6500 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6501 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6502 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6503 	} else {
6504 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6505 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6506 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6507 	}
6508 	if (ire != NULL) {
6509 		if (ire->ire_flags & RTF_MULTIRT) {
6510 			error = ip_multirt_apply_membership(optfn, ire, connp,
6511 			    checkonly, &v6group, fmode, &v6src);
6512 			done = B_TRUE;
6513 		}
6514 		ire_refrele(ire);
6515 	}
6516 	if (!done) {
6517 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6518 		    fmode, &v6src);
6519 	}
6520 	return (error);
6521 }
6522 
6523 /*
6524  * Given a destination address and a pointer to where to put the information
6525  * this routine fills in the mtuinfo.
6526  * The socket must be connected.
6527  * For sctp conn_faddr is the primary address.
6528  */
6529 int
6530 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6531 {
6532 	uint32_t	pmtu = IP_MAXPACKET;
6533 	uint_t		scopeid;
6534 
6535 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6536 		return (-1);
6537 
6538 	/* In case we never sent or called ip_set_destination_v4/v6 */
6539 	if (ixa->ixa_ire != NULL)
6540 		pmtu = ip_get_pmtu(ixa);
6541 
6542 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6543 		scopeid = ixa->ixa_scopeid;
6544 	else
6545 		scopeid = 0;
6546 
6547 	bzero(mtuinfo, sizeof (*mtuinfo));
6548 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6549 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6550 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6551 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6552 	mtuinfo->ip6m_mtu = pmtu;
6553 
6554 	return (sizeof (struct ip6_mtuinfo));
6555 }
6556 
6557 /*
6558  * When the src multihoming is changed from weak to [strong, preferred]
6559  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6560  * and identify routes that were created by user-applications in the
6561  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6562  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6563  * is selected by finding an interface route for the gateway.
6564  */
6565 /* ARGSUSED */
6566 void
6567 ip_ire_rebind_walker(ire_t *ire, void *notused)
6568 {
6569 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6570 		return;
6571 	ire_rebind(ire);
6572 	ire_delete(ire);
6573 }
6574 
6575 /*
6576  * When the src multihoming is changed from  [strong, preferred] to weak,
6577  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6578  * set any entries that were created by user-applications in the unbound state
6579  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6580  */
6581 /* ARGSUSED */
6582 void
6583 ip_ire_unbind_walker(ire_t *ire, void *notused)
6584 {
6585 	ire_t *new_ire;
6586 
6587 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6588 		return;
6589 	if (ire->ire_ipversion == IPV6_VERSION) {
6590 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6591 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6592 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6593 	} else {
6594 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6595 		    (uchar_t *)&ire->ire_mask,
6596 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6597 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6598 	}
6599 	if (new_ire == NULL)
6600 		return;
6601 	new_ire->ire_unbound = B_TRUE;
6602 	/*
6603 	 * The bound ire must first be deleted so that we don't return
6604 	 * the existing one on the attempt to add the unbound new_ire.
6605 	 */
6606 	ire_delete(ire);
6607 	new_ire = ire_add(new_ire);
6608 	if (new_ire != NULL)
6609 		ire_refrele(new_ire);
6610 }
6611 
6612 /*
6613  * When the settings of ip*_strict_src_multihoming tunables are changed,
6614  * all cached routes need to be recomputed. This recomputation needs to be
6615  * done when going from weaker to stronger modes so that the cached ire
6616  * for the connection does not violate the current ip*_strict_src_multihoming
6617  * setting. It also needs to be done when going from stronger to weaker modes,
6618  * so that we fall back to matching on the longest-matching-route (as opposed
6619  * to a shorter match that may have been selected in the strong mode
6620  * to satisfy src_multihoming settings).
6621  *
6622  * The cached ixa_ire entires for all conn_t entries are marked as
6623  * "verify" so that they will be recomputed for the next packet.
6624  */
6625 void
6626 conn_ire_revalidate(conn_t *connp, void *arg)
6627 {
6628 	boolean_t isv6 = (boolean_t)arg;
6629 
6630 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6631 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6632 		return;
6633 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6634 }
6635 
6636 /*
6637  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6638  * When an ipf is passed here for the first time, if
6639  * we already have in-order fragments on the queue, we convert from the fast-
6640  * path reassembly scheme to the hard-case scheme.  From then on, additional
6641  * fragments are reassembled here.  We keep track of the start and end offsets
6642  * of each piece, and the number of holes in the chain.  When the hole count
6643  * goes to zero, we are done!
6644  *
6645  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6646  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6647  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6648  * after the call to ip_reassemble().
6649  */
6650 int
6651 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6652     size_t msg_len)
6653 {
6654 	uint_t	end;
6655 	mblk_t	*next_mp;
6656 	mblk_t	*mp1;
6657 	uint_t	offset;
6658 	boolean_t incr_dups = B_TRUE;
6659 	boolean_t offset_zero_seen = B_FALSE;
6660 	boolean_t pkt_boundary_checked = B_FALSE;
6661 
6662 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6663 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6664 
6665 	/* Add in byte count */
6666 	ipf->ipf_count += msg_len;
6667 	if (ipf->ipf_end) {
6668 		/*
6669 		 * We were part way through in-order reassembly, but now there
6670 		 * is a hole.  We walk through messages already queued, and
6671 		 * mark them for hard case reassembly.  We know that up till
6672 		 * now they were in order starting from offset zero.
6673 		 */
6674 		offset = 0;
6675 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6676 			IP_REASS_SET_START(mp1, offset);
6677 			if (offset == 0) {
6678 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6679 				offset = -ipf->ipf_nf_hdr_len;
6680 			}
6681 			offset += mp1->b_wptr - mp1->b_rptr;
6682 			IP_REASS_SET_END(mp1, offset);
6683 		}
6684 		/* One hole at the end. */
6685 		ipf->ipf_hole_cnt = 1;
6686 		/* Brand it as a hard case, forever. */
6687 		ipf->ipf_end = 0;
6688 	}
6689 	/* Walk through all the new pieces. */
6690 	do {
6691 		end = start + (mp->b_wptr - mp->b_rptr);
6692 		/*
6693 		 * If start is 0, decrease 'end' only for the first mblk of
6694 		 * the fragment. Otherwise 'end' can get wrong value in the
6695 		 * second pass of the loop if first mblk is exactly the
6696 		 * size of ipf_nf_hdr_len.
6697 		 */
6698 		if (start == 0 && !offset_zero_seen) {
6699 			/* First segment */
6700 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6701 			end -= ipf->ipf_nf_hdr_len;
6702 			offset_zero_seen = B_TRUE;
6703 		}
6704 		next_mp = mp->b_cont;
6705 		/*
6706 		 * We are checking to see if there is any interesing data
6707 		 * to process.  If there isn't and the mblk isn't the
6708 		 * one which carries the unfragmentable header then we
6709 		 * drop it.  It's possible to have just the unfragmentable
6710 		 * header come through without any data.  That needs to be
6711 		 * saved.
6712 		 *
6713 		 * If the assert at the top of this function holds then the
6714 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6715 		 * is infrequently traveled enough that the test is left in
6716 		 * to protect against future code changes which break that
6717 		 * invariant.
6718 		 */
6719 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6720 			/* Empty.  Blast it. */
6721 			IP_REASS_SET_START(mp, 0);
6722 			IP_REASS_SET_END(mp, 0);
6723 			/*
6724 			 * If the ipf points to the mblk we are about to free,
6725 			 * update ipf to point to the next mblk (or NULL
6726 			 * if none).
6727 			 */
6728 			if (ipf->ipf_mp->b_cont == mp)
6729 				ipf->ipf_mp->b_cont = next_mp;
6730 			freeb(mp);
6731 			continue;
6732 		}
6733 		mp->b_cont = NULL;
6734 		IP_REASS_SET_START(mp, start);
6735 		IP_REASS_SET_END(mp, end);
6736 		if (!ipf->ipf_tail_mp) {
6737 			ipf->ipf_tail_mp = mp;
6738 			ipf->ipf_mp->b_cont = mp;
6739 			if (start == 0 || !more) {
6740 				ipf->ipf_hole_cnt = 1;
6741 				/*
6742 				 * if the first fragment comes in more than one
6743 				 * mblk, this loop will be executed for each
6744 				 * mblk. Need to adjust hole count so exiting
6745 				 * this routine will leave hole count at 1.
6746 				 */
6747 				if (next_mp)
6748 					ipf->ipf_hole_cnt++;
6749 			} else
6750 				ipf->ipf_hole_cnt = 2;
6751 			continue;
6752 		} else if (ipf->ipf_last_frag_seen && !more &&
6753 		    !pkt_boundary_checked) {
6754 			/*
6755 			 * We check datagram boundary only if this fragment
6756 			 * claims to be the last fragment and we have seen a
6757 			 * last fragment in the past too. We do this only
6758 			 * once for a given fragment.
6759 			 *
6760 			 * start cannot be 0 here as fragments with start=0
6761 			 * and MF=0 gets handled as a complete packet. These
6762 			 * fragments should not reach here.
6763 			 */
6764 
6765 			if (start + msgdsize(mp) !=
6766 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6767 				/*
6768 				 * We have two fragments both of which claim
6769 				 * to be the last fragment but gives conflicting
6770 				 * information about the whole datagram size.
6771 				 * Something fishy is going on. Drop the
6772 				 * fragment and free up the reassembly list.
6773 				 */
6774 				return (IP_REASS_FAILED);
6775 			}
6776 
6777 			/*
6778 			 * We shouldn't come to this code block again for this
6779 			 * particular fragment.
6780 			 */
6781 			pkt_boundary_checked = B_TRUE;
6782 		}
6783 
6784 		/* New stuff at or beyond tail? */
6785 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6786 		if (start >= offset) {
6787 			if (ipf->ipf_last_frag_seen) {
6788 				/* current fragment is beyond last fragment */
6789 				return (IP_REASS_FAILED);
6790 			}
6791 			/* Link it on end. */
6792 			ipf->ipf_tail_mp->b_cont = mp;
6793 			ipf->ipf_tail_mp = mp;
6794 			if (more) {
6795 				if (start != offset)
6796 					ipf->ipf_hole_cnt++;
6797 			} else if (start == offset && next_mp == NULL)
6798 					ipf->ipf_hole_cnt--;
6799 			continue;
6800 		}
6801 		mp1 = ipf->ipf_mp->b_cont;
6802 		offset = IP_REASS_START(mp1);
6803 		/* New stuff at the front? */
6804 		if (start < offset) {
6805 			if (start == 0) {
6806 				if (end >= offset) {
6807 					/* Nailed the hole at the begining. */
6808 					ipf->ipf_hole_cnt--;
6809 				}
6810 			} else if (end < offset) {
6811 				/*
6812 				 * A hole, stuff, and a hole where there used
6813 				 * to be just a hole.
6814 				 */
6815 				ipf->ipf_hole_cnt++;
6816 			}
6817 			mp->b_cont = mp1;
6818 			/* Check for overlap. */
6819 			while (end > offset) {
6820 				if (end < IP_REASS_END(mp1)) {
6821 					mp->b_wptr -= end - offset;
6822 					IP_REASS_SET_END(mp, offset);
6823 					BUMP_MIB(ill->ill_ip_mib,
6824 					    ipIfStatsReasmPartDups);
6825 					break;
6826 				}
6827 				/* Did we cover another hole? */
6828 				if ((mp1->b_cont &&
6829 				    IP_REASS_END(mp1) !=
6830 				    IP_REASS_START(mp1->b_cont) &&
6831 				    end >= IP_REASS_START(mp1->b_cont)) ||
6832 				    (!ipf->ipf_last_frag_seen && !more)) {
6833 					ipf->ipf_hole_cnt--;
6834 				}
6835 				/* Clip out mp1. */
6836 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6837 					/*
6838 					 * After clipping out mp1, this guy
6839 					 * is now hanging off the end.
6840 					 */
6841 					ipf->ipf_tail_mp = mp;
6842 				}
6843 				IP_REASS_SET_START(mp1, 0);
6844 				IP_REASS_SET_END(mp1, 0);
6845 				/* Subtract byte count */
6846 				ipf->ipf_count -= mp1->b_datap->db_lim -
6847 				    mp1->b_datap->db_base;
6848 				freeb(mp1);
6849 				BUMP_MIB(ill->ill_ip_mib,
6850 				    ipIfStatsReasmPartDups);
6851 				mp1 = mp->b_cont;
6852 				if (!mp1)
6853 					break;
6854 				offset = IP_REASS_START(mp1);
6855 			}
6856 			ipf->ipf_mp->b_cont = mp;
6857 			continue;
6858 		}
6859 		/*
6860 		 * The new piece starts somewhere between the start of the head
6861 		 * and before the end of the tail.
6862 		 */
6863 		for (; mp1; mp1 = mp1->b_cont) {
6864 			offset = IP_REASS_END(mp1);
6865 			if (start < offset) {
6866 				if (end <= offset) {
6867 					/* Nothing new. */
6868 					IP_REASS_SET_START(mp, 0);
6869 					IP_REASS_SET_END(mp, 0);
6870 					/* Subtract byte count */
6871 					ipf->ipf_count -= mp->b_datap->db_lim -
6872 					    mp->b_datap->db_base;
6873 					if (incr_dups) {
6874 						ipf->ipf_num_dups++;
6875 						incr_dups = B_FALSE;
6876 					}
6877 					freeb(mp);
6878 					BUMP_MIB(ill->ill_ip_mib,
6879 					    ipIfStatsReasmDuplicates);
6880 					break;
6881 				}
6882 				/*
6883 				 * Trim redundant stuff off beginning of new
6884 				 * piece.
6885 				 */
6886 				IP_REASS_SET_START(mp, offset);
6887 				mp->b_rptr += offset - start;
6888 				BUMP_MIB(ill->ill_ip_mib,
6889 				    ipIfStatsReasmPartDups);
6890 				start = offset;
6891 				if (!mp1->b_cont) {
6892 					/*
6893 					 * After trimming, this guy is now
6894 					 * hanging off the end.
6895 					 */
6896 					mp1->b_cont = mp;
6897 					ipf->ipf_tail_mp = mp;
6898 					if (!more) {
6899 						ipf->ipf_hole_cnt--;
6900 					}
6901 					break;
6902 				}
6903 			}
6904 			if (start >= IP_REASS_START(mp1->b_cont))
6905 				continue;
6906 			/* Fill a hole */
6907 			if (start > offset)
6908 				ipf->ipf_hole_cnt++;
6909 			mp->b_cont = mp1->b_cont;
6910 			mp1->b_cont = mp;
6911 			mp1 = mp->b_cont;
6912 			offset = IP_REASS_START(mp1);
6913 			if (end >= offset) {
6914 				ipf->ipf_hole_cnt--;
6915 				/* Check for overlap. */
6916 				while (end > offset) {
6917 					if (end < IP_REASS_END(mp1)) {
6918 						mp->b_wptr -= end - offset;
6919 						IP_REASS_SET_END(mp, offset);
6920 						/*
6921 						 * TODO we might bump
6922 						 * this up twice if there is
6923 						 * overlap at both ends.
6924 						 */
6925 						BUMP_MIB(ill->ill_ip_mib,
6926 						    ipIfStatsReasmPartDups);
6927 						break;
6928 					}
6929 					/* Did we cover another hole? */
6930 					if ((mp1->b_cont &&
6931 					    IP_REASS_END(mp1)
6932 					    != IP_REASS_START(mp1->b_cont) &&
6933 					    end >=
6934 					    IP_REASS_START(mp1->b_cont)) ||
6935 					    (!ipf->ipf_last_frag_seen &&
6936 					    !more)) {
6937 						ipf->ipf_hole_cnt--;
6938 					}
6939 					/* Clip out mp1. */
6940 					if ((mp->b_cont = mp1->b_cont) ==
6941 					    NULL) {
6942 						/*
6943 						 * After clipping out mp1,
6944 						 * this guy is now hanging
6945 						 * off the end.
6946 						 */
6947 						ipf->ipf_tail_mp = mp;
6948 					}
6949 					IP_REASS_SET_START(mp1, 0);
6950 					IP_REASS_SET_END(mp1, 0);
6951 					/* Subtract byte count */
6952 					ipf->ipf_count -=
6953 					    mp1->b_datap->db_lim -
6954 					    mp1->b_datap->db_base;
6955 					freeb(mp1);
6956 					BUMP_MIB(ill->ill_ip_mib,
6957 					    ipIfStatsReasmPartDups);
6958 					mp1 = mp->b_cont;
6959 					if (!mp1)
6960 						break;
6961 					offset = IP_REASS_START(mp1);
6962 				}
6963 			}
6964 			break;
6965 		}
6966 	} while (start = end, mp = next_mp);
6967 
6968 	/* Fragment just processed could be the last one. Remember this fact */
6969 	if (!more)
6970 		ipf->ipf_last_frag_seen = B_TRUE;
6971 
6972 	/* Still got holes? */
6973 	if (ipf->ipf_hole_cnt)
6974 		return (IP_REASS_PARTIAL);
6975 	/* Clean up overloaded fields to avoid upstream disasters. */
6976 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6977 		IP_REASS_SET_START(mp1, 0);
6978 		IP_REASS_SET_END(mp1, 0);
6979 	}
6980 	return (IP_REASS_COMPLETE);
6981 }
6982 
6983 /*
6984  * Fragmentation reassembly.  Each ILL has a hash table for
6985  * queuing packets undergoing reassembly for all IPIFs
6986  * associated with the ILL.  The hash is based on the packet
6987  * IP ident field.  The ILL frag hash table was allocated
6988  * as a timer block at the time the ILL was created.  Whenever
6989  * there is anything on the reassembly queue, the timer will
6990  * be running.  Returns the reassembled packet if reassembly completes.
6991  */
6992 mblk_t *
6993 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
6994 {
6995 	uint32_t	frag_offset_flags;
6996 	mblk_t		*t_mp;
6997 	ipaddr_t	dst;
6998 	uint8_t		proto = ipha->ipha_protocol;
6999 	uint32_t	sum_val;
7000 	uint16_t	sum_flags;
7001 	ipf_t		*ipf;
7002 	ipf_t		**ipfp;
7003 	ipfb_t		*ipfb;
7004 	uint16_t	ident;
7005 	uint32_t	offset;
7006 	ipaddr_t	src;
7007 	uint_t		hdr_length;
7008 	uint32_t	end;
7009 	mblk_t		*mp1;
7010 	mblk_t		*tail_mp;
7011 	size_t		count;
7012 	size_t		msg_len;
7013 	uint8_t		ecn_info = 0;
7014 	uint32_t	packet_size;
7015 	boolean_t	pruned = B_FALSE;
7016 	ill_t		*ill = ira->ira_ill;
7017 	ip_stack_t	*ipst = ill->ill_ipst;
7018 
7019 	/*
7020 	 * Drop the fragmented as early as possible, if
7021 	 * we don't have resource(s) to re-assemble.
7022 	 */
7023 	if (ipst->ips_ip_reass_queue_bytes == 0) {
7024 		freemsg(mp);
7025 		return (NULL);
7026 	}
7027 
7028 	/* Check for fragmentation offset; return if there's none */
7029 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
7030 	    (IPH_MF | IPH_OFFSET)) == 0)
7031 		return (mp);
7032 
7033 	/*
7034 	 * We utilize hardware computed checksum info only for UDP since
7035 	 * IP fragmentation is a normal occurrence for the protocol.  In
7036 	 * addition, checksum offload support for IP fragments carrying
7037 	 * UDP payload is commonly implemented across network adapters.
7038 	 */
7039 	ASSERT(ira->ira_rill != NULL);
7040 	if (proto == IPPROTO_UDP && dohwcksum &&
7041 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
7042 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
7043 		mblk_t *mp1 = mp->b_cont;
7044 		int32_t len;
7045 
7046 		/* Record checksum information from the packet */
7047 		sum_val = (uint32_t)DB_CKSUM16(mp);
7048 		sum_flags = DB_CKSUMFLAGS(mp);
7049 
7050 		/* IP payload offset from beginning of mblk */
7051 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7052 
7053 		if ((sum_flags & HCK_PARTIALCKSUM) &&
7054 		    (mp1 == NULL || mp1->b_cont == NULL) &&
7055 		    offset >= DB_CKSUMSTART(mp) &&
7056 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7057 			uint32_t adj;
7058 			/*
7059 			 * Partial checksum has been calculated by hardware
7060 			 * and attached to the packet; in addition, any
7061 			 * prepended extraneous data is even byte aligned.
7062 			 * If any such data exists, we adjust the checksum;
7063 			 * this would also handle any postpended data.
7064 			 */
7065 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7066 			    mp, mp1, len, adj);
7067 
7068 			/* One's complement subtract extraneous checksum */
7069 			if (adj >= sum_val)
7070 				sum_val = ~(adj - sum_val) & 0xFFFF;
7071 			else
7072 				sum_val -= adj;
7073 		}
7074 	} else {
7075 		sum_val = 0;
7076 		sum_flags = 0;
7077 	}
7078 
7079 	/* Clear hardware checksumming flag */
7080 	DB_CKSUMFLAGS(mp) = 0;
7081 
7082 	ident = ipha->ipha_ident;
7083 	offset = (frag_offset_flags << 3) & 0xFFFF;
7084 	src = ipha->ipha_src;
7085 	dst = ipha->ipha_dst;
7086 	hdr_length = IPH_HDR_LENGTH(ipha);
7087 	end = ntohs(ipha->ipha_length) - hdr_length;
7088 
7089 	/* If end == 0 then we have a packet with no data, so just free it */
7090 	if (end == 0) {
7091 		freemsg(mp);
7092 		return (NULL);
7093 	}
7094 
7095 	/* Record the ECN field info. */
7096 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7097 	if (offset != 0) {
7098 		/*
7099 		 * If this isn't the first piece, strip the header, and
7100 		 * add the offset to the end value.
7101 		 */
7102 		mp->b_rptr += hdr_length;
7103 		end += offset;
7104 	}
7105 
7106 	/* Handle vnic loopback of fragments */
7107 	if (mp->b_datap->db_ref > 2)
7108 		msg_len = 0;
7109 	else
7110 		msg_len = MBLKSIZE(mp);
7111 
7112 	tail_mp = mp;
7113 	while (tail_mp->b_cont != NULL) {
7114 		tail_mp = tail_mp->b_cont;
7115 		if (tail_mp->b_datap->db_ref <= 2)
7116 			msg_len += MBLKSIZE(tail_mp);
7117 	}
7118 
7119 	/* If the reassembly list for this ILL will get too big, prune it */
7120 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7121 	    ipst->ips_ip_reass_queue_bytes) {
7122 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7123 		    uint_t, ill->ill_frag_count,
7124 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7125 		ill_frag_prune(ill,
7126 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7127 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7128 		pruned = B_TRUE;
7129 	}
7130 
7131 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7132 	mutex_enter(&ipfb->ipfb_lock);
7133 
7134 	ipfp = &ipfb->ipfb_ipf;
7135 	/* Try to find an existing fragment queue for this packet. */
7136 	for (;;) {
7137 		ipf = ipfp[0];
7138 		if (ipf != NULL) {
7139 			/*
7140 			 * It has to match on ident and src/dst address.
7141 			 */
7142 			if (ipf->ipf_ident == ident &&
7143 			    ipf->ipf_src == src &&
7144 			    ipf->ipf_dst == dst &&
7145 			    ipf->ipf_protocol == proto) {
7146 				/*
7147 				 * If we have received too many
7148 				 * duplicate fragments for this packet
7149 				 * free it.
7150 				 */
7151 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7152 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7153 					freemsg(mp);
7154 					mutex_exit(&ipfb->ipfb_lock);
7155 					return (NULL);
7156 				}
7157 				/* Found it. */
7158 				break;
7159 			}
7160 			ipfp = &ipf->ipf_hash_next;
7161 			continue;
7162 		}
7163 
7164 		/*
7165 		 * If we pruned the list, do we want to store this new
7166 		 * fragment?. We apply an optimization here based on the
7167 		 * fact that most fragments will be received in order.
7168 		 * So if the offset of this incoming fragment is zero,
7169 		 * it is the first fragment of a new packet. We will
7170 		 * keep it.  Otherwise drop the fragment, as we have
7171 		 * probably pruned the packet already (since the
7172 		 * packet cannot be found).
7173 		 */
7174 		if (pruned && offset != 0) {
7175 			mutex_exit(&ipfb->ipfb_lock);
7176 			freemsg(mp);
7177 			return (NULL);
7178 		}
7179 
7180 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7181 			/*
7182 			 * Too many fragmented packets in this hash
7183 			 * bucket. Free the oldest.
7184 			 */
7185 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7186 		}
7187 
7188 		/* New guy.  Allocate a frag message. */
7189 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7190 		if (mp1 == NULL) {
7191 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7192 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7193 			freemsg(mp);
7194 reass_done:
7195 			mutex_exit(&ipfb->ipfb_lock);
7196 			return (NULL);
7197 		}
7198 
7199 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7200 		mp1->b_cont = mp;
7201 
7202 		/* Initialize the fragment header. */
7203 		ipf = (ipf_t *)mp1->b_rptr;
7204 		ipf->ipf_mp = mp1;
7205 		ipf->ipf_ptphn = ipfp;
7206 		ipfp[0] = ipf;
7207 		ipf->ipf_hash_next = NULL;
7208 		ipf->ipf_ident = ident;
7209 		ipf->ipf_protocol = proto;
7210 		ipf->ipf_src = src;
7211 		ipf->ipf_dst = dst;
7212 		ipf->ipf_nf_hdr_len = 0;
7213 		/* Record reassembly start time. */
7214 		ipf->ipf_timestamp = gethrestime_sec();
7215 		/* Record ipf generation and account for frag header */
7216 		ipf->ipf_gen = ill->ill_ipf_gen++;
7217 		ipf->ipf_count = MBLKSIZE(mp1);
7218 		ipf->ipf_last_frag_seen = B_FALSE;
7219 		ipf->ipf_ecn = ecn_info;
7220 		ipf->ipf_num_dups = 0;
7221 		ipfb->ipfb_frag_pkts++;
7222 		ipf->ipf_checksum = 0;
7223 		ipf->ipf_checksum_flags = 0;
7224 
7225 		/* Store checksum value in fragment header */
7226 		if (sum_flags != 0) {
7227 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7228 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7229 			ipf->ipf_checksum = sum_val;
7230 			ipf->ipf_checksum_flags = sum_flags;
7231 		}
7232 
7233 		/*
7234 		 * We handle reassembly two ways.  In the easy case,
7235 		 * where all the fragments show up in order, we do
7236 		 * minimal bookkeeping, and just clip new pieces on
7237 		 * the end.  If we ever see a hole, then we go off
7238 		 * to ip_reassemble which has to mark the pieces and
7239 		 * keep track of the number of holes, etc.  Obviously,
7240 		 * the point of having both mechanisms is so we can
7241 		 * handle the easy case as efficiently as possible.
7242 		 */
7243 		if (offset == 0) {
7244 			/* Easy case, in-order reassembly so far. */
7245 			ipf->ipf_count += msg_len;
7246 			ipf->ipf_tail_mp = tail_mp;
7247 			/*
7248 			 * Keep track of next expected offset in
7249 			 * ipf_end.
7250 			 */
7251 			ipf->ipf_end = end;
7252 			ipf->ipf_nf_hdr_len = hdr_length;
7253 		} else {
7254 			/* Hard case, hole at the beginning. */
7255 			ipf->ipf_tail_mp = NULL;
7256 			/*
7257 			 * ipf_end == 0 means that we have given up
7258 			 * on easy reassembly.
7259 			 */
7260 			ipf->ipf_end = 0;
7261 
7262 			/* Forget checksum offload from now on */
7263 			ipf->ipf_checksum_flags = 0;
7264 
7265 			/*
7266 			 * ipf_hole_cnt is set by ip_reassemble.
7267 			 * ipf_count is updated by ip_reassemble.
7268 			 * No need to check for return value here
7269 			 * as we don't expect reassembly to complete
7270 			 * or fail for the first fragment itself.
7271 			 */
7272 			(void) ip_reassemble(mp, ipf,
7273 			    (frag_offset_flags & IPH_OFFSET) << 3,
7274 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7275 		}
7276 		/* Update per ipfb and ill byte counts */
7277 		ipfb->ipfb_count += ipf->ipf_count;
7278 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7279 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7280 		/* If the frag timer wasn't already going, start it. */
7281 		mutex_enter(&ill->ill_lock);
7282 		ill_frag_timer_start(ill);
7283 		mutex_exit(&ill->ill_lock);
7284 		goto reass_done;
7285 	}
7286 
7287 	/*
7288 	 * If the packet's flag has changed (it could be coming up
7289 	 * from an interface different than the previous, therefore
7290 	 * possibly different checksum capability), then forget about
7291 	 * any stored checksum states.  Otherwise add the value to
7292 	 * the existing one stored in the fragment header.
7293 	 */
7294 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7295 		sum_val += ipf->ipf_checksum;
7296 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7297 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7298 		ipf->ipf_checksum = sum_val;
7299 	} else if (ipf->ipf_checksum_flags != 0) {
7300 		/* Forget checksum offload from now on */
7301 		ipf->ipf_checksum_flags = 0;
7302 	}
7303 
7304 	/*
7305 	 * We have a new piece of a datagram which is already being
7306 	 * reassembled.  Update the ECN info if all IP fragments
7307 	 * are ECN capable.  If there is one which is not, clear
7308 	 * all the info.  If there is at least one which has CE
7309 	 * code point, IP needs to report that up to transport.
7310 	 */
7311 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7312 		if (ecn_info == IPH_ECN_CE)
7313 			ipf->ipf_ecn = IPH_ECN_CE;
7314 	} else {
7315 		ipf->ipf_ecn = IPH_ECN_NECT;
7316 	}
7317 	if (offset && ipf->ipf_end == offset) {
7318 		/* The new fragment fits at the end */
7319 		ipf->ipf_tail_mp->b_cont = mp;
7320 		/* Update the byte count */
7321 		ipf->ipf_count += msg_len;
7322 		/* Update per ipfb and ill byte counts */
7323 		ipfb->ipfb_count += msg_len;
7324 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7325 		atomic_add_32(&ill->ill_frag_count, msg_len);
7326 		if (frag_offset_flags & IPH_MF) {
7327 			/* More to come. */
7328 			ipf->ipf_end = end;
7329 			ipf->ipf_tail_mp = tail_mp;
7330 			goto reass_done;
7331 		}
7332 	} else {
7333 		/* Go do the hard cases. */
7334 		int ret;
7335 
7336 		if (offset == 0)
7337 			ipf->ipf_nf_hdr_len = hdr_length;
7338 
7339 		/* Save current byte count */
7340 		count = ipf->ipf_count;
7341 		ret = ip_reassemble(mp, ipf,
7342 		    (frag_offset_flags & IPH_OFFSET) << 3,
7343 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7344 		/* Count of bytes added and subtracted (freeb()ed) */
7345 		count = ipf->ipf_count - count;
7346 		if (count) {
7347 			/* Update per ipfb and ill byte counts */
7348 			ipfb->ipfb_count += count;
7349 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7350 			atomic_add_32(&ill->ill_frag_count, count);
7351 		}
7352 		if (ret == IP_REASS_PARTIAL) {
7353 			goto reass_done;
7354 		} else if (ret == IP_REASS_FAILED) {
7355 			/* Reassembly failed. Free up all resources */
7356 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7357 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7358 				IP_REASS_SET_START(t_mp, 0);
7359 				IP_REASS_SET_END(t_mp, 0);
7360 			}
7361 			freemsg(mp);
7362 			goto reass_done;
7363 		}
7364 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7365 	}
7366 	/*
7367 	 * We have completed reassembly.  Unhook the frag header from
7368 	 * the reassembly list.
7369 	 *
7370 	 * Before we free the frag header, record the ECN info
7371 	 * to report back to the transport.
7372 	 */
7373 	ecn_info = ipf->ipf_ecn;
7374 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7375 	ipfp = ipf->ipf_ptphn;
7376 
7377 	/* We need to supply these to caller */
7378 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7379 		sum_val = ipf->ipf_checksum;
7380 	else
7381 		sum_val = 0;
7382 
7383 	mp1 = ipf->ipf_mp;
7384 	count = ipf->ipf_count;
7385 	ipf = ipf->ipf_hash_next;
7386 	if (ipf != NULL)
7387 		ipf->ipf_ptphn = ipfp;
7388 	ipfp[0] = ipf;
7389 	atomic_add_32(&ill->ill_frag_count, -count);
7390 	ASSERT(ipfb->ipfb_count >= count);
7391 	ipfb->ipfb_count -= count;
7392 	ipfb->ipfb_frag_pkts--;
7393 	mutex_exit(&ipfb->ipfb_lock);
7394 	/* Ditch the frag header. */
7395 	mp = mp1->b_cont;
7396 
7397 	freeb(mp1);
7398 
7399 	/* Restore original IP length in header. */
7400 	packet_size = (uint32_t)msgdsize(mp);
7401 	if (packet_size > IP_MAXPACKET) {
7402 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7403 		ip_drop_input("Reassembled packet too large", mp, ill);
7404 		freemsg(mp);
7405 		return (NULL);
7406 	}
7407 
7408 	if (DB_REF(mp) > 1) {
7409 		mblk_t *mp2 = copymsg(mp);
7410 
7411 		if (mp2 == NULL) {
7412 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7413 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7414 			freemsg(mp);
7415 			return (NULL);
7416 		}
7417 		freemsg(mp);
7418 		mp = mp2;
7419 	}
7420 	ipha = (ipha_t *)mp->b_rptr;
7421 
7422 	ipha->ipha_length = htons((uint16_t)packet_size);
7423 	/* We're now complete, zip the frag state */
7424 	ipha->ipha_fragment_offset_and_flags = 0;
7425 	/* Record the ECN info. */
7426 	ipha->ipha_type_of_service &= 0xFC;
7427 	ipha->ipha_type_of_service |= ecn_info;
7428 
7429 	/* Update the receive attributes */
7430 	ira->ira_pktlen = packet_size;
7431 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7432 
7433 	/* Reassembly is successful; set checksum information in packet */
7434 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7435 	DB_CKSUMFLAGS(mp) = sum_flags;
7436 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7437 
7438 	return (mp);
7439 }
7440 
7441 /*
7442  * Pullup function that should be used for IP input in order to
7443  * ensure we do not loose the L2 source address; we need the l2 source
7444  * address for IP_RECVSLLA and for ndp_input.
7445  *
7446  * We return either NULL or b_rptr.
7447  */
7448 void *
7449 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7450 {
7451 	ill_t		*ill = ira->ira_ill;
7452 
7453 	if (ip_rput_pullups++ == 0) {
7454 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7455 		    "ip_pullup: %s forced us to "
7456 		    " pullup pkt, hdr len %ld, hdr addr %p",
7457 		    ill->ill_name, len, (void *)mp->b_rptr);
7458 	}
7459 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7460 		ip_setl2src(mp, ira, ira->ira_rill);
7461 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7462 	if (!pullupmsg(mp, len))
7463 		return (NULL);
7464 	else
7465 		return (mp->b_rptr);
7466 }
7467 
7468 /*
7469  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7470  * When called from the ULP ira_rill will be NULL hence the caller has to
7471  * pass in the ill.
7472  */
7473 /* ARGSUSED */
7474 void
7475 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7476 {
7477 	const uchar_t *addr;
7478 	int alen;
7479 
7480 	if (ira->ira_flags & IRAF_L2SRC_SET)
7481 		return;
7482 
7483 	ASSERT(ill != NULL);
7484 	alen = ill->ill_phys_addr_length;
7485 	ASSERT(alen <= sizeof (ira->ira_l2src));
7486 	if (ira->ira_mhip != NULL &&
7487 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7488 		bcopy(addr, ira->ira_l2src, alen);
7489 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7490 	    (addr = ill->ill_phys_addr) != NULL) {
7491 		bcopy(addr, ira->ira_l2src, alen);
7492 	} else {
7493 		bzero(ira->ira_l2src, alen);
7494 	}
7495 	ira->ira_flags |= IRAF_L2SRC_SET;
7496 }
7497 
7498 /*
7499  * check ip header length and align it.
7500  */
7501 mblk_t *
7502 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7503 {
7504 	ill_t	*ill = ira->ira_ill;
7505 	ssize_t len;
7506 
7507 	len = MBLKL(mp);
7508 
7509 	if (!OK_32PTR(mp->b_rptr))
7510 		IP_STAT(ill->ill_ipst, ip_notaligned);
7511 	else
7512 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7513 
7514 	/* Guard against bogus device drivers */
7515 	if (len < 0) {
7516 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7517 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7518 		freemsg(mp);
7519 		return (NULL);
7520 	}
7521 
7522 	if (len == 0) {
7523 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7524 		mblk_t *mp1 = mp->b_cont;
7525 
7526 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7527 			ip_setl2src(mp, ira, ira->ira_rill);
7528 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7529 
7530 		freeb(mp);
7531 		mp = mp1;
7532 		if (mp == NULL)
7533 			return (NULL);
7534 
7535 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7536 			return (mp);
7537 	}
7538 	if (ip_pullup(mp, min_size, ira) == NULL) {
7539 		if (msgdsize(mp) < min_size) {
7540 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7541 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7542 		} else {
7543 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7544 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7545 		}
7546 		freemsg(mp);
7547 		return (NULL);
7548 	}
7549 	return (mp);
7550 }
7551 
7552 /*
7553  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7554  */
7555 mblk_t *
7556 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7557     uint_t min_size, ip_recv_attr_t *ira)
7558 {
7559 	ill_t	*ill = ira->ira_ill;
7560 
7561 	/*
7562 	 * Make sure we have data length consistent
7563 	 * with the IP header.
7564 	 */
7565 	if (mp->b_cont == NULL) {
7566 		/* pkt_len is based on ipha_len, not the mblk length */
7567 		if (pkt_len < min_size) {
7568 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7569 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7570 			freemsg(mp);
7571 			return (NULL);
7572 		}
7573 		if (len < 0) {
7574 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7575 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7576 			freemsg(mp);
7577 			return (NULL);
7578 		}
7579 		/* Drop any pad */
7580 		mp->b_wptr = rptr + pkt_len;
7581 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7582 		ASSERT(pkt_len >= min_size);
7583 		if (pkt_len < min_size) {
7584 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7585 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7586 			freemsg(mp);
7587 			return (NULL);
7588 		}
7589 		if (len < 0) {
7590 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7591 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7592 			freemsg(mp);
7593 			return (NULL);
7594 		}
7595 		/* Drop any pad */
7596 		(void) adjmsg(mp, -len);
7597 		/*
7598 		 * adjmsg may have freed an mblk from the chain, hence
7599 		 * invalidate any hw checksum here. This will force IP to
7600 		 * calculate the checksum in sw, but only for this packet.
7601 		 */
7602 		DB_CKSUMFLAGS(mp) = 0;
7603 		IP_STAT(ill->ill_ipst, ip_multimblk);
7604 	}
7605 	return (mp);
7606 }
7607 
7608 /*
7609  * Check that the IPv4 opt_len is consistent with the packet and pullup
7610  * the options.
7611  */
7612 mblk_t *
7613 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7614     ip_recv_attr_t *ira)
7615 {
7616 	ill_t	*ill = ira->ira_ill;
7617 	ssize_t len;
7618 
7619 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7620 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7621 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7622 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7623 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7624 		freemsg(mp);
7625 		return (NULL);
7626 	}
7627 
7628 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7629 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7630 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7631 		freemsg(mp);
7632 		return (NULL);
7633 	}
7634 	/*
7635 	 * Recompute complete header length and make sure we
7636 	 * have access to all of it.
7637 	 */
7638 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7639 	if (len > (mp->b_wptr - mp->b_rptr)) {
7640 		if (len > pkt_len) {
7641 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7642 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7643 			freemsg(mp);
7644 			return (NULL);
7645 		}
7646 		if (ip_pullup(mp, len, ira) == NULL) {
7647 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7648 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7649 			freemsg(mp);
7650 			return (NULL);
7651 		}
7652 	}
7653 	return (mp);
7654 }
7655 
7656 /*
7657  * Returns a new ire, or the same ire, or NULL.
7658  * If a different IRE is returned, then it is held; the caller
7659  * needs to release it.
7660  * In no case is there any hold/release on the ire argument.
7661  */
7662 ire_t *
7663 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7664 {
7665 	ire_t		*new_ire;
7666 	ill_t		*ire_ill;
7667 	uint_t		ifindex;
7668 	ip_stack_t	*ipst = ill->ill_ipst;
7669 	boolean_t	strict_check = B_FALSE;
7670 
7671 	/*
7672 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7673 	 * issue (e.g. packet received on an underlying interface matched an
7674 	 * IRE_LOCAL on its associated group interface).
7675 	 */
7676 	ASSERT(ire->ire_ill != NULL);
7677 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7678 		return (ire);
7679 
7680 	/*
7681 	 * Do another ire lookup here, using the ingress ill, to see if the
7682 	 * interface is in a usesrc group.
7683 	 * As long as the ills belong to the same group, we don't consider
7684 	 * them to be arriving on the wrong interface. Thus, if the switch
7685 	 * is doing inbound load spreading, we won't drop packets when the
7686 	 * ip*_strict_dst_multihoming switch is on.
7687 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7688 	 * where the local address may not be unique. In this case we were
7689 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7690 	 * actually returned. The new lookup, which is more specific, should
7691 	 * only find the IRE_LOCAL associated with the ingress ill if one
7692 	 * exists.
7693 	 */
7694 	if (ire->ire_ipversion == IPV4_VERSION) {
7695 		if (ipst->ips_ip_strict_dst_multihoming)
7696 			strict_check = B_TRUE;
7697 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7698 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7699 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7700 	} else {
7701 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7702 		if (ipst->ips_ipv6_strict_dst_multihoming)
7703 			strict_check = B_TRUE;
7704 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7705 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7706 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7707 	}
7708 	/*
7709 	 * If the same ire that was returned in ip_input() is found then this
7710 	 * is an indication that usesrc groups are in use. The packet
7711 	 * arrived on a different ill in the group than the one associated with
7712 	 * the destination address.  If a different ire was found then the same
7713 	 * IP address must be hosted on multiple ills. This is possible with
7714 	 * unnumbered point2point interfaces. We switch to use this new ire in
7715 	 * order to have accurate interface statistics.
7716 	 */
7717 	if (new_ire != NULL) {
7718 		/* Note: held in one case but not the other? Caller handles */
7719 		if (new_ire != ire)
7720 			return (new_ire);
7721 		/* Unchanged */
7722 		ire_refrele(new_ire);
7723 		return (ire);
7724 	}
7725 
7726 	/*
7727 	 * Chase pointers once and store locally.
7728 	 */
7729 	ASSERT(ire->ire_ill != NULL);
7730 	ire_ill = ire->ire_ill;
7731 	ifindex = ill->ill_usesrc_ifindex;
7732 
7733 	/*
7734 	 * Check if it's a legal address on the 'usesrc' interface.
7735 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7736 	 * can just check phyint_ifindex.
7737 	 */
7738 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7739 		return (ire);
7740 	}
7741 
7742 	/*
7743 	 * If the ip*_strict_dst_multihoming switch is on then we can
7744 	 * only accept this packet if the interface is marked as routing.
7745 	 */
7746 	if (!(strict_check))
7747 		return (ire);
7748 
7749 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7750 		return (ire);
7751 	}
7752 	return (NULL);
7753 }
7754 
7755 /*
7756  * This function is used to construct a mac_header_info_s from a
7757  * DL_UNITDATA_IND message.
7758  * The address fields in the mhi structure points into the message,
7759  * thus the caller can't use those fields after freeing the message.
7760  *
7761  * We determine whether the packet received is a non-unicast packet
7762  * and in doing so, determine whether or not it is broadcast vs multicast.
7763  * For it to be a broadcast packet, we must have the appropriate mblk_t
7764  * hanging off the ill_t.  If this is either not present or doesn't match
7765  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7766  * to be multicast.  Thus NICs that have no broadcast address (or no
7767  * capability for one, such as point to point links) cannot return as
7768  * the packet being broadcast.
7769  */
7770 void
7771 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7772 {
7773 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7774 	mblk_t *bmp;
7775 	uint_t extra_offset;
7776 
7777 	bzero(mhip, sizeof (struct mac_header_info_s));
7778 
7779 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7780 
7781 	if (ill->ill_sap_length < 0)
7782 		extra_offset = 0;
7783 	else
7784 		extra_offset = ill->ill_sap_length;
7785 
7786 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7787 	    extra_offset;
7788 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7789 	    extra_offset;
7790 
7791 	if (!ind->dl_group_address)
7792 		return;
7793 
7794 	/* Multicast or broadcast */
7795 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7796 
7797 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7798 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7799 	    (bmp = ill->ill_bcast_mp) != NULL) {
7800 		dl_unitdata_req_t *dlur;
7801 		uint8_t *bphys_addr;
7802 
7803 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7804 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7805 		    extra_offset;
7806 
7807 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7808 		    ind->dl_dest_addr_length) == 0)
7809 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7810 	}
7811 }
7812 
7813 /*
7814  * This function is used to construct a mac_header_info_s from a
7815  * M_DATA fastpath message from a DLPI driver.
7816  * The address fields in the mhi structure points into the message,
7817  * thus the caller can't use those fields after freeing the message.
7818  *
7819  * We determine whether the packet received is a non-unicast packet
7820  * and in doing so, determine whether or not it is broadcast vs multicast.
7821  * For it to be a broadcast packet, we must have the appropriate mblk_t
7822  * hanging off the ill_t.  If this is either not present or doesn't match
7823  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7824  * to be multicast.  Thus NICs that have no broadcast address (or no
7825  * capability for one, such as point to point links) cannot return as
7826  * the packet being broadcast.
7827  */
7828 void
7829 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7830 {
7831 	mblk_t *bmp;
7832 	struct ether_header *pether;
7833 
7834 	bzero(mhip, sizeof (struct mac_header_info_s));
7835 
7836 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7837 
7838 	pether = (struct ether_header *)((char *)mp->b_rptr
7839 	    - sizeof (struct ether_header));
7840 
7841 	/*
7842 	 * Make sure the interface is an ethernet type, since we don't
7843 	 * know the header format for anything but Ethernet. Also make
7844 	 * sure we are pointing correctly above db_base.
7845 	 */
7846 	if (ill->ill_type != IFT_ETHER)
7847 		return;
7848 
7849 retry:
7850 	if ((uchar_t *)pether < mp->b_datap->db_base)
7851 		return;
7852 
7853 	/* Is there a VLAN tag? */
7854 	if (ill->ill_isv6) {
7855 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7856 			pether = (struct ether_header *)((char *)pether - 4);
7857 			goto retry;
7858 		}
7859 	} else {
7860 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
7861 			pether = (struct ether_header *)((char *)pether - 4);
7862 			goto retry;
7863 		}
7864 	}
7865 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7866 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7867 
7868 	if (!(mhip->mhi_daddr[0] & 0x01))
7869 		return;
7870 
7871 	/* Multicast or broadcast */
7872 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7873 
7874 	if ((bmp = ill->ill_bcast_mp) != NULL) {
7875 		dl_unitdata_req_t *dlur;
7876 		uint8_t *bphys_addr;
7877 		uint_t	addrlen;
7878 
7879 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7880 		addrlen = dlur->dl_dest_addr_length;
7881 		if (ill->ill_sap_length < 0) {
7882 			bphys_addr = (uchar_t *)dlur +
7883 			    dlur->dl_dest_addr_offset;
7884 			addrlen += ill->ill_sap_length;
7885 		} else {
7886 			bphys_addr = (uchar_t *)dlur +
7887 			    dlur->dl_dest_addr_offset +
7888 			    ill->ill_sap_length;
7889 			addrlen -= ill->ill_sap_length;
7890 		}
7891 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7892 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7893 	}
7894 }
7895 
7896 /*
7897  * Handle anything but M_DATA messages
7898  * We see the DL_UNITDATA_IND which are part
7899  * of the data path, and also the other messages from the driver.
7900  */
7901 void
7902 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7903 {
7904 	mblk_t		*first_mp;
7905 	struct iocblk   *iocp;
7906 	struct mac_header_info_s mhi;
7907 
7908 	switch (DB_TYPE(mp)) {
7909 	case M_PROTO:
7910 	case M_PCPROTO: {
7911 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7912 		    DL_UNITDATA_IND) {
7913 			/* Go handle anything other than data elsewhere. */
7914 			ip_rput_dlpi(ill, mp);
7915 			return;
7916 		}
7917 
7918 		first_mp = mp;
7919 		mp = first_mp->b_cont;
7920 		first_mp->b_cont = NULL;
7921 
7922 		if (mp == NULL) {
7923 			freeb(first_mp);
7924 			return;
7925 		}
7926 		ip_dlur_to_mhi(ill, first_mp, &mhi);
7927 		if (ill->ill_isv6)
7928 			ip_input_v6(ill, NULL, mp, &mhi);
7929 		else
7930 			ip_input(ill, NULL, mp, &mhi);
7931 
7932 		/* Ditch the DLPI header. */
7933 		freeb(first_mp);
7934 		return;
7935 	}
7936 	case M_IOCACK:
7937 		iocp = (struct iocblk *)mp->b_rptr;
7938 		switch (iocp->ioc_cmd) {
7939 		case DL_IOC_HDR_INFO:
7940 			ill_fastpath_ack(ill, mp);
7941 			return;
7942 		default:
7943 			putnext(ill->ill_rq, mp);
7944 			return;
7945 		}
7946 		/* FALLTHRU */
7947 	case M_ERROR:
7948 	case M_HANGUP:
7949 		mutex_enter(&ill->ill_lock);
7950 		if (ill->ill_state_flags & ILL_CONDEMNED) {
7951 			mutex_exit(&ill->ill_lock);
7952 			freemsg(mp);
7953 			return;
7954 		}
7955 		ill_refhold_locked(ill);
7956 		mutex_exit(&ill->ill_lock);
7957 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7958 		    B_FALSE);
7959 		return;
7960 	case M_CTL:
7961 		putnext(ill->ill_rq, mp);
7962 		return;
7963 	case M_IOCNAK:
7964 		ip1dbg(("got iocnak "));
7965 		iocp = (struct iocblk *)mp->b_rptr;
7966 		switch (iocp->ioc_cmd) {
7967 		case DL_IOC_HDR_INFO:
7968 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7969 			return;
7970 		default:
7971 			break;
7972 		}
7973 		/* FALLTHRU */
7974 	default:
7975 		putnext(ill->ill_rq, mp);
7976 		return;
7977 	}
7978 }
7979 
7980 /* Read side put procedure.  Packets coming from the wire arrive here. */
7981 void
7982 ip_rput(queue_t *q, mblk_t *mp)
7983 {
7984 	ill_t	*ill;
7985 	union DL_primitives *dl;
7986 
7987 	ill = (ill_t *)q->q_ptr;
7988 
7989 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
7990 		/*
7991 		 * If things are opening or closing, only accept high-priority
7992 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
7993 		 * created; on close, things hanging off the ill may have been
7994 		 * freed already.)
7995 		 */
7996 		dl = (union DL_primitives *)mp->b_rptr;
7997 		if (DB_TYPE(mp) != M_PCPROTO ||
7998 		    dl->dl_primitive == DL_UNITDATA_IND) {
7999 			inet_freemsg(mp);
8000 			return;
8001 		}
8002 	}
8003 	if (DB_TYPE(mp) == M_DATA) {
8004 		struct mac_header_info_s mhi;
8005 
8006 		ip_mdata_to_mhi(ill, mp, &mhi);
8007 		ip_input(ill, NULL, mp, &mhi);
8008 	} else {
8009 		ip_rput_notdata(ill, mp);
8010 	}
8011 }
8012 
8013 /*
8014  * Move the information to a copy.
8015  */
8016 mblk_t *
8017 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
8018 {
8019 	mblk_t		*mp1;
8020 	ill_t		*ill = ira->ira_ill;
8021 	ip_stack_t	*ipst = ill->ill_ipst;
8022 
8023 	IP_STAT(ipst, ip_db_ref);
8024 
8025 	/* Make sure we have ira_l2src before we loose the original mblk */
8026 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
8027 		ip_setl2src(mp, ira, ira->ira_rill);
8028 
8029 	mp1 = copymsg(mp);
8030 	if (mp1 == NULL) {
8031 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
8032 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
8033 		freemsg(mp);
8034 		return (NULL);
8035 	}
8036 	/* preserve the hardware checksum flags and data, if present */
8037 	if (DB_CKSUMFLAGS(mp) != 0) {
8038 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
8039 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
8040 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
8041 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
8042 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
8043 	}
8044 	freemsg(mp);
8045 	return (mp1);
8046 }
8047 
8048 static void
8049 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8050     t_uscalar_t err)
8051 {
8052 	if (dl_err == DL_SYSERR) {
8053 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8054 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
8055 		    ill->ill_name, dl_primstr(prim), err);
8056 		return;
8057 	}
8058 
8059 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8060 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8061 	    dl_errstr(dl_err));
8062 }
8063 
8064 /*
8065  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8066  * than DL_UNITDATA_IND messages. If we need to process this message
8067  * exclusively, we call qwriter_ip, in which case we also need to call
8068  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8069  */
8070 void
8071 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8072 {
8073 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8074 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8075 	queue_t		*q = ill->ill_rq;
8076 	t_uscalar_t	prim = dloa->dl_primitive;
8077 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8078 
8079 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8080 	    char *, dl_primstr(prim), ill_t *, ill);
8081 	ip1dbg(("ip_rput_dlpi"));
8082 
8083 	/*
8084 	 * If we received an ACK but didn't send a request for it, then it
8085 	 * can't be part of any pending operation; discard up-front.
8086 	 */
8087 	switch (prim) {
8088 	case DL_ERROR_ACK:
8089 		reqprim = dlea->dl_error_primitive;
8090 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8091 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8092 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8093 		    dlea->dl_unix_errno));
8094 		break;
8095 	case DL_OK_ACK:
8096 		reqprim = dloa->dl_correct_primitive;
8097 		break;
8098 	case DL_INFO_ACK:
8099 		reqprim = DL_INFO_REQ;
8100 		break;
8101 	case DL_BIND_ACK:
8102 		reqprim = DL_BIND_REQ;
8103 		break;
8104 	case DL_PHYS_ADDR_ACK:
8105 		reqprim = DL_PHYS_ADDR_REQ;
8106 		break;
8107 	case DL_NOTIFY_ACK:
8108 		reqprim = DL_NOTIFY_REQ;
8109 		break;
8110 	case DL_CAPABILITY_ACK:
8111 		reqprim = DL_CAPABILITY_REQ;
8112 		break;
8113 	}
8114 
8115 	if (prim != DL_NOTIFY_IND) {
8116 		if (reqprim == DL_PRIM_INVAL ||
8117 		    !ill_dlpi_pending(ill, reqprim)) {
8118 			/* Not a DLPI message we support or expected */
8119 			freemsg(mp);
8120 			return;
8121 		}
8122 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8123 		    dl_primstr(reqprim)));
8124 	}
8125 
8126 	switch (reqprim) {
8127 	case DL_UNBIND_REQ:
8128 		/*
8129 		 * NOTE: we mark the unbind as complete even if we got a
8130 		 * DL_ERROR_ACK, since there's not much else we can do.
8131 		 */
8132 		mutex_enter(&ill->ill_lock);
8133 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8134 		cv_signal(&ill->ill_cv);
8135 		mutex_exit(&ill->ill_lock);
8136 		break;
8137 
8138 	case DL_ENABMULTI_REQ:
8139 		if (prim == DL_OK_ACK) {
8140 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8141 				ill->ill_dlpi_multicast_state = IDS_OK;
8142 		}
8143 		break;
8144 	}
8145 
8146 	/*
8147 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8148 	 * need to become writer to continue to process it.  Because an
8149 	 * exclusive operation doesn't complete until replies to all queued
8150 	 * DLPI messages have been received, we know we're in the middle of an
8151 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8152 	 *
8153 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8154 	 * Since this is on the ill stream we unconditionally bump up the
8155 	 * refcount without doing ILL_CAN_LOOKUP().
8156 	 */
8157 	ill_refhold(ill);
8158 	if (prim == DL_NOTIFY_IND)
8159 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8160 	else
8161 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8162 }
8163 
8164 /*
8165  * Handling of DLPI messages that require exclusive access to the ipsq.
8166  *
8167  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8168  * happen here. (along with mi_copy_done)
8169  */
8170 /* ARGSUSED */
8171 static void
8172 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8173 {
8174 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8175 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8176 	int		err = 0;
8177 	ill_t		*ill = (ill_t *)q->q_ptr;
8178 	ipif_t		*ipif = NULL;
8179 	mblk_t		*mp1 = NULL;
8180 	conn_t		*connp = NULL;
8181 	t_uscalar_t	paddrreq;
8182 	mblk_t		*mp_hw;
8183 	boolean_t	success;
8184 	boolean_t	ioctl_aborted = B_FALSE;
8185 	boolean_t	log = B_TRUE;
8186 
8187 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8188 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8189 
8190 	ip1dbg(("ip_rput_dlpi_writer .."));
8191 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8192 	ASSERT(IAM_WRITER_ILL(ill));
8193 
8194 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8195 	/*
8196 	 * The current ioctl could have been aborted by the user and a new
8197 	 * ioctl to bring up another ill could have started. We could still
8198 	 * get a response from the driver later.
8199 	 */
8200 	if (ipif != NULL && ipif->ipif_ill != ill)
8201 		ioctl_aborted = B_TRUE;
8202 
8203 	switch (dloa->dl_primitive) {
8204 	case DL_ERROR_ACK:
8205 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8206 		    dl_primstr(dlea->dl_error_primitive)));
8207 
8208 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8209 		    char *, dl_primstr(dlea->dl_error_primitive),
8210 		    ill_t *, ill);
8211 
8212 		switch (dlea->dl_error_primitive) {
8213 		case DL_DISABMULTI_REQ:
8214 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8215 			break;
8216 		case DL_PROMISCON_REQ:
8217 		case DL_PROMISCOFF_REQ:
8218 		case DL_UNBIND_REQ:
8219 		case DL_ATTACH_REQ:
8220 		case DL_INFO_REQ:
8221 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8222 			break;
8223 		case DL_NOTIFY_REQ:
8224 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8225 			log = B_FALSE;
8226 			break;
8227 		case DL_PHYS_ADDR_REQ:
8228 			/*
8229 			 * For IPv6 only, there are two additional
8230 			 * phys_addr_req's sent to the driver to get the
8231 			 * IPv6 token and lla. This allows IP to acquire
8232 			 * the hardware address format for a given interface
8233 			 * without having built in knowledge of the hardware
8234 			 * address. ill_phys_addr_pend keeps track of the last
8235 			 * DL_PAR sent so we know which response we are
8236 			 * dealing with. ill_dlpi_done will update
8237 			 * ill_phys_addr_pend when it sends the next req.
8238 			 * We don't complete the IOCTL until all three DL_PARs
8239 			 * have been attempted, so set *_len to 0 and break.
8240 			 */
8241 			paddrreq = ill->ill_phys_addr_pend;
8242 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8243 			if (paddrreq == DL_IPV6_TOKEN) {
8244 				ill->ill_token_length = 0;
8245 				log = B_FALSE;
8246 				break;
8247 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8248 				ill->ill_nd_lla_len = 0;
8249 				log = B_FALSE;
8250 				break;
8251 			}
8252 			/*
8253 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8254 			 * We presumably have an IOCTL hanging out waiting
8255 			 * for completion. Find it and complete the IOCTL
8256 			 * with the error noted.
8257 			 * However, ill_dl_phys was called on an ill queue
8258 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8259 			 * set. But the ioctl is known to be pending on ill_wq.
8260 			 */
8261 			if (!ill->ill_ifname_pending)
8262 				break;
8263 			ill->ill_ifname_pending = 0;
8264 			if (!ioctl_aborted)
8265 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8266 			if (mp1 != NULL) {
8267 				/*
8268 				 * This operation (SIOCSLIFNAME) must have
8269 				 * happened on the ill. Assert there is no conn
8270 				 */
8271 				ASSERT(connp == NULL);
8272 				q = ill->ill_wq;
8273 			}
8274 			break;
8275 		case DL_BIND_REQ:
8276 			ill_dlpi_done(ill, DL_BIND_REQ);
8277 			if (ill->ill_ifname_pending)
8278 				break;
8279 			mutex_enter(&ill->ill_lock);
8280 			ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8281 			mutex_exit(&ill->ill_lock);
8282 			/*
8283 			 * Something went wrong with the bind.  We presumably
8284 			 * have an IOCTL hanging out waiting for completion.
8285 			 * Find it, take down the interface that was coming
8286 			 * up, and complete the IOCTL with the error noted.
8287 			 */
8288 			if (!ioctl_aborted)
8289 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8290 			if (mp1 != NULL) {
8291 				/*
8292 				 * This might be a result of a DL_NOTE_REPLUMB
8293 				 * notification. In that case, connp is NULL.
8294 				 */
8295 				if (connp != NULL)
8296 					q = CONNP_TO_WQ(connp);
8297 
8298 				(void) ipif_down(ipif, NULL, NULL);
8299 				/* error is set below the switch */
8300 			}
8301 			break;
8302 		case DL_ENABMULTI_REQ:
8303 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8304 
8305 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8306 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8307 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8308 
8309 				printf("ip: joining multicasts failed (%d)"
8310 				    " on %s - will use link layer "
8311 				    "broadcasts for multicast\n",
8312 				    dlea->dl_errno, ill->ill_name);
8313 
8314 				/*
8315 				 * Set up for multi_bcast; We are the
8316 				 * writer, so ok to access ill->ill_ipif
8317 				 * without any lock.
8318 				 */
8319 				mutex_enter(&ill->ill_phyint->phyint_lock);
8320 				ill->ill_phyint->phyint_flags |=
8321 				    PHYI_MULTI_BCAST;
8322 				mutex_exit(&ill->ill_phyint->phyint_lock);
8323 
8324 			}
8325 			freemsg(mp);	/* Don't want to pass this up */
8326 			return;
8327 		case DL_CAPABILITY_REQ:
8328 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8329 			    "DL_CAPABILITY REQ\n"));
8330 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8331 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8332 			ill_capability_done(ill);
8333 			freemsg(mp);
8334 			return;
8335 		}
8336 		/*
8337 		 * Note the error for IOCTL completion (mp1 is set when
8338 		 * ready to complete ioctl). If ill_ifname_pending_err is
8339 		 * set, an error occured during plumbing (ill_ifname_pending),
8340 		 * so we want to report that error.
8341 		 *
8342 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8343 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8344 		 * expected to get errack'd if the driver doesn't support
8345 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8346 		 * if these error conditions are encountered.
8347 		 */
8348 		if (mp1 != NULL) {
8349 			if (ill->ill_ifname_pending_err != 0)  {
8350 				err = ill->ill_ifname_pending_err;
8351 				ill->ill_ifname_pending_err = 0;
8352 			} else {
8353 				err = dlea->dl_unix_errno ?
8354 				    dlea->dl_unix_errno : ENXIO;
8355 			}
8356 		/*
8357 		 * If we're plumbing an interface and an error hasn't already
8358 		 * been saved, set ill_ifname_pending_err to the error passed
8359 		 * up. Ignore the error if log is B_FALSE (see comment above).
8360 		 */
8361 		} else if (log && ill->ill_ifname_pending &&
8362 		    ill->ill_ifname_pending_err == 0) {
8363 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8364 			    dlea->dl_unix_errno : ENXIO;
8365 		}
8366 
8367 		if (log)
8368 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8369 			    dlea->dl_errno, dlea->dl_unix_errno);
8370 		break;
8371 	case DL_CAPABILITY_ACK:
8372 		ill_capability_ack(ill, mp);
8373 		/*
8374 		 * The message has been handed off to ill_capability_ack
8375 		 * and must not be freed below
8376 		 */
8377 		mp = NULL;
8378 		break;
8379 
8380 	case DL_INFO_ACK:
8381 		/* Call a routine to handle this one. */
8382 		ill_dlpi_done(ill, DL_INFO_REQ);
8383 		ip_ll_subnet_defaults(ill, mp);
8384 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8385 		return;
8386 	case DL_BIND_ACK:
8387 		/*
8388 		 * We should have an IOCTL waiting on this unless
8389 		 * sent by ill_dl_phys, in which case just return
8390 		 */
8391 		ill_dlpi_done(ill, DL_BIND_REQ);
8392 
8393 		if (ill->ill_ifname_pending) {
8394 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8395 			    ill_t *, ill, mblk_t *, mp);
8396 			break;
8397 		}
8398 		mutex_enter(&ill->ill_lock);
8399 		ill->ill_dl_up = 1;
8400 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8401 		mutex_exit(&ill->ill_lock);
8402 
8403 		if (!ioctl_aborted)
8404 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8405 		if (mp1 == NULL) {
8406 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8407 			break;
8408 		}
8409 		/*
8410 		 * mp1 was added by ill_dl_up(). if that is a result of
8411 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8412 		 */
8413 		if (connp != NULL)
8414 			q = CONNP_TO_WQ(connp);
8415 		/*
8416 		 * We are exclusive. So nothing can change even after
8417 		 * we get the pending mp.
8418 		 */
8419 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8420 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8421 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8422 
8423 		/*
8424 		 * Now bring up the resolver; when that is complete, we'll
8425 		 * create IREs.  Note that we intentionally mirror what
8426 		 * ipif_up() would have done, because we got here by way of
8427 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8428 		 */
8429 		if (ill->ill_isv6) {
8430 			/*
8431 			 * v6 interfaces.
8432 			 * Unlike ARP which has to do another bind
8433 			 * and attach, once we get here we are
8434 			 * done with NDP
8435 			 */
8436 			(void) ipif_resolver_up(ipif, Res_act_initial);
8437 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8438 				err = ipif_up_done_v6(ipif);
8439 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8440 			/*
8441 			 * ARP and other v4 external resolvers.
8442 			 * Leave the pending mblk intact so that
8443 			 * the ioctl completes in ip_rput().
8444 			 */
8445 			if (connp != NULL)
8446 				mutex_enter(&connp->conn_lock);
8447 			mutex_enter(&ill->ill_lock);
8448 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8449 			mutex_exit(&ill->ill_lock);
8450 			if (connp != NULL)
8451 				mutex_exit(&connp->conn_lock);
8452 			if (success) {
8453 				err = ipif_resolver_up(ipif, Res_act_initial);
8454 				if (err == EINPROGRESS) {
8455 					freemsg(mp);
8456 					return;
8457 				}
8458 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8459 			} else {
8460 				/* The conn has started closing */
8461 				err = EINTR;
8462 			}
8463 		} else {
8464 			/*
8465 			 * This one is complete. Reply to pending ioctl.
8466 			 */
8467 			(void) ipif_resolver_up(ipif, Res_act_initial);
8468 			err = ipif_up_done(ipif);
8469 		}
8470 
8471 		if ((err == 0) && (ill->ill_up_ipifs)) {
8472 			err = ill_up_ipifs(ill, q, mp1);
8473 			if (err == EINPROGRESS) {
8474 				freemsg(mp);
8475 				return;
8476 			}
8477 		}
8478 
8479 		/*
8480 		 * If we have a moved ipif to bring up, and everything has
8481 		 * succeeded to this point, bring it up on the IPMP ill.
8482 		 * Otherwise, leave it down -- the admin can try to bring it
8483 		 * up by hand if need be.
8484 		 */
8485 		if (ill->ill_move_ipif != NULL) {
8486 			if (err != 0) {
8487 				ill->ill_move_ipif = NULL;
8488 			} else {
8489 				ipif = ill->ill_move_ipif;
8490 				ill->ill_move_ipif = NULL;
8491 				err = ipif_up(ipif, q, mp1);
8492 				if (err == EINPROGRESS) {
8493 					freemsg(mp);
8494 					return;
8495 				}
8496 			}
8497 		}
8498 		break;
8499 
8500 	case DL_NOTIFY_IND: {
8501 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8502 		uint_t orig_mtu, orig_mc_mtu;
8503 
8504 		switch (notify->dl_notification) {
8505 		case DL_NOTE_PHYS_ADDR:
8506 			err = ill_set_phys_addr(ill, mp);
8507 			break;
8508 
8509 		case DL_NOTE_REPLUMB:
8510 			/*
8511 			 * Directly return after calling ill_replumb().
8512 			 * Note that we should not free mp as it is reused
8513 			 * in the ill_replumb() function.
8514 			 */
8515 			err = ill_replumb(ill, mp);
8516 			return;
8517 
8518 		case DL_NOTE_FASTPATH_FLUSH:
8519 			nce_flush(ill, B_FALSE);
8520 			break;
8521 
8522 		case DL_NOTE_SDU_SIZE:
8523 		case DL_NOTE_SDU_SIZE2:
8524 			/*
8525 			 * The dce and fragmentation code can cope with
8526 			 * this changing while packets are being sent.
8527 			 * When packets are sent ip_output will discover
8528 			 * a change.
8529 			 *
8530 			 * Change the MTU size of the interface.
8531 			 */
8532 			mutex_enter(&ill->ill_lock);
8533 			orig_mtu = ill->ill_mtu;
8534 			orig_mc_mtu = ill->ill_mc_mtu;
8535 			switch (notify->dl_notification) {
8536 			case DL_NOTE_SDU_SIZE:
8537 				ill->ill_current_frag =
8538 				    (uint_t)notify->dl_data;
8539 				ill->ill_mc_mtu = (uint_t)notify->dl_data;
8540 				break;
8541 			case DL_NOTE_SDU_SIZE2:
8542 				ill->ill_current_frag =
8543 				    (uint_t)notify->dl_data1;
8544 				ill->ill_mc_mtu = (uint_t)notify->dl_data2;
8545 				break;
8546 			}
8547 			if (ill->ill_current_frag > ill->ill_max_frag)
8548 				ill->ill_max_frag = ill->ill_current_frag;
8549 
8550 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8551 				ill->ill_mtu = ill->ill_current_frag;
8552 
8553 				/*
8554 				 * If ill_user_mtu was set (via
8555 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8556 				 */
8557 				if (ill->ill_user_mtu != 0 &&
8558 				    ill->ill_user_mtu < ill->ill_mtu)
8559 					ill->ill_mtu = ill->ill_user_mtu;
8560 
8561 				if (ill->ill_user_mtu != 0 &&
8562 				    ill->ill_user_mtu < ill->ill_mc_mtu)
8563 					ill->ill_mc_mtu = ill->ill_user_mtu;
8564 
8565 				if (ill->ill_isv6) {
8566 					if (ill->ill_mtu < IPV6_MIN_MTU)
8567 						ill->ill_mtu = IPV6_MIN_MTU;
8568 					if (ill->ill_mc_mtu < IPV6_MIN_MTU)
8569 						ill->ill_mc_mtu = IPV6_MIN_MTU;
8570 				} else {
8571 					if (ill->ill_mtu < IP_MIN_MTU)
8572 						ill->ill_mtu = IP_MIN_MTU;
8573 					if (ill->ill_mc_mtu < IP_MIN_MTU)
8574 						ill->ill_mc_mtu = IP_MIN_MTU;
8575 				}
8576 			} else if (ill->ill_mc_mtu > ill->ill_mtu) {
8577 				ill->ill_mc_mtu = ill->ill_mtu;
8578 			}
8579 
8580 			mutex_exit(&ill->ill_lock);
8581 			/*
8582 			 * Make sure all dce_generation checks find out
8583 			 * that ill_mtu/ill_mc_mtu has changed.
8584 			 */
8585 			if (orig_mtu != ill->ill_mtu ||
8586 			    orig_mc_mtu != ill->ill_mc_mtu) {
8587 				dce_increment_all_generations(ill->ill_isv6,
8588 				    ill->ill_ipst);
8589 			}
8590 
8591 			/*
8592 			 * Refresh IPMP meta-interface MTU if necessary.
8593 			 */
8594 			if (IS_UNDER_IPMP(ill))
8595 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8596 			break;
8597 
8598 		case DL_NOTE_LINK_UP:
8599 		case DL_NOTE_LINK_DOWN: {
8600 			/*
8601 			 * We are writer. ill / phyint / ipsq assocs stable.
8602 			 * The RUNNING flag reflects the state of the link.
8603 			 */
8604 			phyint_t *phyint = ill->ill_phyint;
8605 			uint64_t new_phyint_flags;
8606 			boolean_t changed = B_FALSE;
8607 			boolean_t went_up;
8608 
8609 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8610 			mutex_enter(&phyint->phyint_lock);
8611 
8612 			new_phyint_flags = went_up ?
8613 			    phyint->phyint_flags | PHYI_RUNNING :
8614 			    phyint->phyint_flags & ~PHYI_RUNNING;
8615 
8616 			if (IS_IPMP(ill)) {
8617 				new_phyint_flags = went_up ?
8618 				    new_phyint_flags & ~PHYI_FAILED :
8619 				    new_phyint_flags | PHYI_FAILED;
8620 			}
8621 
8622 			if (new_phyint_flags != phyint->phyint_flags) {
8623 				phyint->phyint_flags = new_phyint_flags;
8624 				changed = B_TRUE;
8625 			}
8626 			mutex_exit(&phyint->phyint_lock);
8627 			/*
8628 			 * ill_restart_dad handles the DAD restart and routing
8629 			 * socket notification logic.
8630 			 */
8631 			if (changed) {
8632 				ill_restart_dad(phyint->phyint_illv4, went_up);
8633 				ill_restart_dad(phyint->phyint_illv6, went_up);
8634 			}
8635 			break;
8636 		}
8637 		case DL_NOTE_PROMISC_ON_PHYS: {
8638 			phyint_t *phyint = ill->ill_phyint;
8639 
8640 			mutex_enter(&phyint->phyint_lock);
8641 			phyint->phyint_flags |= PHYI_PROMISC;
8642 			mutex_exit(&phyint->phyint_lock);
8643 			break;
8644 		}
8645 		case DL_NOTE_PROMISC_OFF_PHYS: {
8646 			phyint_t *phyint = ill->ill_phyint;
8647 
8648 			mutex_enter(&phyint->phyint_lock);
8649 			phyint->phyint_flags &= ~PHYI_PROMISC;
8650 			mutex_exit(&phyint->phyint_lock);
8651 			break;
8652 		}
8653 		case DL_NOTE_CAPAB_RENEG:
8654 			/*
8655 			 * Something changed on the driver side.
8656 			 * It wants us to renegotiate the capabilities
8657 			 * on this ill. One possible cause is the aggregation
8658 			 * interface under us where a port got added or
8659 			 * went away.
8660 			 *
8661 			 * If the capability negotiation is already done
8662 			 * or is in progress, reset the capabilities and
8663 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8664 			 * so that when the ack comes back, we can start
8665 			 * the renegotiation process.
8666 			 *
8667 			 * Note that if ill_capab_reneg is already B_TRUE
8668 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8669 			 * the capability resetting request has been sent
8670 			 * and the renegotiation has not been started yet;
8671 			 * nothing needs to be done in this case.
8672 			 */
8673 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8674 			ill_capability_reset(ill, B_TRUE);
8675 			ipsq_current_finish(ipsq);
8676 			break;
8677 
8678 		case DL_NOTE_ALLOWED_IPS:
8679 			ill_set_allowed_ips(ill, mp);
8680 			break;
8681 		default:
8682 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8683 			    "type 0x%x for DL_NOTIFY_IND\n",
8684 			    notify->dl_notification));
8685 			break;
8686 		}
8687 
8688 		/*
8689 		 * As this is an asynchronous operation, we
8690 		 * should not call ill_dlpi_done
8691 		 */
8692 		break;
8693 	}
8694 	case DL_NOTIFY_ACK: {
8695 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8696 
8697 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8698 			ill->ill_note_link = 1;
8699 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8700 		break;
8701 	}
8702 	case DL_PHYS_ADDR_ACK: {
8703 		/*
8704 		 * As part of plumbing the interface via SIOCSLIFNAME,
8705 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8706 		 * whose answers we receive here.  As each answer is received,
8707 		 * we call ill_dlpi_done() to dispatch the next request as
8708 		 * we're processing the current one.  Once all answers have
8709 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8710 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8711 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8712 		 * available, but we know the ioctl is pending on ill_wq.)
8713 		 */
8714 		uint_t	paddrlen, paddroff;
8715 		uint8_t	*addr;
8716 
8717 		paddrreq = ill->ill_phys_addr_pend;
8718 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8719 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8720 		addr = mp->b_rptr + paddroff;
8721 
8722 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8723 		if (paddrreq == DL_IPV6_TOKEN) {
8724 			/*
8725 			 * bcopy to low-order bits of ill_token
8726 			 *
8727 			 * XXX Temporary hack - currently, all known tokens
8728 			 * are 64 bits, so I'll cheat for the moment.
8729 			 */
8730 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8731 			ill->ill_token_length = paddrlen;
8732 			break;
8733 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8734 			ASSERT(ill->ill_nd_lla_mp == NULL);
8735 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8736 			mp = NULL;
8737 			break;
8738 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8739 			ASSERT(ill->ill_dest_addr_mp == NULL);
8740 			ill->ill_dest_addr_mp = mp;
8741 			ill->ill_dest_addr = addr;
8742 			mp = NULL;
8743 			if (ill->ill_isv6) {
8744 				ill_setdesttoken(ill);
8745 				ipif_setdestlinklocal(ill->ill_ipif);
8746 			}
8747 			break;
8748 		}
8749 
8750 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8751 		ASSERT(ill->ill_phys_addr_mp == NULL);
8752 		if (!ill->ill_ifname_pending)
8753 			break;
8754 		ill->ill_ifname_pending = 0;
8755 		if (!ioctl_aborted)
8756 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8757 		if (mp1 != NULL) {
8758 			ASSERT(connp == NULL);
8759 			q = ill->ill_wq;
8760 		}
8761 		/*
8762 		 * If any error acks received during the plumbing sequence,
8763 		 * ill_ifname_pending_err will be set. Break out and send up
8764 		 * the error to the pending ioctl.
8765 		 */
8766 		if (ill->ill_ifname_pending_err != 0) {
8767 			err = ill->ill_ifname_pending_err;
8768 			ill->ill_ifname_pending_err = 0;
8769 			break;
8770 		}
8771 
8772 		ill->ill_phys_addr_mp = mp;
8773 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8774 		mp = NULL;
8775 
8776 		/*
8777 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8778 		 * provider doesn't support physical addresses.  We check both
8779 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8780 		 * not have physical addresses, but historically adversises a
8781 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8782 		 * its DL_PHYS_ADDR_ACK.
8783 		 */
8784 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8785 			ill->ill_phys_addr = NULL;
8786 		} else if (paddrlen != ill->ill_phys_addr_length) {
8787 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8788 			    paddrlen, ill->ill_phys_addr_length));
8789 			err = EINVAL;
8790 			break;
8791 		}
8792 
8793 		if (ill->ill_nd_lla_mp == NULL) {
8794 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8795 				err = ENOMEM;
8796 				break;
8797 			}
8798 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8799 		}
8800 
8801 		if (ill->ill_isv6) {
8802 			ill_setdefaulttoken(ill);
8803 			ipif_setlinklocal(ill->ill_ipif);
8804 		}
8805 		break;
8806 	}
8807 	case DL_OK_ACK:
8808 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8809 		    dl_primstr((int)dloa->dl_correct_primitive),
8810 		    dloa->dl_correct_primitive));
8811 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8812 		    char *, dl_primstr(dloa->dl_correct_primitive),
8813 		    ill_t *, ill);
8814 
8815 		switch (dloa->dl_correct_primitive) {
8816 		case DL_ENABMULTI_REQ:
8817 		case DL_DISABMULTI_REQ:
8818 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8819 			break;
8820 		case DL_PROMISCON_REQ:
8821 		case DL_PROMISCOFF_REQ:
8822 		case DL_UNBIND_REQ:
8823 		case DL_ATTACH_REQ:
8824 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8825 			break;
8826 		}
8827 		break;
8828 	default:
8829 		break;
8830 	}
8831 
8832 	freemsg(mp);
8833 	if (mp1 == NULL)
8834 		return;
8835 
8836 	/*
8837 	 * The operation must complete without EINPROGRESS since
8838 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8839 	 * the operation will be stuck forever inside the IPSQ.
8840 	 */
8841 	ASSERT(err != EINPROGRESS);
8842 
8843 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8844 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8845 	    ipif_t *, NULL);
8846 
8847 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8848 	case 0:
8849 		ipsq_current_finish(ipsq);
8850 		break;
8851 
8852 	case SIOCSLIFNAME:
8853 	case IF_UNITSEL: {
8854 		ill_t *ill_other = ILL_OTHER(ill);
8855 
8856 		/*
8857 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8858 		 * ill has a peer which is in an IPMP group, then place ill
8859 		 * into the same group.  One catch: although ifconfig plumbs
8860 		 * the appropriate IPMP meta-interface prior to plumbing this
8861 		 * ill, it is possible for multiple ifconfig applications to
8862 		 * race (or for another application to adjust plumbing), in
8863 		 * which case the IPMP meta-interface we need will be missing.
8864 		 * If so, kick the phyint out of the group.
8865 		 */
8866 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8867 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8868 			ipmp_illgrp_t	*illg;
8869 
8870 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8871 			if (illg == NULL)
8872 				ipmp_phyint_leave_grp(ill->ill_phyint);
8873 			else
8874 				ipmp_ill_join_illgrp(ill, illg);
8875 		}
8876 
8877 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8878 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8879 		else
8880 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8881 		break;
8882 	}
8883 	case SIOCLIFADDIF:
8884 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8885 		break;
8886 
8887 	default:
8888 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8889 		break;
8890 	}
8891 }
8892 
8893 /*
8894  * ip_rput_other is called by ip_rput to handle messages modifying the global
8895  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8896  */
8897 /* ARGSUSED */
8898 void
8899 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8900 {
8901 	ill_t		*ill = q->q_ptr;
8902 	struct iocblk	*iocp;
8903 
8904 	ip1dbg(("ip_rput_other "));
8905 	if (ipsq != NULL) {
8906 		ASSERT(IAM_WRITER_IPSQ(ipsq));
8907 		ASSERT(ipsq->ipsq_xop ==
8908 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
8909 	}
8910 
8911 	switch (mp->b_datap->db_type) {
8912 	case M_ERROR:
8913 	case M_HANGUP:
8914 		/*
8915 		 * The device has a problem.  We force the ILL down.  It can
8916 		 * be brought up again manually using SIOCSIFFLAGS (via
8917 		 * ifconfig or equivalent).
8918 		 */
8919 		ASSERT(ipsq != NULL);
8920 		if (mp->b_rptr < mp->b_wptr)
8921 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8922 		if (ill->ill_error == 0)
8923 			ill->ill_error = ENXIO;
8924 		if (!ill_down_start(q, mp))
8925 			return;
8926 		ipif_all_down_tail(ipsq, q, mp, NULL);
8927 		break;
8928 	case M_IOCNAK: {
8929 		iocp = (struct iocblk *)mp->b_rptr;
8930 
8931 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8932 		/*
8933 		 * If this was the first attempt, turn off the fastpath
8934 		 * probing.
8935 		 */
8936 		mutex_enter(&ill->ill_lock);
8937 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8938 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
8939 			mutex_exit(&ill->ill_lock);
8940 			/*
8941 			 * don't flush the nce_t entries: we use them
8942 			 * as an index to the ncec itself.
8943 			 */
8944 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8945 			    ill->ill_name));
8946 		} else {
8947 			mutex_exit(&ill->ill_lock);
8948 		}
8949 		freemsg(mp);
8950 		break;
8951 	}
8952 	default:
8953 		ASSERT(0);
8954 		break;
8955 	}
8956 }
8957 
8958 /*
8959  * Update any source route, record route or timestamp options
8960  * When it fails it has consumed the message and BUMPed the MIB.
8961  */
8962 boolean_t
8963 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8964     ip_recv_attr_t *ira)
8965 {
8966 	ipoptp_t	opts;
8967 	uchar_t		*opt;
8968 	uint8_t		optval;
8969 	uint8_t		optlen;
8970 	ipaddr_t	dst;
8971 	ipaddr_t	ifaddr;
8972 	uint32_t	ts;
8973 	timestruc_t	now;
8974 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
8975 
8976 	ip2dbg(("ip_forward_options\n"));
8977 	dst = ipha->ipha_dst;
8978 	for (optval = ipoptp_first(&opts, ipha);
8979 	    optval != IPOPT_EOL;
8980 	    optval = ipoptp_next(&opts)) {
8981 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
8982 		opt = opts.ipoptp_cur;
8983 		optlen = opts.ipoptp_len;
8984 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
8985 		    optval, opts.ipoptp_len));
8986 		switch (optval) {
8987 			uint32_t off;
8988 		case IPOPT_SSRR:
8989 		case IPOPT_LSRR:
8990 			/* Check if adminstratively disabled */
8991 			if (!ipst->ips_ip_forward_src_routed) {
8992 				BUMP_MIB(dst_ill->ill_ip_mib,
8993 				    ipIfStatsForwProhibits);
8994 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
8995 				    mp, dst_ill);
8996 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
8997 				    ira);
8998 				return (B_FALSE);
8999 			}
9000 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9001 				/*
9002 				 * Must be partial since ip_input_options
9003 				 * checked for strict.
9004 				 */
9005 				break;
9006 			}
9007 			off = opt[IPOPT_OFFSET];
9008 			off--;
9009 		redo_srr:
9010 			if (optlen < IP_ADDR_LEN ||
9011 			    off > optlen - IP_ADDR_LEN) {
9012 				/* End of source route */
9013 				ip1dbg((
9014 				    "ip_forward_options: end of SR\n"));
9015 				break;
9016 			}
9017 			/* Pick a reasonable address on the outbound if */
9018 			ASSERT(dst_ill != NULL);
9019 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9020 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9021 			    NULL) != 0) {
9022 				/* No source! Shouldn't happen */
9023 				ifaddr = INADDR_ANY;
9024 			}
9025 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9026 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9027 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
9028 			    ntohl(dst)));
9029 
9030 			/*
9031 			 * Check if our address is present more than
9032 			 * once as consecutive hops in source route.
9033 			 */
9034 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9035 				off += IP_ADDR_LEN;
9036 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9037 				goto redo_srr;
9038 			}
9039 			ipha->ipha_dst = dst;
9040 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9041 			break;
9042 		case IPOPT_RR:
9043 			off = opt[IPOPT_OFFSET];
9044 			off--;
9045 			if (optlen < IP_ADDR_LEN ||
9046 			    off > optlen - IP_ADDR_LEN) {
9047 				/* No more room - ignore */
9048 				ip1dbg((
9049 				    "ip_forward_options: end of RR\n"));
9050 				break;
9051 			}
9052 			/* Pick a reasonable address on the outbound if */
9053 			ASSERT(dst_ill != NULL);
9054 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9055 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9056 			    NULL) != 0) {
9057 				/* No source! Shouldn't happen */
9058 				ifaddr = INADDR_ANY;
9059 			}
9060 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9061 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9062 			break;
9063 		case IPOPT_TS:
9064 			/* Insert timestamp if there is room */
9065 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9066 			case IPOPT_TS_TSONLY:
9067 				off = IPOPT_TS_TIMELEN;
9068 				break;
9069 			case IPOPT_TS_PRESPEC:
9070 			case IPOPT_TS_PRESPEC_RFC791:
9071 				/* Verify that the address matched */
9072 				off = opt[IPOPT_OFFSET] - 1;
9073 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9074 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9075 					/* Not for us */
9076 					break;
9077 				}
9078 				/* FALLTHRU */
9079 			case IPOPT_TS_TSANDADDR:
9080 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9081 				break;
9082 			default:
9083 				/*
9084 				 * ip_*put_options should have already
9085 				 * dropped this packet.
9086 				 */
9087 				cmn_err(CE_PANIC, "ip_forward_options: "
9088 				    "unknown IT - bug in ip_input_options?\n");
9089 				return (B_TRUE);	/* Keep "lint" happy */
9090 			}
9091 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9092 				/* Increase overflow counter */
9093 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9094 				opt[IPOPT_POS_OV_FLG] =
9095 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9096 				    (off << 4));
9097 				break;
9098 			}
9099 			off = opt[IPOPT_OFFSET] - 1;
9100 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9101 			case IPOPT_TS_PRESPEC:
9102 			case IPOPT_TS_PRESPEC_RFC791:
9103 			case IPOPT_TS_TSANDADDR:
9104 				/* Pick a reasonable addr on the outbound if */
9105 				ASSERT(dst_ill != NULL);
9106 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9107 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9108 				    NULL, NULL) != 0) {
9109 					/* No source! Shouldn't happen */
9110 					ifaddr = INADDR_ANY;
9111 				}
9112 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9113 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9114 				/* FALLTHRU */
9115 			case IPOPT_TS_TSONLY:
9116 				off = opt[IPOPT_OFFSET] - 1;
9117 				/* Compute # of milliseconds since midnight */
9118 				gethrestime(&now);
9119 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9120 				    NSEC2MSEC(now.tv_nsec);
9121 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9122 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9123 				break;
9124 			}
9125 			break;
9126 		}
9127 	}
9128 	return (B_TRUE);
9129 }
9130 
9131 /*
9132  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9133  * returns 'true' if there are still fragments left on the queue, in
9134  * which case we restart the timer.
9135  */
9136 void
9137 ill_frag_timer(void *arg)
9138 {
9139 	ill_t	*ill = (ill_t *)arg;
9140 	boolean_t frag_pending;
9141 	ip_stack_t *ipst = ill->ill_ipst;
9142 	time_t	timeout;
9143 
9144 	mutex_enter(&ill->ill_lock);
9145 	ASSERT(!ill->ill_fragtimer_executing);
9146 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9147 		ill->ill_frag_timer_id = 0;
9148 		mutex_exit(&ill->ill_lock);
9149 		return;
9150 	}
9151 	ill->ill_fragtimer_executing = 1;
9152 	mutex_exit(&ill->ill_lock);
9153 
9154 	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9155 	    ipst->ips_ip_reassembly_timeout);
9156 
9157 	frag_pending = ill_frag_timeout(ill, timeout);
9158 
9159 	/*
9160 	 * Restart the timer, if we have fragments pending or if someone
9161 	 * wanted us to be scheduled again.
9162 	 */
9163 	mutex_enter(&ill->ill_lock);
9164 	ill->ill_fragtimer_executing = 0;
9165 	ill->ill_frag_timer_id = 0;
9166 	if (frag_pending || ill->ill_fragtimer_needrestart)
9167 		ill_frag_timer_start(ill);
9168 	mutex_exit(&ill->ill_lock);
9169 }
9170 
9171 void
9172 ill_frag_timer_start(ill_t *ill)
9173 {
9174 	ip_stack_t *ipst = ill->ill_ipst;
9175 	clock_t	timeo_ms;
9176 
9177 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9178 
9179 	/* If the ill is closing or opening don't proceed */
9180 	if (ill->ill_state_flags & ILL_CONDEMNED)
9181 		return;
9182 
9183 	if (ill->ill_fragtimer_executing) {
9184 		/*
9185 		 * ill_frag_timer is currently executing. Just record the
9186 		 * the fact that we want the timer to be restarted.
9187 		 * ill_frag_timer will post a timeout before it returns,
9188 		 * ensuring it will be called again.
9189 		 */
9190 		ill->ill_fragtimer_needrestart = 1;
9191 		return;
9192 	}
9193 
9194 	if (ill->ill_frag_timer_id == 0) {
9195 		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9196 		    ipst->ips_ip_reassembly_timeout) * SECONDS;
9197 
9198 		/*
9199 		 * The timer is neither running nor is the timeout handler
9200 		 * executing. Post a timeout so that ill_frag_timer will be
9201 		 * called
9202 		 */
9203 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9204 		    MSEC_TO_TICK(timeo_ms >> 1));
9205 		ill->ill_fragtimer_needrestart = 0;
9206 	}
9207 }
9208 
9209 /*
9210  * Update any source route, record route or timestamp options.
9211  * Check that we are at end of strict source route.
9212  * The options have already been checked for sanity in ip_input_options().
9213  */
9214 boolean_t
9215 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9216 {
9217 	ipoptp_t	opts;
9218 	uchar_t		*opt;
9219 	uint8_t		optval;
9220 	uint8_t		optlen;
9221 	ipaddr_t	dst;
9222 	ipaddr_t	ifaddr;
9223 	uint32_t	ts;
9224 	timestruc_t	now;
9225 	ill_t		*ill = ira->ira_ill;
9226 	ip_stack_t	*ipst = ill->ill_ipst;
9227 
9228 	ip2dbg(("ip_input_local_options\n"));
9229 
9230 	for (optval = ipoptp_first(&opts, ipha);
9231 	    optval != IPOPT_EOL;
9232 	    optval = ipoptp_next(&opts)) {
9233 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9234 		opt = opts.ipoptp_cur;
9235 		optlen = opts.ipoptp_len;
9236 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9237 		    optval, optlen));
9238 		switch (optval) {
9239 			uint32_t off;
9240 		case IPOPT_SSRR:
9241 		case IPOPT_LSRR:
9242 			off = opt[IPOPT_OFFSET];
9243 			off--;
9244 			if (optlen < IP_ADDR_LEN ||
9245 			    off > optlen - IP_ADDR_LEN) {
9246 				/* End of source route */
9247 				ip1dbg(("ip_input_local_options: end of SR\n"));
9248 				break;
9249 			}
9250 			/*
9251 			 * This will only happen if two consecutive entries
9252 			 * in the source route contains our address or if
9253 			 * it is a packet with a loose source route which
9254 			 * reaches us before consuming the whole source route
9255 			 */
9256 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9257 			if (optval == IPOPT_SSRR) {
9258 				goto bad_src_route;
9259 			}
9260 			/*
9261 			 * Hack: instead of dropping the packet truncate the
9262 			 * source route to what has been used by filling the
9263 			 * rest with IPOPT_NOP.
9264 			 */
9265 			opt[IPOPT_OLEN] = (uint8_t)off;
9266 			while (off < optlen) {
9267 				opt[off++] = IPOPT_NOP;
9268 			}
9269 			break;
9270 		case IPOPT_RR:
9271 			off = opt[IPOPT_OFFSET];
9272 			off--;
9273 			if (optlen < IP_ADDR_LEN ||
9274 			    off > optlen - IP_ADDR_LEN) {
9275 				/* No more room - ignore */
9276 				ip1dbg((
9277 				    "ip_input_local_options: end of RR\n"));
9278 				break;
9279 			}
9280 			/* Pick a reasonable address on the outbound if */
9281 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9282 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9283 			    NULL) != 0) {
9284 				/* No source! Shouldn't happen */
9285 				ifaddr = INADDR_ANY;
9286 			}
9287 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9288 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9289 			break;
9290 		case IPOPT_TS:
9291 			/* Insert timestamp if there is romm */
9292 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9293 			case IPOPT_TS_TSONLY:
9294 				off = IPOPT_TS_TIMELEN;
9295 				break;
9296 			case IPOPT_TS_PRESPEC:
9297 			case IPOPT_TS_PRESPEC_RFC791:
9298 				/* Verify that the address matched */
9299 				off = opt[IPOPT_OFFSET] - 1;
9300 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9301 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9302 					/* Not for us */
9303 					break;
9304 				}
9305 				/* FALLTHRU */
9306 			case IPOPT_TS_TSANDADDR:
9307 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9308 				break;
9309 			default:
9310 				/*
9311 				 * ip_*put_options should have already
9312 				 * dropped this packet.
9313 				 */
9314 				cmn_err(CE_PANIC, "ip_input_local_options: "
9315 				    "unknown IT - bug in ip_input_options?\n");
9316 				return (B_TRUE);	/* Keep "lint" happy */
9317 			}
9318 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9319 				/* Increase overflow counter */
9320 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9321 				opt[IPOPT_POS_OV_FLG] =
9322 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9323 				    (off << 4));
9324 				break;
9325 			}
9326 			off = opt[IPOPT_OFFSET] - 1;
9327 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9328 			case IPOPT_TS_PRESPEC:
9329 			case IPOPT_TS_PRESPEC_RFC791:
9330 			case IPOPT_TS_TSANDADDR:
9331 				/* Pick a reasonable addr on the outbound if */
9332 				if (ip_select_source_v4(ill, INADDR_ANY,
9333 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9334 				    &ifaddr, NULL, NULL) != 0) {
9335 					/* No source! Shouldn't happen */
9336 					ifaddr = INADDR_ANY;
9337 				}
9338 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9339 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9340 				/* FALLTHRU */
9341 			case IPOPT_TS_TSONLY:
9342 				off = opt[IPOPT_OFFSET] - 1;
9343 				/* Compute # of milliseconds since midnight */
9344 				gethrestime(&now);
9345 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9346 				    NSEC2MSEC(now.tv_nsec);
9347 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9348 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9349 				break;
9350 			}
9351 			break;
9352 		}
9353 	}
9354 	return (B_TRUE);
9355 
9356 bad_src_route:
9357 	/* make sure we clear any indication of a hardware checksum */
9358 	DB_CKSUMFLAGS(mp) = 0;
9359 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9360 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9361 	return (B_FALSE);
9362 
9363 }
9364 
9365 /*
9366  * Process IP options in an inbound packet.  Always returns the nexthop.
9367  * Normally this is the passed in nexthop, but if there is an option
9368  * that effects the nexthop (such as a source route) that will be returned.
9369  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9370  * and mp freed.
9371  */
9372 ipaddr_t
9373 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9374     ip_recv_attr_t *ira, int *errorp)
9375 {
9376 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9377 	ipoptp_t	opts;
9378 	uchar_t		*opt;
9379 	uint8_t		optval;
9380 	uint8_t		optlen;
9381 	intptr_t	code = 0;
9382 	ire_t		*ire;
9383 
9384 	ip2dbg(("ip_input_options\n"));
9385 	*errorp = 0;
9386 	for (optval = ipoptp_first(&opts, ipha);
9387 	    optval != IPOPT_EOL;
9388 	    optval = ipoptp_next(&opts)) {
9389 		opt = opts.ipoptp_cur;
9390 		optlen = opts.ipoptp_len;
9391 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9392 		    optval, optlen));
9393 		/*
9394 		 * Note: we need to verify the checksum before we
9395 		 * modify anything thus this routine only extracts the next
9396 		 * hop dst from any source route.
9397 		 */
9398 		switch (optval) {
9399 			uint32_t off;
9400 		case IPOPT_SSRR:
9401 		case IPOPT_LSRR:
9402 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9403 				if (optval == IPOPT_SSRR) {
9404 					ip1dbg(("ip_input_options: not next"
9405 					    " strict source route 0x%x\n",
9406 					    ntohl(dst)));
9407 					code = (char *)&ipha->ipha_dst -
9408 					    (char *)ipha;
9409 					goto param_prob; /* RouterReq's */
9410 				}
9411 				ip2dbg(("ip_input_options: "
9412 				    "not next source route 0x%x\n",
9413 				    ntohl(dst)));
9414 				break;
9415 			}
9416 
9417 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9418 				ip1dbg((
9419 				    "ip_input_options: bad option offset\n"));
9420 				code = (char *)&opt[IPOPT_OLEN] -
9421 				    (char *)ipha;
9422 				goto param_prob;
9423 			}
9424 			off = opt[IPOPT_OFFSET];
9425 			off--;
9426 		redo_srr:
9427 			if (optlen < IP_ADDR_LEN ||
9428 			    off > optlen - IP_ADDR_LEN) {
9429 				/* End of source route */
9430 				ip1dbg(("ip_input_options: end of SR\n"));
9431 				break;
9432 			}
9433 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9434 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9435 			    ntohl(dst)));
9436 
9437 			/*
9438 			 * Check if our address is present more than
9439 			 * once as consecutive hops in source route.
9440 			 * XXX verify per-interface ip_forwarding
9441 			 * for source route?
9442 			 */
9443 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9444 				off += IP_ADDR_LEN;
9445 				goto redo_srr;
9446 			}
9447 
9448 			if (dst == htonl(INADDR_LOOPBACK)) {
9449 				ip1dbg(("ip_input_options: loopback addr in "
9450 				    "source route!\n"));
9451 				goto bad_src_route;
9452 			}
9453 			/*
9454 			 * For strict: verify that dst is directly
9455 			 * reachable.
9456 			 */
9457 			if (optval == IPOPT_SSRR) {
9458 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9459 				    IRE_INTERFACE, NULL, ALL_ZONES,
9460 				    ira->ira_tsl,
9461 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9462 				    NULL);
9463 				if (ire == NULL) {
9464 					ip1dbg(("ip_input_options: SSRR not "
9465 					    "directly reachable: 0x%x\n",
9466 					    ntohl(dst)));
9467 					goto bad_src_route;
9468 				}
9469 				ire_refrele(ire);
9470 			}
9471 			/*
9472 			 * Defer update of the offset and the record route
9473 			 * until the packet is forwarded.
9474 			 */
9475 			break;
9476 		case IPOPT_RR:
9477 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9478 				ip1dbg((
9479 				    "ip_input_options: bad option offset\n"));
9480 				code = (char *)&opt[IPOPT_OLEN] -
9481 				    (char *)ipha;
9482 				goto param_prob;
9483 			}
9484 			break;
9485 		case IPOPT_TS:
9486 			/*
9487 			 * Verify that length >= 5 and that there is either
9488 			 * room for another timestamp or that the overflow
9489 			 * counter is not maxed out.
9490 			 */
9491 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9492 			if (optlen < IPOPT_MINLEN_IT) {
9493 				goto param_prob;
9494 			}
9495 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9496 				ip1dbg((
9497 				    "ip_input_options: bad option offset\n"));
9498 				code = (char *)&opt[IPOPT_OFFSET] -
9499 				    (char *)ipha;
9500 				goto param_prob;
9501 			}
9502 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9503 			case IPOPT_TS_TSONLY:
9504 				off = IPOPT_TS_TIMELEN;
9505 				break;
9506 			case IPOPT_TS_TSANDADDR:
9507 			case IPOPT_TS_PRESPEC:
9508 			case IPOPT_TS_PRESPEC_RFC791:
9509 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9510 				break;
9511 			default:
9512 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9513 				    (char *)ipha;
9514 				goto param_prob;
9515 			}
9516 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9517 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9518 				/*
9519 				 * No room and the overflow counter is 15
9520 				 * already.
9521 				 */
9522 				goto param_prob;
9523 			}
9524 			break;
9525 		}
9526 	}
9527 
9528 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9529 		return (dst);
9530 	}
9531 
9532 	ip1dbg(("ip_input_options: error processing IP options."));
9533 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9534 
9535 param_prob:
9536 	/* make sure we clear any indication of a hardware checksum */
9537 	DB_CKSUMFLAGS(mp) = 0;
9538 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9539 	icmp_param_problem(mp, (uint8_t)code, ira);
9540 	*errorp = -1;
9541 	return (dst);
9542 
9543 bad_src_route:
9544 	/* make sure we clear any indication of a hardware checksum */
9545 	DB_CKSUMFLAGS(mp) = 0;
9546 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9547 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9548 	*errorp = -1;
9549 	return (dst);
9550 }
9551 
9552 /*
9553  * IP & ICMP info in >=14 msg's ...
9554  *  - ip fixed part (mib2_ip_t)
9555  *  - icmp fixed part (mib2_icmp_t)
9556  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9557  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9558  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9559  *  - ipRouteAttributeTable (ip 102)	labeled routes
9560  *  - ip multicast membership (ip_member_t)
9561  *  - ip multicast source filtering (ip_grpsrc_t)
9562  *  - igmp fixed part (struct igmpstat)
9563  *  - multicast routing stats (struct mrtstat)
9564  *  - multicast routing vifs (array of struct vifctl)
9565  *  - multicast routing routes (array of struct mfcctl)
9566  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9567  *					One per ill plus one generic
9568  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9569  *					One per ill plus one generic
9570  *  - ipv6RouteEntry			all IPv6 IREs
9571  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9572  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9573  *  - ipv6AddrEntry			all IPv6 ipifs
9574  *  - ipv6 multicast membership (ipv6_member_t)
9575  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9576  *
9577  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9578  * already filled in by the caller.
9579  * If legacy_req is true then MIB structures needs to be truncated to their
9580  * legacy sizes before being returned.
9581  * Return value of 0 indicates that no messages were sent and caller
9582  * should free mpctl.
9583  */
9584 int
9585 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level, boolean_t legacy_req)
9586 {
9587 	ip_stack_t *ipst;
9588 	sctp_stack_t *sctps;
9589 
9590 	if (q->q_next != NULL) {
9591 		ipst = ILLQ_TO_IPST(q);
9592 	} else {
9593 		ipst = CONNQ_TO_IPST(q);
9594 	}
9595 	ASSERT(ipst != NULL);
9596 	sctps = ipst->ips_netstack->netstack_sctp;
9597 
9598 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9599 		return (0);
9600 	}
9601 
9602 	/*
9603 	 * For the purposes of the (broken) packet shell use
9604 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9605 	 * to make TCP and UDP appear first in the list of mib items.
9606 	 * TBD: We could expand this and use it in netstat so that
9607 	 * the kernel doesn't have to produce large tables (connections,
9608 	 * routes, etc) when netstat only wants the statistics or a particular
9609 	 * table.
9610 	 */
9611 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9612 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9613 			return (1);
9614 		}
9615 	}
9616 
9617 	if (level != MIB2_TCP) {
9618 		if ((mpctl = udp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9619 			return (1);
9620 		}
9621 	}
9622 
9623 	if (level != MIB2_UDP) {
9624 		if ((mpctl = tcp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9625 			return (1);
9626 		}
9627 	}
9628 
9629 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9630 	    ipst, legacy_req)) == NULL) {
9631 		return (1);
9632 	}
9633 
9634 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst,
9635 	    legacy_req)) == NULL) {
9636 		return (1);
9637 	}
9638 
9639 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9640 		return (1);
9641 	}
9642 
9643 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9644 		return (1);
9645 	}
9646 
9647 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9648 		return (1);
9649 	}
9650 
9651 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9652 		return (1);
9653 	}
9654 
9655 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst,
9656 	    legacy_req)) == NULL) {
9657 		return (1);
9658 	}
9659 
9660 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst,
9661 	    legacy_req)) == NULL) {
9662 		return (1);
9663 	}
9664 
9665 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9666 		return (1);
9667 	}
9668 
9669 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9670 		return (1);
9671 	}
9672 
9673 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9674 		return (1);
9675 	}
9676 
9677 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9678 		return (1);
9679 	}
9680 
9681 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9682 		return (1);
9683 	}
9684 
9685 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9686 		return (1);
9687 	}
9688 
9689 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9690 	if (mpctl == NULL)
9691 		return (1);
9692 
9693 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9694 	if (mpctl == NULL)
9695 		return (1);
9696 
9697 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9698 		return (1);
9699 	}
9700 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9701 		return (1);
9702 	}
9703 	freemsg(mpctl);
9704 	return (1);
9705 }
9706 
9707 /* Get global (legacy) IPv4 statistics */
9708 static mblk_t *
9709 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9710     ip_stack_t *ipst, boolean_t legacy_req)
9711 {
9712 	mib2_ip_t		old_ip_mib;
9713 	struct opthdr		*optp;
9714 	mblk_t			*mp2ctl;
9715 	mib2_ipAddrEntry_t	mae;
9716 
9717 	/*
9718 	 * make a copy of the original message
9719 	 */
9720 	mp2ctl = copymsg(mpctl);
9721 
9722 	/* fixed length IP structure... */
9723 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9724 	optp->level = MIB2_IP;
9725 	optp->name = 0;
9726 	SET_MIB(old_ip_mib.ipForwarding,
9727 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9728 	SET_MIB(old_ip_mib.ipDefaultTTL,
9729 	    (uint32_t)ipst->ips_ip_def_ttl);
9730 	SET_MIB(old_ip_mib.ipReasmTimeout,
9731 	    ipst->ips_ip_reassembly_timeout);
9732 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9733 	    (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9734 	    sizeof (mib2_ipAddrEntry_t));
9735 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9736 	    sizeof (mib2_ipRouteEntry_t));
9737 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9738 	    sizeof (mib2_ipNetToMediaEntry_t));
9739 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9740 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9741 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9742 	    sizeof (mib2_ipAttributeEntry_t));
9743 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9744 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9745 
9746 	/*
9747 	 * Grab the statistics from the new IP MIB
9748 	 */
9749 	SET_MIB(old_ip_mib.ipInReceives,
9750 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9751 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9752 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9753 	SET_MIB(old_ip_mib.ipForwDatagrams,
9754 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9755 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9756 	    ipmib->ipIfStatsInUnknownProtos);
9757 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9758 	SET_MIB(old_ip_mib.ipInDelivers,
9759 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9760 	SET_MIB(old_ip_mib.ipOutRequests,
9761 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9762 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9763 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9764 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9765 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9766 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9767 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9768 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9769 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9770 
9771 	/* ipRoutingDiscards is not being used */
9772 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9773 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9774 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9775 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9776 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9777 	    ipmib->ipIfStatsReasmDuplicates);
9778 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9779 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9780 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9781 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9782 	SET_MIB(old_ip_mib.rawipInOverflows,
9783 	    ipmib->rawipIfStatsInOverflows);
9784 
9785 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9786 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9787 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9788 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9789 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9790 	    ipmib->ipIfStatsOutSwitchIPVersion);
9791 
9792 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9793 	    (int)sizeof (old_ip_mib))) {
9794 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9795 		    (uint_t)sizeof (old_ip_mib)));
9796 	}
9797 
9798 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9799 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9800 	    (int)optp->level, (int)optp->name, (int)optp->len));
9801 	qreply(q, mpctl);
9802 	return (mp2ctl);
9803 }
9804 
9805 /* Per interface IPv4 statistics */
9806 static mblk_t *
9807 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9808     boolean_t legacy_req)
9809 {
9810 	struct opthdr		*optp;
9811 	mblk_t			*mp2ctl;
9812 	ill_t			*ill;
9813 	ill_walk_context_t	ctx;
9814 	mblk_t			*mp_tail = NULL;
9815 	mib2_ipIfStatsEntry_t	global_ip_mib;
9816 	mib2_ipAddrEntry_t	mae;
9817 
9818 	/*
9819 	 * Make a copy of the original message
9820 	 */
9821 	mp2ctl = copymsg(mpctl);
9822 
9823 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9824 	optp->level = MIB2_IP;
9825 	optp->name = MIB2_IP_TRAFFIC_STATS;
9826 	/* Include "unknown interface" ip_mib */
9827 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9828 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9829 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9830 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9831 	    (ipst->ips_ip_forwarding ? 1 : 2));
9832 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9833 	    (uint32_t)ipst->ips_ip_def_ttl);
9834 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9835 	    sizeof (mib2_ipIfStatsEntry_t));
9836 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9837 	    sizeof (mib2_ipAddrEntry_t));
9838 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9839 	    sizeof (mib2_ipRouteEntry_t));
9840 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9841 	    sizeof (mib2_ipNetToMediaEntry_t));
9842 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9843 	    sizeof (ip_member_t));
9844 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9845 	    sizeof (ip_grpsrc_t));
9846 
9847 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9848 
9849 	if (legacy_req) {
9850 		SET_MIB(global_ip_mib.ipIfStatsAddrEntrySize,
9851 		    LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t));
9852 	}
9853 
9854 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9855 	    (char *)&global_ip_mib, (int)sizeof (global_ip_mib))) {
9856 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9857 		    "failed to allocate %u bytes\n",
9858 		    (uint_t)sizeof (global_ip_mib)));
9859 	}
9860 
9861 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9862 	ill = ILL_START_WALK_V4(&ctx, ipst);
9863 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9864 		ill->ill_ip_mib->ipIfStatsIfIndex =
9865 		    ill->ill_phyint->phyint_ifindex;
9866 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9867 		    (ipst->ips_ip_forwarding ? 1 : 2));
9868 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9869 		    (uint32_t)ipst->ips_ip_def_ttl);
9870 
9871 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9872 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9873 		    (char *)ill->ill_ip_mib,
9874 		    (int)sizeof (*ill->ill_ip_mib))) {
9875 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9876 			    "failed to allocate %u bytes\n",
9877 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9878 		}
9879 	}
9880 	rw_exit(&ipst->ips_ill_g_lock);
9881 
9882 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9883 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9884 	    "level %d, name %d, len %d\n",
9885 	    (int)optp->level, (int)optp->name, (int)optp->len));
9886 	qreply(q, mpctl);
9887 
9888 	if (mp2ctl == NULL)
9889 		return (NULL);
9890 
9891 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst,
9892 	    legacy_req));
9893 }
9894 
9895 /* Global IPv4 ICMP statistics */
9896 static mblk_t *
9897 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9898 {
9899 	struct opthdr		*optp;
9900 	mblk_t			*mp2ctl;
9901 
9902 	/*
9903 	 * Make a copy of the original message
9904 	 */
9905 	mp2ctl = copymsg(mpctl);
9906 
9907 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9908 	optp->level = MIB2_ICMP;
9909 	optp->name = 0;
9910 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9911 	    (int)sizeof (ipst->ips_icmp_mib))) {
9912 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9913 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
9914 	}
9915 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9916 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9917 	    (int)optp->level, (int)optp->name, (int)optp->len));
9918 	qreply(q, mpctl);
9919 	return (mp2ctl);
9920 }
9921 
9922 /* Global IPv4 IGMP statistics */
9923 static mblk_t *
9924 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9925 {
9926 	struct opthdr		*optp;
9927 	mblk_t			*mp2ctl;
9928 
9929 	/*
9930 	 * make a copy of the original message
9931 	 */
9932 	mp2ctl = copymsg(mpctl);
9933 
9934 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9935 	optp->level = EXPER_IGMP;
9936 	optp->name = 0;
9937 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9938 	    (int)sizeof (ipst->ips_igmpstat))) {
9939 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9940 		    (uint_t)sizeof (ipst->ips_igmpstat)));
9941 	}
9942 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9943 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9944 	    (int)optp->level, (int)optp->name, (int)optp->len));
9945 	qreply(q, mpctl);
9946 	return (mp2ctl);
9947 }
9948 
9949 /* Global IPv4 Multicast Routing statistics */
9950 static mblk_t *
9951 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9952 {
9953 	struct opthdr		*optp;
9954 	mblk_t			*mp2ctl;
9955 
9956 	/*
9957 	 * make a copy of the original message
9958 	 */
9959 	mp2ctl = copymsg(mpctl);
9960 
9961 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9962 	optp->level = EXPER_DVMRP;
9963 	optp->name = 0;
9964 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9965 		ip0dbg(("ip_mroute_stats: failed\n"));
9966 	}
9967 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9968 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9969 	    (int)optp->level, (int)optp->name, (int)optp->len));
9970 	qreply(q, mpctl);
9971 	return (mp2ctl);
9972 }
9973 
9974 /* IPv4 address information */
9975 static mblk_t *
9976 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9977     boolean_t legacy_req)
9978 {
9979 	struct opthdr		*optp;
9980 	mblk_t			*mp2ctl;
9981 	mblk_t			*mp_tail = NULL;
9982 	ill_t			*ill;
9983 	ipif_t			*ipif;
9984 	uint_t			bitval;
9985 	mib2_ipAddrEntry_t	mae;
9986 	size_t			mae_size;
9987 	zoneid_t		zoneid;
9988 	ill_walk_context_t	ctx;
9989 
9990 	/*
9991 	 * make a copy of the original message
9992 	 */
9993 	mp2ctl = copymsg(mpctl);
9994 
9995 	mae_size = (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9996 	    sizeof (mib2_ipAddrEntry_t);
9997 
9998 	/* ipAddrEntryTable */
9999 
10000 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10001 	optp->level = MIB2_IP;
10002 	optp->name = MIB2_IP_ADDR;
10003 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10004 
10005 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10006 	ill = ILL_START_WALK_V4(&ctx, ipst);
10007 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10008 		for (ipif = ill->ill_ipif; ipif != NULL;
10009 		    ipif = ipif->ipif_next) {
10010 			if (ipif->ipif_zoneid != zoneid &&
10011 			    ipif->ipif_zoneid != ALL_ZONES)
10012 				continue;
10013 			/* Sum of count from dead IRE_LO* and our current */
10014 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10015 			if (ipif->ipif_ire_local != NULL) {
10016 				mae.ipAdEntInfo.ae_ibcnt +=
10017 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10018 			}
10019 			mae.ipAdEntInfo.ae_obcnt = 0;
10020 			mae.ipAdEntInfo.ae_focnt = 0;
10021 
10022 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
10023 			    OCTET_LENGTH);
10024 			mae.ipAdEntIfIndex.o_length =
10025 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
10026 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
10027 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
10028 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
10029 			mae.ipAdEntInfo.ae_subnet_len =
10030 			    ip_mask_to_plen(ipif->ipif_net_mask);
10031 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
10032 			for (bitval = 1;
10033 			    bitval &&
10034 			    !(bitval & ipif->ipif_brd_addr);
10035 			    bitval <<= 1)
10036 				noop;
10037 			mae.ipAdEntBcastAddr = bitval;
10038 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
10039 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10040 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
10041 			mae.ipAdEntInfo.ae_broadcast_addr =
10042 			    ipif->ipif_brd_addr;
10043 			mae.ipAdEntInfo.ae_pp_dst_addr =
10044 			    ipif->ipif_pp_dst_addr;
10045 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
10046 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10047 			mae.ipAdEntRetransmitTime =
10048 			    ill->ill_reachable_retrans_time;
10049 
10050 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10051 			    (char *)&mae, (int)mae_size)) {
10052 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
10053 				    "allocate %u bytes\n", (uint_t)mae_size));
10054 			}
10055 		}
10056 	}
10057 	rw_exit(&ipst->ips_ill_g_lock);
10058 
10059 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10060 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
10061 	    (int)optp->level, (int)optp->name, (int)optp->len));
10062 	qreply(q, mpctl);
10063 	return (mp2ctl);
10064 }
10065 
10066 /* IPv6 address information */
10067 static mblk_t *
10068 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10069     boolean_t legacy_req)
10070 {
10071 	struct opthdr		*optp;
10072 	mblk_t			*mp2ctl;
10073 	mblk_t			*mp_tail = NULL;
10074 	ill_t			*ill;
10075 	ipif_t			*ipif;
10076 	mib2_ipv6AddrEntry_t	mae6;
10077 	size_t			mae6_size;
10078 	zoneid_t		zoneid;
10079 	ill_walk_context_t	ctx;
10080 
10081 	/*
10082 	 * make a copy of the original message
10083 	 */
10084 	mp2ctl = copymsg(mpctl);
10085 
10086 	mae6_size = (legacy_req) ?
10087 	    LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t) :
10088 	    sizeof (mib2_ipv6AddrEntry_t);
10089 
10090 	/* ipv6AddrEntryTable */
10091 
10092 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10093 	optp->level = MIB2_IP6;
10094 	optp->name = MIB2_IP6_ADDR;
10095 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10096 
10097 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10098 	ill = ILL_START_WALK_V6(&ctx, ipst);
10099 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10100 		for (ipif = ill->ill_ipif; ipif != NULL;
10101 		    ipif = ipif->ipif_next) {
10102 			if (ipif->ipif_zoneid != zoneid &&
10103 			    ipif->ipif_zoneid != ALL_ZONES)
10104 				continue;
10105 			/* Sum of count from dead IRE_LO* and our current */
10106 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10107 			if (ipif->ipif_ire_local != NULL) {
10108 				mae6.ipv6AddrInfo.ae_ibcnt +=
10109 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10110 			}
10111 			mae6.ipv6AddrInfo.ae_obcnt = 0;
10112 			mae6.ipv6AddrInfo.ae_focnt = 0;
10113 
10114 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10115 			    OCTET_LENGTH);
10116 			mae6.ipv6AddrIfIndex.o_length =
10117 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10118 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10119 			mae6.ipv6AddrPfxLength =
10120 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10121 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10122 			mae6.ipv6AddrInfo.ae_subnet_len =
10123 			    mae6.ipv6AddrPfxLength;
10124 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10125 
10126 			/* Type: stateless(1), stateful(2), unknown(3) */
10127 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10128 				mae6.ipv6AddrType = 1;
10129 			else
10130 				mae6.ipv6AddrType = 2;
10131 			/* Anycast: true(1), false(2) */
10132 			if (ipif->ipif_flags & IPIF_ANYCAST)
10133 				mae6.ipv6AddrAnycastFlag = 1;
10134 			else
10135 				mae6.ipv6AddrAnycastFlag = 2;
10136 
10137 			/*
10138 			 * Address status: preferred(1), deprecated(2),
10139 			 * invalid(3), inaccessible(4), unknown(5)
10140 			 */
10141 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10142 				mae6.ipv6AddrStatus = 3;
10143 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10144 				mae6.ipv6AddrStatus = 2;
10145 			else
10146 				mae6.ipv6AddrStatus = 1;
10147 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10148 			mae6.ipv6AddrInfo.ae_metric  =
10149 			    ipif->ipif_ill->ill_metric;
10150 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10151 			    ipif->ipif_v6pp_dst_addr;
10152 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10153 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10154 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10155 			mae6.ipv6AddrIdentifier = ill->ill_token;
10156 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10157 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10158 			mae6.ipv6AddrRetransmitTime =
10159 			    ill->ill_reachable_retrans_time;
10160 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10161 			    (char *)&mae6, (int)mae6_size)) {
10162 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10163 				    "allocate %u bytes\n",
10164 				    (uint_t)mae6_size));
10165 			}
10166 		}
10167 	}
10168 	rw_exit(&ipst->ips_ill_g_lock);
10169 
10170 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10171 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10172 	    (int)optp->level, (int)optp->name, (int)optp->len));
10173 	qreply(q, mpctl);
10174 	return (mp2ctl);
10175 }
10176 
10177 /* IPv4 multicast group membership. */
10178 static mblk_t *
10179 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10180 {
10181 	struct opthdr		*optp;
10182 	mblk_t			*mp2ctl;
10183 	ill_t			*ill;
10184 	ipif_t			*ipif;
10185 	ilm_t			*ilm;
10186 	ip_member_t		ipm;
10187 	mblk_t			*mp_tail = NULL;
10188 	ill_walk_context_t	ctx;
10189 	zoneid_t		zoneid;
10190 
10191 	/*
10192 	 * make a copy of the original message
10193 	 */
10194 	mp2ctl = copymsg(mpctl);
10195 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10196 
10197 	/* ipGroupMember table */
10198 	optp = (struct opthdr *)&mpctl->b_rptr[
10199 	    sizeof (struct T_optmgmt_ack)];
10200 	optp->level = MIB2_IP;
10201 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10202 
10203 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10204 	ill = ILL_START_WALK_V4(&ctx, ipst);
10205 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10206 		/* Make sure the ill isn't going away. */
10207 		if (!ill_check_and_refhold(ill))
10208 			continue;
10209 		rw_exit(&ipst->ips_ill_g_lock);
10210 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10211 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10212 			if (ilm->ilm_zoneid != zoneid &&
10213 			    ilm->ilm_zoneid != ALL_ZONES)
10214 				continue;
10215 
10216 			/* Is there an ipif for ilm_ifaddr? */
10217 			for (ipif = ill->ill_ipif; ipif != NULL;
10218 			    ipif = ipif->ipif_next) {
10219 				if (!IPIF_IS_CONDEMNED(ipif) &&
10220 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10221 				    ilm->ilm_ifaddr != INADDR_ANY)
10222 					break;
10223 			}
10224 			if (ipif != NULL) {
10225 				ipif_get_name(ipif,
10226 				    ipm.ipGroupMemberIfIndex.o_bytes,
10227 				    OCTET_LENGTH);
10228 			} else {
10229 				ill_get_name(ill,
10230 				    ipm.ipGroupMemberIfIndex.o_bytes,
10231 				    OCTET_LENGTH);
10232 			}
10233 			ipm.ipGroupMemberIfIndex.o_length =
10234 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10235 
10236 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10237 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10238 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10239 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10240 			    (char *)&ipm, (int)sizeof (ipm))) {
10241 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10242 				    "failed to allocate %u bytes\n",
10243 				    (uint_t)sizeof (ipm)));
10244 			}
10245 		}
10246 		rw_exit(&ill->ill_mcast_lock);
10247 		ill_refrele(ill);
10248 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10249 	}
10250 	rw_exit(&ipst->ips_ill_g_lock);
10251 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10252 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10253 	    (int)optp->level, (int)optp->name, (int)optp->len));
10254 	qreply(q, mpctl);
10255 	return (mp2ctl);
10256 }
10257 
10258 /* IPv6 multicast group membership. */
10259 static mblk_t *
10260 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10261 {
10262 	struct opthdr		*optp;
10263 	mblk_t			*mp2ctl;
10264 	ill_t			*ill;
10265 	ilm_t			*ilm;
10266 	ipv6_member_t		ipm6;
10267 	mblk_t			*mp_tail = NULL;
10268 	ill_walk_context_t	ctx;
10269 	zoneid_t		zoneid;
10270 
10271 	/*
10272 	 * make a copy of the original message
10273 	 */
10274 	mp2ctl = copymsg(mpctl);
10275 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10276 
10277 	/* ip6GroupMember table */
10278 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10279 	optp->level = MIB2_IP6;
10280 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10281 
10282 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10283 	ill = ILL_START_WALK_V6(&ctx, ipst);
10284 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10285 		/* Make sure the ill isn't going away. */
10286 		if (!ill_check_and_refhold(ill))
10287 			continue;
10288 		rw_exit(&ipst->ips_ill_g_lock);
10289 		/*
10290 		 * Normally we don't have any members on under IPMP interfaces.
10291 		 * We report them as a debugging aid.
10292 		 */
10293 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10294 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10295 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10296 			if (ilm->ilm_zoneid != zoneid &&
10297 			    ilm->ilm_zoneid != ALL_ZONES)
10298 				continue;	/* not this zone */
10299 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10300 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10301 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10302 			if (!snmp_append_data2(mpctl->b_cont,
10303 			    &mp_tail,
10304 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10305 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10306 				    "failed to allocate %u bytes\n",
10307 				    (uint_t)sizeof (ipm6)));
10308 			}
10309 		}
10310 		rw_exit(&ill->ill_mcast_lock);
10311 		ill_refrele(ill);
10312 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10313 	}
10314 	rw_exit(&ipst->ips_ill_g_lock);
10315 
10316 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10317 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10318 	    (int)optp->level, (int)optp->name, (int)optp->len));
10319 	qreply(q, mpctl);
10320 	return (mp2ctl);
10321 }
10322 
10323 /* IP multicast filtered sources */
10324 static mblk_t *
10325 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10326 {
10327 	struct opthdr		*optp;
10328 	mblk_t			*mp2ctl;
10329 	ill_t			*ill;
10330 	ipif_t			*ipif;
10331 	ilm_t			*ilm;
10332 	ip_grpsrc_t		ips;
10333 	mblk_t			*mp_tail = NULL;
10334 	ill_walk_context_t	ctx;
10335 	zoneid_t		zoneid;
10336 	int			i;
10337 	slist_t			*sl;
10338 
10339 	/*
10340 	 * make a copy of the original message
10341 	 */
10342 	mp2ctl = copymsg(mpctl);
10343 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10344 
10345 	/* ipGroupSource table */
10346 	optp = (struct opthdr *)&mpctl->b_rptr[
10347 	    sizeof (struct T_optmgmt_ack)];
10348 	optp->level = MIB2_IP;
10349 	optp->name = EXPER_IP_GROUP_SOURCES;
10350 
10351 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10352 	ill = ILL_START_WALK_V4(&ctx, ipst);
10353 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10354 		/* Make sure the ill isn't going away. */
10355 		if (!ill_check_and_refhold(ill))
10356 			continue;
10357 		rw_exit(&ipst->ips_ill_g_lock);
10358 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10359 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10360 			sl = ilm->ilm_filter;
10361 			if (ilm->ilm_zoneid != zoneid &&
10362 			    ilm->ilm_zoneid != ALL_ZONES)
10363 				continue;
10364 			if (SLIST_IS_EMPTY(sl))
10365 				continue;
10366 
10367 			/* Is there an ipif for ilm_ifaddr? */
10368 			for (ipif = ill->ill_ipif; ipif != NULL;
10369 			    ipif = ipif->ipif_next) {
10370 				if (!IPIF_IS_CONDEMNED(ipif) &&
10371 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10372 				    ilm->ilm_ifaddr != INADDR_ANY)
10373 					break;
10374 			}
10375 			if (ipif != NULL) {
10376 				ipif_get_name(ipif,
10377 				    ips.ipGroupSourceIfIndex.o_bytes,
10378 				    OCTET_LENGTH);
10379 			} else {
10380 				ill_get_name(ill,
10381 				    ips.ipGroupSourceIfIndex.o_bytes,
10382 				    OCTET_LENGTH);
10383 			}
10384 			ips.ipGroupSourceIfIndex.o_length =
10385 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10386 
10387 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10388 			for (i = 0; i < sl->sl_numsrc; i++) {
10389 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10390 					continue;
10391 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10392 				    ips.ipGroupSourceAddress);
10393 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10394 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10395 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10396 					    " failed to allocate %u bytes\n",
10397 					    (uint_t)sizeof (ips)));
10398 				}
10399 			}
10400 		}
10401 		rw_exit(&ill->ill_mcast_lock);
10402 		ill_refrele(ill);
10403 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10404 	}
10405 	rw_exit(&ipst->ips_ill_g_lock);
10406 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10407 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10408 	    (int)optp->level, (int)optp->name, (int)optp->len));
10409 	qreply(q, mpctl);
10410 	return (mp2ctl);
10411 }
10412 
10413 /* IPv6 multicast filtered sources. */
10414 static mblk_t *
10415 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10416 {
10417 	struct opthdr		*optp;
10418 	mblk_t			*mp2ctl;
10419 	ill_t			*ill;
10420 	ilm_t			*ilm;
10421 	ipv6_grpsrc_t		ips6;
10422 	mblk_t			*mp_tail = NULL;
10423 	ill_walk_context_t	ctx;
10424 	zoneid_t		zoneid;
10425 	int			i;
10426 	slist_t			*sl;
10427 
10428 	/*
10429 	 * make a copy of the original message
10430 	 */
10431 	mp2ctl = copymsg(mpctl);
10432 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10433 
10434 	/* ip6GroupMember table */
10435 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10436 	optp->level = MIB2_IP6;
10437 	optp->name = EXPER_IP6_GROUP_SOURCES;
10438 
10439 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10440 	ill = ILL_START_WALK_V6(&ctx, ipst);
10441 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10442 		/* Make sure the ill isn't going away. */
10443 		if (!ill_check_and_refhold(ill))
10444 			continue;
10445 		rw_exit(&ipst->ips_ill_g_lock);
10446 		/*
10447 		 * Normally we don't have any members on under IPMP interfaces.
10448 		 * We report them as a debugging aid.
10449 		 */
10450 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10451 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10452 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10453 			sl = ilm->ilm_filter;
10454 			if (ilm->ilm_zoneid != zoneid &&
10455 			    ilm->ilm_zoneid != ALL_ZONES)
10456 				continue;
10457 			if (SLIST_IS_EMPTY(sl))
10458 				continue;
10459 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10460 			for (i = 0; i < sl->sl_numsrc; i++) {
10461 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10462 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10463 				    (char *)&ips6, (int)sizeof (ips6))) {
10464 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10465 					    "group_src: failed to allocate "
10466 					    "%u bytes\n",
10467 					    (uint_t)sizeof (ips6)));
10468 				}
10469 			}
10470 		}
10471 		rw_exit(&ill->ill_mcast_lock);
10472 		ill_refrele(ill);
10473 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10474 	}
10475 	rw_exit(&ipst->ips_ill_g_lock);
10476 
10477 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10478 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10479 	    (int)optp->level, (int)optp->name, (int)optp->len));
10480 	qreply(q, mpctl);
10481 	return (mp2ctl);
10482 }
10483 
10484 /* Multicast routing virtual interface table. */
10485 static mblk_t *
10486 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10487 {
10488 	struct opthdr		*optp;
10489 	mblk_t			*mp2ctl;
10490 
10491 	/*
10492 	 * make a copy of the original message
10493 	 */
10494 	mp2ctl = copymsg(mpctl);
10495 
10496 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10497 	optp->level = EXPER_DVMRP;
10498 	optp->name = EXPER_DVMRP_VIF;
10499 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10500 		ip0dbg(("ip_mroute_vif: failed\n"));
10501 	}
10502 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10503 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10504 	    (int)optp->level, (int)optp->name, (int)optp->len));
10505 	qreply(q, mpctl);
10506 	return (mp2ctl);
10507 }
10508 
10509 /* Multicast routing table. */
10510 static mblk_t *
10511 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10512 {
10513 	struct opthdr		*optp;
10514 	mblk_t			*mp2ctl;
10515 
10516 	/*
10517 	 * make a copy of the original message
10518 	 */
10519 	mp2ctl = copymsg(mpctl);
10520 
10521 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10522 	optp->level = EXPER_DVMRP;
10523 	optp->name = EXPER_DVMRP_MRT;
10524 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10525 		ip0dbg(("ip_mroute_mrt: failed\n"));
10526 	}
10527 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10528 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10529 	    (int)optp->level, (int)optp->name, (int)optp->len));
10530 	qreply(q, mpctl);
10531 	return (mp2ctl);
10532 }
10533 
10534 /*
10535  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10536  * in one IRE walk.
10537  */
10538 static mblk_t *
10539 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10540     ip_stack_t *ipst)
10541 {
10542 	struct opthdr	*optp;
10543 	mblk_t		*mp2ctl;	/* Returned */
10544 	mblk_t		*mp3ctl;	/* nettomedia */
10545 	mblk_t		*mp4ctl;	/* routeattrs */
10546 	iproutedata_t	ird;
10547 	zoneid_t	zoneid;
10548 
10549 	/*
10550 	 * make copies of the original message
10551 	 *	- mp2ctl is returned unchanged to the caller for his use
10552 	 *	- mpctl is sent upstream as ipRouteEntryTable
10553 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10554 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10555 	 */
10556 	mp2ctl = copymsg(mpctl);
10557 	mp3ctl = copymsg(mpctl);
10558 	mp4ctl = copymsg(mpctl);
10559 	if (mp3ctl == NULL || mp4ctl == NULL) {
10560 		freemsg(mp4ctl);
10561 		freemsg(mp3ctl);
10562 		freemsg(mp2ctl);
10563 		freemsg(mpctl);
10564 		return (NULL);
10565 	}
10566 
10567 	bzero(&ird, sizeof (ird));
10568 
10569 	ird.ird_route.lp_head = mpctl->b_cont;
10570 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10571 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10572 	/*
10573 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10574 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10575 	 * intended a temporary solution until a proper MIB API is provided
10576 	 * that provides complete filtering/caller-opt-in.
10577 	 */
10578 	if (level == EXPER_IP_AND_ALL_IRES)
10579 		ird.ird_flags |= IRD_REPORT_ALL;
10580 
10581 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10582 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10583 
10584 	/* ipRouteEntryTable in mpctl */
10585 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10586 	optp->level = MIB2_IP;
10587 	optp->name = MIB2_IP_ROUTE;
10588 	optp->len = msgdsize(ird.ird_route.lp_head);
10589 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10590 	    (int)optp->level, (int)optp->name, (int)optp->len));
10591 	qreply(q, mpctl);
10592 
10593 	/* ipNetToMediaEntryTable in mp3ctl */
10594 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10595 
10596 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10597 	optp->level = MIB2_IP;
10598 	optp->name = MIB2_IP_MEDIA;
10599 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10600 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10601 	    (int)optp->level, (int)optp->name, (int)optp->len));
10602 	qreply(q, mp3ctl);
10603 
10604 	/* ipRouteAttributeTable in mp4ctl */
10605 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10606 	optp->level = MIB2_IP;
10607 	optp->name = EXPER_IP_RTATTR;
10608 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10609 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10610 	    (int)optp->level, (int)optp->name, (int)optp->len));
10611 	if (optp->len == 0)
10612 		freemsg(mp4ctl);
10613 	else
10614 		qreply(q, mp4ctl);
10615 
10616 	return (mp2ctl);
10617 }
10618 
10619 /*
10620  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10621  * ipv6NetToMediaEntryTable in an NDP walk.
10622  */
10623 static mblk_t *
10624 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10625     ip_stack_t *ipst)
10626 {
10627 	struct opthdr	*optp;
10628 	mblk_t		*mp2ctl;	/* Returned */
10629 	mblk_t		*mp3ctl;	/* nettomedia */
10630 	mblk_t		*mp4ctl;	/* routeattrs */
10631 	iproutedata_t	ird;
10632 	zoneid_t	zoneid;
10633 
10634 	/*
10635 	 * make copies of the original message
10636 	 *	- mp2ctl is returned unchanged to the caller for his use
10637 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10638 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10639 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10640 	 */
10641 	mp2ctl = copymsg(mpctl);
10642 	mp3ctl = copymsg(mpctl);
10643 	mp4ctl = copymsg(mpctl);
10644 	if (mp3ctl == NULL || mp4ctl == NULL) {
10645 		freemsg(mp4ctl);
10646 		freemsg(mp3ctl);
10647 		freemsg(mp2ctl);
10648 		freemsg(mpctl);
10649 		return (NULL);
10650 	}
10651 
10652 	bzero(&ird, sizeof (ird));
10653 
10654 	ird.ird_route.lp_head = mpctl->b_cont;
10655 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10656 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10657 	/*
10658 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10659 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10660 	 * intended a temporary solution until a proper MIB API is provided
10661 	 * that provides complete filtering/caller-opt-in.
10662 	 */
10663 	if (level == EXPER_IP_AND_ALL_IRES)
10664 		ird.ird_flags |= IRD_REPORT_ALL;
10665 
10666 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10667 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10668 
10669 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10670 	optp->level = MIB2_IP6;
10671 	optp->name = MIB2_IP6_ROUTE;
10672 	optp->len = msgdsize(ird.ird_route.lp_head);
10673 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10674 	    (int)optp->level, (int)optp->name, (int)optp->len));
10675 	qreply(q, mpctl);
10676 
10677 	/* ipv6NetToMediaEntryTable in mp3ctl */
10678 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10679 
10680 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10681 	optp->level = MIB2_IP6;
10682 	optp->name = MIB2_IP6_MEDIA;
10683 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10684 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10685 	    (int)optp->level, (int)optp->name, (int)optp->len));
10686 	qreply(q, mp3ctl);
10687 
10688 	/* ipv6RouteAttributeTable in mp4ctl */
10689 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10690 	optp->level = MIB2_IP6;
10691 	optp->name = EXPER_IP_RTATTR;
10692 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10693 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10694 	    (int)optp->level, (int)optp->name, (int)optp->len));
10695 	if (optp->len == 0)
10696 		freemsg(mp4ctl);
10697 	else
10698 		qreply(q, mp4ctl);
10699 
10700 	return (mp2ctl);
10701 }
10702 
10703 /*
10704  * IPv6 mib: One per ill
10705  */
10706 static mblk_t *
10707 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10708     boolean_t legacy_req)
10709 {
10710 	struct opthdr		*optp;
10711 	mblk_t			*mp2ctl;
10712 	ill_t			*ill;
10713 	ill_walk_context_t	ctx;
10714 	mblk_t			*mp_tail = NULL;
10715 	mib2_ipv6AddrEntry_t	mae6;
10716 	mib2_ipIfStatsEntry_t	*ise;
10717 	size_t			ise_size, iae_size;
10718 
10719 	/*
10720 	 * Make a copy of the original message
10721 	 */
10722 	mp2ctl = copymsg(mpctl);
10723 
10724 	/* fixed length IPv6 structure ... */
10725 
10726 	if (legacy_req) {
10727 		ise_size = LEGACY_MIB_SIZE(&ipst->ips_ip6_mib,
10728 		    mib2_ipIfStatsEntry_t);
10729 		iae_size = LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t);
10730 	} else {
10731 		ise_size = sizeof (mib2_ipIfStatsEntry_t);
10732 		iae_size = sizeof (mib2_ipv6AddrEntry_t);
10733 	}
10734 
10735 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10736 	optp->level = MIB2_IP6;
10737 	optp->name = 0;
10738 	/* Include "unknown interface" ip6_mib */
10739 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10740 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10741 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10742 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10743 	    ipst->ips_ipv6_forwarding ? 1 : 2);
10744 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10745 	    ipst->ips_ipv6_def_hops);
10746 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10747 	    sizeof (mib2_ipIfStatsEntry_t));
10748 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10749 	    sizeof (mib2_ipv6AddrEntry_t));
10750 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10751 	    sizeof (mib2_ipv6RouteEntry_t));
10752 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10753 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10754 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10755 	    sizeof (ipv6_member_t));
10756 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10757 	    sizeof (ipv6_grpsrc_t));
10758 
10759 	/*
10760 	 * Synchronize 64- and 32-bit counters
10761 	 */
10762 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10763 	    ipIfStatsHCInReceives);
10764 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10765 	    ipIfStatsHCInDelivers);
10766 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10767 	    ipIfStatsHCOutRequests);
10768 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10769 	    ipIfStatsHCOutForwDatagrams);
10770 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10771 	    ipIfStatsHCOutMcastPkts);
10772 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10773 	    ipIfStatsHCInMcastPkts);
10774 
10775 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10776 	    (char *)&ipst->ips_ip6_mib, (int)ise_size)) {
10777 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10778 		    (uint_t)ise_size));
10779 	} else if (legacy_req) {
10780 		/* Adjust the EntrySize fields for legacy requests. */
10781 		ise =
10782 		    (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr - (int)ise_size);
10783 		SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10784 		SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10785 	}
10786 
10787 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10788 	ill = ILL_START_WALK_V6(&ctx, ipst);
10789 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10790 		ill->ill_ip_mib->ipIfStatsIfIndex =
10791 		    ill->ill_phyint->phyint_ifindex;
10792 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10793 		    ipst->ips_ipv6_forwarding ? 1 : 2);
10794 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10795 		    ill->ill_max_hops);
10796 
10797 		/*
10798 		 * Synchronize 64- and 32-bit counters
10799 		 */
10800 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10801 		    ipIfStatsHCInReceives);
10802 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10803 		    ipIfStatsHCInDelivers);
10804 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10805 		    ipIfStatsHCOutRequests);
10806 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10807 		    ipIfStatsHCOutForwDatagrams);
10808 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10809 		    ipIfStatsHCOutMcastPkts);
10810 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10811 		    ipIfStatsHCInMcastPkts);
10812 
10813 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10814 		    (char *)ill->ill_ip_mib, (int)ise_size)) {
10815 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10816 			"%u bytes\n", (uint_t)ise_size));
10817 		} else if (legacy_req) {
10818 			/* Adjust the EntrySize fields for legacy requests. */
10819 			ise = (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr -
10820 			    (int)ise_size);
10821 			SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10822 			SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10823 		}
10824 	}
10825 	rw_exit(&ipst->ips_ill_g_lock);
10826 
10827 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10828 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10829 	    (int)optp->level, (int)optp->name, (int)optp->len));
10830 	qreply(q, mpctl);
10831 	return (mp2ctl);
10832 }
10833 
10834 /*
10835  * ICMPv6 mib: One per ill
10836  */
10837 static mblk_t *
10838 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10839 {
10840 	struct opthdr		*optp;
10841 	mblk_t			*mp2ctl;
10842 	ill_t			*ill;
10843 	ill_walk_context_t	ctx;
10844 	mblk_t			*mp_tail = NULL;
10845 	/*
10846 	 * Make a copy of the original message
10847 	 */
10848 	mp2ctl = copymsg(mpctl);
10849 
10850 	/* fixed length ICMPv6 structure ... */
10851 
10852 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10853 	optp->level = MIB2_ICMP6;
10854 	optp->name = 0;
10855 	/* Include "unknown interface" icmp6_mib */
10856 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10857 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10858 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10859 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10860 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10861 	    (char *)&ipst->ips_icmp6_mib,
10862 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10863 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10864 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10865 	}
10866 
10867 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10868 	ill = ILL_START_WALK_V6(&ctx, ipst);
10869 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10870 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10871 		    ill->ill_phyint->phyint_ifindex;
10872 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10873 		    (char *)ill->ill_icmp6_mib,
10874 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10875 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10876 			    "%u bytes\n",
10877 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10878 		}
10879 	}
10880 	rw_exit(&ipst->ips_ill_g_lock);
10881 
10882 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10883 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10884 	    (int)optp->level, (int)optp->name, (int)optp->len));
10885 	qreply(q, mpctl);
10886 	return (mp2ctl);
10887 }
10888 
10889 /*
10890  * ire_walk routine to create both ipRouteEntryTable and
10891  * ipRouteAttributeTable in one IRE walk
10892  */
10893 static void
10894 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10895 {
10896 	ill_t				*ill;
10897 	mib2_ipRouteEntry_t		*re;
10898 	mib2_ipAttributeEntry_t		iaes;
10899 	tsol_ire_gw_secattr_t		*attrp;
10900 	tsol_gc_t			*gc = NULL;
10901 	tsol_gcgrp_t			*gcgrp = NULL;
10902 	ip_stack_t			*ipst = ire->ire_ipst;
10903 
10904 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10905 
10906 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10907 		if (ire->ire_testhidden)
10908 			return;
10909 		if (ire->ire_type & IRE_IF_CLONE)
10910 			return;
10911 	}
10912 
10913 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10914 		return;
10915 
10916 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10917 		mutex_enter(&attrp->igsa_lock);
10918 		if ((gc = attrp->igsa_gc) != NULL) {
10919 			gcgrp = gc->gc_grp;
10920 			ASSERT(gcgrp != NULL);
10921 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10922 		}
10923 		mutex_exit(&attrp->igsa_lock);
10924 	}
10925 	/*
10926 	 * Return all IRE types for route table... let caller pick and choose
10927 	 */
10928 	re->ipRouteDest = ire->ire_addr;
10929 	ill = ire->ire_ill;
10930 	re->ipRouteIfIndex.o_length = 0;
10931 	if (ill != NULL) {
10932 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10933 		re->ipRouteIfIndex.o_length =
10934 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
10935 	}
10936 	re->ipRouteMetric1 = -1;
10937 	re->ipRouteMetric2 = -1;
10938 	re->ipRouteMetric3 = -1;
10939 	re->ipRouteMetric4 = -1;
10940 
10941 	re->ipRouteNextHop = ire->ire_gateway_addr;
10942 	/* indirect(4), direct(3), or invalid(2) */
10943 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10944 		re->ipRouteType = 2;
10945 	else if (ire->ire_type & IRE_ONLINK)
10946 		re->ipRouteType = 3;
10947 	else
10948 		re->ipRouteType = 4;
10949 
10950 	re->ipRouteProto = -1;
10951 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10952 	re->ipRouteMask = ire->ire_mask;
10953 	re->ipRouteMetric5 = -1;
10954 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10955 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10956 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10957 
10958 	re->ipRouteInfo.re_frag_flag	= 0;
10959 	re->ipRouteInfo.re_rtt		= 0;
10960 	re->ipRouteInfo.re_src_addr	= 0;
10961 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
10962 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10963 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10964 	re->ipRouteInfo.re_flags	= ire->ire_flags;
10965 
10966 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10967 	if (ire->ire_type & IRE_INTERFACE) {
10968 		ire_t *child;
10969 
10970 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10971 		child = ire->ire_dep_children;
10972 		while (child != NULL) {
10973 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10974 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10975 			child = child->ire_dep_sib_next;
10976 		}
10977 		rw_exit(&ipst->ips_ire_dep_lock);
10978 	}
10979 
10980 	if (ire->ire_flags & RTF_DYNAMIC) {
10981 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
10982 	} else {
10983 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
10984 	}
10985 
10986 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
10987 	    (char *)re, (int)sizeof (*re))) {
10988 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
10989 		    (uint_t)sizeof (*re)));
10990 	}
10991 
10992 	if (gc != NULL) {
10993 		iaes.iae_routeidx = ird->ird_idx;
10994 		iaes.iae_doi = gc->gc_db->gcdb_doi;
10995 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
10996 
10997 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
10998 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
10999 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
11000 			    "bytes\n", (uint_t)sizeof (iaes)));
11001 		}
11002 	}
11003 
11004 	/* bump route index for next pass */
11005 	ird->ird_idx++;
11006 
11007 	kmem_free(re, sizeof (*re));
11008 	if (gcgrp != NULL)
11009 		rw_exit(&gcgrp->gcgrp_rwlock);
11010 }
11011 
11012 /*
11013  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
11014  */
11015 static void
11016 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
11017 {
11018 	ill_t				*ill;
11019 	mib2_ipv6RouteEntry_t		*re;
11020 	mib2_ipAttributeEntry_t		iaes;
11021 	tsol_ire_gw_secattr_t		*attrp;
11022 	tsol_gc_t			*gc = NULL;
11023 	tsol_gcgrp_t			*gcgrp = NULL;
11024 	ip_stack_t			*ipst = ire->ire_ipst;
11025 
11026 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
11027 
11028 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11029 		if (ire->ire_testhidden)
11030 			return;
11031 		if (ire->ire_type & IRE_IF_CLONE)
11032 			return;
11033 	}
11034 
11035 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11036 		return;
11037 
11038 	if ((attrp = ire->ire_gw_secattr) != NULL) {
11039 		mutex_enter(&attrp->igsa_lock);
11040 		if ((gc = attrp->igsa_gc) != NULL) {
11041 			gcgrp = gc->gc_grp;
11042 			ASSERT(gcgrp != NULL);
11043 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11044 		}
11045 		mutex_exit(&attrp->igsa_lock);
11046 	}
11047 	/*
11048 	 * Return all IRE types for route table... let caller pick and choose
11049 	 */
11050 	re->ipv6RouteDest = ire->ire_addr_v6;
11051 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
11052 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
11053 	re->ipv6RouteIfIndex.o_length = 0;
11054 	ill = ire->ire_ill;
11055 	if (ill != NULL) {
11056 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
11057 		re->ipv6RouteIfIndex.o_length =
11058 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
11059 	}
11060 
11061 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
11062 
11063 	mutex_enter(&ire->ire_lock);
11064 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
11065 	mutex_exit(&ire->ire_lock);
11066 
11067 	/* remote(4), local(3), or discard(2) */
11068 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11069 		re->ipv6RouteType = 2;
11070 	else if (ire->ire_type & IRE_ONLINK)
11071 		re->ipv6RouteType = 3;
11072 	else
11073 		re->ipv6RouteType = 4;
11074 
11075 	re->ipv6RouteProtocol	= -1;
11076 	re->ipv6RoutePolicy	= 0;
11077 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
11078 	re->ipv6RouteNextHopRDI	= 0;
11079 	re->ipv6RouteWeight	= 0;
11080 	re->ipv6RouteMetric	= 0;
11081 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11082 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11083 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11084 
11085 	re->ipv6RouteInfo.re_frag_flag	= 0;
11086 	re->ipv6RouteInfo.re_rtt	= 0;
11087 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
11088 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11089 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11090 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
11091 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
11092 
11093 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11094 	if (ire->ire_type & IRE_INTERFACE) {
11095 		ire_t *child;
11096 
11097 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11098 		child = ire->ire_dep_children;
11099 		while (child != NULL) {
11100 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11101 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11102 			child = child->ire_dep_sib_next;
11103 		}
11104 		rw_exit(&ipst->ips_ire_dep_lock);
11105 	}
11106 	if (ire->ire_flags & RTF_DYNAMIC) {
11107 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11108 	} else {
11109 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
11110 	}
11111 
11112 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11113 	    (char *)re, (int)sizeof (*re))) {
11114 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11115 		    (uint_t)sizeof (*re)));
11116 	}
11117 
11118 	if (gc != NULL) {
11119 		iaes.iae_routeidx = ird->ird_idx;
11120 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11121 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11122 
11123 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11124 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11125 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11126 			    "bytes\n", (uint_t)sizeof (iaes)));
11127 		}
11128 	}
11129 
11130 	/* bump route index for next pass */
11131 	ird->ird_idx++;
11132 
11133 	kmem_free(re, sizeof (*re));
11134 	if (gcgrp != NULL)
11135 		rw_exit(&gcgrp->gcgrp_rwlock);
11136 }
11137 
11138 /*
11139  * ncec_walk routine to create ipv6NetToMediaEntryTable
11140  */
11141 static int
11142 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11143 {
11144 	ill_t				*ill;
11145 	mib2_ipv6NetToMediaEntry_t	ntme;
11146 
11147 	ill = ncec->ncec_ill;
11148 	/* skip arpce entries, and loopback ncec entries */
11149 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11150 		return (0);
11151 	/*
11152 	 * Neighbor cache entry attached to IRE with on-link
11153 	 * destination.
11154 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11155 	 */
11156 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11157 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11158 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11159 	if (ncec->ncec_lladdr != NULL) {
11160 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11161 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11162 	}
11163 	/*
11164 	 * Note: Returns ND_* states. Should be:
11165 	 * reachable(1), stale(2), delay(3), probe(4),
11166 	 * invalid(5), unknown(6)
11167 	 */
11168 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11169 	ntme.ipv6NetToMediaLastUpdated = 0;
11170 
11171 	/* other(1), dynamic(2), static(3), local(4) */
11172 	if (NCE_MYADDR(ncec)) {
11173 		ntme.ipv6NetToMediaType = 4;
11174 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11175 		ntme.ipv6NetToMediaType = 1; /* proxy */
11176 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11177 		ntme.ipv6NetToMediaType = 3;
11178 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11179 		ntme.ipv6NetToMediaType = 1;
11180 	} else {
11181 		ntme.ipv6NetToMediaType = 2;
11182 	}
11183 
11184 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11185 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11186 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11187 		    (uint_t)sizeof (ntme)));
11188 	}
11189 	return (0);
11190 }
11191 
11192 int
11193 nce2ace(ncec_t *ncec)
11194 {
11195 	int flags = 0;
11196 
11197 	if (NCE_ISREACHABLE(ncec))
11198 		flags |= ACE_F_RESOLVED;
11199 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11200 		flags |= ACE_F_AUTHORITY;
11201 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11202 		flags |= ACE_F_PUBLISH;
11203 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11204 		flags |= ACE_F_PERMANENT;
11205 	if (NCE_MYADDR(ncec))
11206 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11207 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11208 		flags |= ACE_F_UNVERIFIED;
11209 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11210 		flags |= ACE_F_AUTHORITY;
11211 	if (ncec->ncec_flags & NCE_F_DELAYED)
11212 		flags |= ACE_F_DELAYED;
11213 	return (flags);
11214 }
11215 
11216 /*
11217  * ncec_walk routine to create ipNetToMediaEntryTable
11218  */
11219 static int
11220 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11221 {
11222 	ill_t				*ill;
11223 	mib2_ipNetToMediaEntry_t	ntme;
11224 	const char			*name = "unknown";
11225 	ipaddr_t			ncec_addr;
11226 
11227 	ill = ncec->ncec_ill;
11228 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11229 	    ill->ill_net_type == IRE_LOOPBACK)
11230 		return (0);
11231 
11232 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11233 	name = ill->ill_name;
11234 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11235 	if (NCE_MYADDR(ncec)) {
11236 		ntme.ipNetToMediaType = 4;
11237 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11238 		ntme.ipNetToMediaType = 1;
11239 	} else {
11240 		ntme.ipNetToMediaType = 3;
11241 	}
11242 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11243 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11244 	    ntme.ipNetToMediaIfIndex.o_length);
11245 
11246 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11247 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11248 
11249 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11250 	ncec_addr = INADDR_BROADCAST;
11251 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11252 	    sizeof (ncec_addr));
11253 	/*
11254 	 * map all the flags to the ACE counterpart.
11255 	 */
11256 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11257 
11258 	ntme.ipNetToMediaPhysAddress.o_length =
11259 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11260 
11261 	if (!NCE_ISREACHABLE(ncec))
11262 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11263 	else {
11264 		if (ncec->ncec_lladdr != NULL) {
11265 			bcopy(ncec->ncec_lladdr,
11266 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11267 			    ntme.ipNetToMediaPhysAddress.o_length);
11268 		}
11269 	}
11270 
11271 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11272 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11273 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11274 		    (uint_t)sizeof (ntme)));
11275 	}
11276 	return (0);
11277 }
11278 
11279 /*
11280  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11281  */
11282 /* ARGSUSED */
11283 int
11284 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11285 {
11286 	switch (level) {
11287 	case MIB2_IP:
11288 	case MIB2_ICMP:
11289 		switch (name) {
11290 		default:
11291 			break;
11292 		}
11293 		return (1);
11294 	default:
11295 		return (1);
11296 	}
11297 }
11298 
11299 /*
11300  * When there exists both a 64- and 32-bit counter of a particular type
11301  * (i.e., InReceives), only the 64-bit counters are added.
11302  */
11303 void
11304 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11305 {
11306 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11307 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11308 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11309 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11310 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11311 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11312 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11313 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11314 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11315 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11316 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11317 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11318 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11319 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11320 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11321 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11322 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11323 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11324 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11325 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11326 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11327 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11328 	    o2->ipIfStatsInWrongIPVersion);
11329 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11330 	    o2->ipIfStatsInWrongIPVersion);
11331 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11332 	    o2->ipIfStatsOutSwitchIPVersion);
11333 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11334 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11335 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11336 	    o2->ipIfStatsHCInForwDatagrams);
11337 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11338 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11339 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11340 	    o2->ipIfStatsHCOutForwDatagrams);
11341 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11342 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11343 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11344 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11345 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11346 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11347 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11348 	    o2->ipIfStatsHCOutMcastOctets);
11349 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11350 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11351 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11352 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11353 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11354 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11355 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11356 }
11357 
11358 void
11359 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11360 {
11361 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11362 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11363 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11364 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11365 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11366 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11367 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11368 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11369 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11370 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11371 	    o2->ipv6IfIcmpInRouterSolicits);
11372 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11373 	    o2->ipv6IfIcmpInRouterAdvertisements);
11374 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11375 	    o2->ipv6IfIcmpInNeighborSolicits);
11376 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11377 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11378 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11379 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11380 	    o2->ipv6IfIcmpInGroupMembQueries);
11381 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11382 	    o2->ipv6IfIcmpInGroupMembResponses);
11383 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11384 	    o2->ipv6IfIcmpInGroupMembReductions);
11385 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11386 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11387 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11388 	    o2->ipv6IfIcmpOutDestUnreachs);
11389 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11390 	    o2->ipv6IfIcmpOutAdminProhibs);
11391 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11392 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11393 	    o2->ipv6IfIcmpOutParmProblems);
11394 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11395 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11396 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11397 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11398 	    o2->ipv6IfIcmpOutRouterSolicits);
11399 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11400 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11401 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11402 	    o2->ipv6IfIcmpOutNeighborSolicits);
11403 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11404 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11405 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11406 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11407 	    o2->ipv6IfIcmpOutGroupMembQueries);
11408 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11409 	    o2->ipv6IfIcmpOutGroupMembResponses);
11410 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11411 	    o2->ipv6IfIcmpOutGroupMembReductions);
11412 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11413 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11414 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11415 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11416 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11417 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11418 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11419 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11420 	    o2->ipv6IfIcmpInGroupMembTotal);
11421 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11422 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11423 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11424 	    o2->ipv6IfIcmpInGroupMembBadReports);
11425 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11426 	    o2->ipv6IfIcmpInGroupMembOurReports);
11427 }
11428 
11429 /*
11430  * Called before the options are updated to check if this packet will
11431  * be source routed from here.
11432  * This routine assumes that the options are well formed i.e. that they
11433  * have already been checked.
11434  */
11435 boolean_t
11436 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11437 {
11438 	ipoptp_t	opts;
11439 	uchar_t		*opt;
11440 	uint8_t		optval;
11441 	uint8_t		optlen;
11442 	ipaddr_t	dst;
11443 
11444 	if (IS_SIMPLE_IPH(ipha)) {
11445 		ip2dbg(("not source routed\n"));
11446 		return (B_FALSE);
11447 	}
11448 	dst = ipha->ipha_dst;
11449 	for (optval = ipoptp_first(&opts, ipha);
11450 	    optval != IPOPT_EOL;
11451 	    optval = ipoptp_next(&opts)) {
11452 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11453 		opt = opts.ipoptp_cur;
11454 		optlen = opts.ipoptp_len;
11455 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11456 		    optval, optlen));
11457 		switch (optval) {
11458 			uint32_t off;
11459 		case IPOPT_SSRR:
11460 		case IPOPT_LSRR:
11461 			/*
11462 			 * If dst is one of our addresses and there are some
11463 			 * entries left in the source route return (true).
11464 			 */
11465 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11466 				ip2dbg(("ip_source_routed: not next"
11467 				    " source route 0x%x\n",
11468 				    ntohl(dst)));
11469 				return (B_FALSE);
11470 			}
11471 			off = opt[IPOPT_OFFSET];
11472 			off--;
11473 			if (optlen < IP_ADDR_LEN ||
11474 			    off > optlen - IP_ADDR_LEN) {
11475 				/* End of source route */
11476 				ip1dbg(("ip_source_routed: end of SR\n"));
11477 				return (B_FALSE);
11478 			}
11479 			return (B_TRUE);
11480 		}
11481 	}
11482 	ip2dbg(("not source routed\n"));
11483 	return (B_FALSE);
11484 }
11485 
11486 /*
11487  * ip_unbind is called by the transports to remove a conn from
11488  * the fanout table.
11489  */
11490 void
11491 ip_unbind(conn_t *connp)
11492 {
11493 
11494 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11495 
11496 	if (is_system_labeled() && connp->conn_anon_port) {
11497 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11498 		    connp->conn_mlp_type, connp->conn_proto,
11499 		    ntohs(connp->conn_lport), B_FALSE);
11500 		connp->conn_anon_port = 0;
11501 	}
11502 	connp->conn_mlp_type = mlptSingle;
11503 
11504 	ipcl_hash_remove(connp);
11505 }
11506 
11507 /*
11508  * Used for deciding the MSS size for the upper layer. Thus
11509  * we need to check the outbound policy values in the conn.
11510  */
11511 int
11512 conn_ipsec_length(conn_t *connp)
11513 {
11514 	ipsec_latch_t *ipl;
11515 
11516 	ipl = connp->conn_latch;
11517 	if (ipl == NULL)
11518 		return (0);
11519 
11520 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11521 		return (0);
11522 
11523 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11524 }
11525 
11526 /*
11527  * Returns an estimate of the IPsec headers size. This is used if
11528  * we don't want to call into IPsec to get the exact size.
11529  */
11530 int
11531 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11532 {
11533 	ipsec_action_t *a;
11534 
11535 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11536 		return (0);
11537 
11538 	a = ixa->ixa_ipsec_action;
11539 	if (a == NULL) {
11540 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11541 		a = ixa->ixa_ipsec_policy->ipsp_act;
11542 	}
11543 	ASSERT(a != NULL);
11544 
11545 	return (a->ipa_ovhd);
11546 }
11547 
11548 /*
11549  * If there are any source route options, return the true final
11550  * destination. Otherwise, return the destination.
11551  */
11552 ipaddr_t
11553 ip_get_dst(ipha_t *ipha)
11554 {
11555 	ipoptp_t	opts;
11556 	uchar_t		*opt;
11557 	uint8_t		optval;
11558 	uint8_t		optlen;
11559 	ipaddr_t	dst;
11560 	uint32_t off;
11561 
11562 	dst = ipha->ipha_dst;
11563 
11564 	if (IS_SIMPLE_IPH(ipha))
11565 		return (dst);
11566 
11567 	for (optval = ipoptp_first(&opts, ipha);
11568 	    optval != IPOPT_EOL;
11569 	    optval = ipoptp_next(&opts)) {
11570 		opt = opts.ipoptp_cur;
11571 		optlen = opts.ipoptp_len;
11572 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11573 		switch (optval) {
11574 		case IPOPT_SSRR:
11575 		case IPOPT_LSRR:
11576 			off = opt[IPOPT_OFFSET];
11577 			/*
11578 			 * If one of the conditions is true, it means
11579 			 * end of options and dst already has the right
11580 			 * value.
11581 			 */
11582 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11583 				off = optlen - IP_ADDR_LEN;
11584 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11585 			}
11586 			return (dst);
11587 		default:
11588 			break;
11589 		}
11590 	}
11591 
11592 	return (dst);
11593 }
11594 
11595 /*
11596  * Outbound IP fragmentation routine.
11597  * Assumes the caller has checked whether or not fragmentation should
11598  * be allowed. Here we copy the DF bit from the header to all the generated
11599  * fragments.
11600  */
11601 int
11602 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11603     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11604     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11605 {
11606 	int		i1;
11607 	int		hdr_len;
11608 	mblk_t		*hdr_mp;
11609 	ipha_t		*ipha;
11610 	int		ip_data_end;
11611 	int		len;
11612 	mblk_t		*mp = mp_orig;
11613 	int		offset;
11614 	ill_t		*ill = nce->nce_ill;
11615 	ip_stack_t	*ipst = ill->ill_ipst;
11616 	mblk_t		*carve_mp;
11617 	uint32_t	frag_flag;
11618 	uint_t		priority = mp->b_band;
11619 	int		error = 0;
11620 
11621 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11622 
11623 	if (pkt_len != msgdsize(mp)) {
11624 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11625 		    pkt_len, msgdsize(mp)));
11626 		freemsg(mp);
11627 		return (EINVAL);
11628 	}
11629 
11630 	if (max_frag == 0) {
11631 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11632 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11633 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11634 		freemsg(mp);
11635 		return (EINVAL);
11636 	}
11637 
11638 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11639 	ipha = (ipha_t *)mp->b_rptr;
11640 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11641 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11642 
11643 	/*
11644 	 * Establish the starting offset.  May not be zero if we are fragging
11645 	 * a fragment that is being forwarded.
11646 	 */
11647 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11648 
11649 	/* TODO why is this test needed? */
11650 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11651 		/* TODO: notify ulp somehow */
11652 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11653 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11654 		freemsg(mp);
11655 		return (EINVAL);
11656 	}
11657 
11658 	hdr_len = IPH_HDR_LENGTH(ipha);
11659 	ipha->ipha_hdr_checksum = 0;
11660 
11661 	/*
11662 	 * Establish the number of bytes maximum per frag, after putting
11663 	 * in the header.
11664 	 */
11665 	len = (max_frag - hdr_len) & ~7;
11666 
11667 	/* Get a copy of the header for the trailing frags */
11668 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11669 	    mp);
11670 	if (hdr_mp == NULL) {
11671 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11672 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11673 		freemsg(mp);
11674 		return (ENOBUFS);
11675 	}
11676 
11677 	/* Store the starting offset, with the MoreFrags flag. */
11678 	i1 = offset | IPH_MF | frag_flag;
11679 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11680 
11681 	/* Establish the ending byte offset, based on the starting offset. */
11682 	offset <<= 3;
11683 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11684 
11685 	/* Store the length of the first fragment in the IP header. */
11686 	i1 = len + hdr_len;
11687 	ASSERT(i1 <= IP_MAXPACKET);
11688 	ipha->ipha_length = htons((uint16_t)i1);
11689 
11690 	/*
11691 	 * Compute the IP header checksum for the first frag.  We have to
11692 	 * watch out that we stop at the end of the header.
11693 	 */
11694 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11695 
11696 	/*
11697 	 * Now carve off the first frag.  Note that this will include the
11698 	 * original IP header.
11699 	 */
11700 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11701 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11702 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11703 		freeb(hdr_mp);
11704 		freemsg(mp_orig);
11705 		return (ENOBUFS);
11706 	}
11707 
11708 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11709 
11710 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11711 	    ixa_cookie);
11712 	if (error != 0 && error != EWOULDBLOCK) {
11713 		/* No point in sending the other fragments */
11714 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11715 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11716 		freeb(hdr_mp);
11717 		freemsg(mp_orig);
11718 		return (error);
11719 	}
11720 
11721 	/* No need to redo state machine in loop */
11722 	ixaflags &= ~IXAF_REACH_CONF;
11723 
11724 	/* Advance the offset to the second frag starting point. */
11725 	offset += len;
11726 	/*
11727 	 * Update hdr_len from the copied header - there might be less options
11728 	 * in the later fragments.
11729 	 */
11730 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11731 	/* Loop until done. */
11732 	for (;;) {
11733 		uint16_t	offset_and_flags;
11734 		uint16_t	ip_len;
11735 
11736 		if (ip_data_end - offset > len) {
11737 			/*
11738 			 * Carve off the appropriate amount from the original
11739 			 * datagram.
11740 			 */
11741 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11742 				mp = NULL;
11743 				break;
11744 			}
11745 			/*
11746 			 * More frags after this one.  Get another copy
11747 			 * of the header.
11748 			 */
11749 			if (carve_mp->b_datap->db_ref == 1 &&
11750 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11751 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11752 				/* Inline IP header */
11753 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11754 				    hdr_mp->b_rptr;
11755 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11756 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11757 				mp = carve_mp;
11758 			} else {
11759 				if (!(mp = copyb(hdr_mp))) {
11760 					freemsg(carve_mp);
11761 					break;
11762 				}
11763 				/* Get priority marking, if any. */
11764 				mp->b_band = priority;
11765 				mp->b_cont = carve_mp;
11766 			}
11767 			ipha = (ipha_t *)mp->b_rptr;
11768 			offset_and_flags = IPH_MF;
11769 		} else {
11770 			/*
11771 			 * Last frag.  Consume the header. Set len to
11772 			 * the length of this last piece.
11773 			 */
11774 			len = ip_data_end - offset;
11775 
11776 			/*
11777 			 * Carve off the appropriate amount from the original
11778 			 * datagram.
11779 			 */
11780 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11781 				mp = NULL;
11782 				break;
11783 			}
11784 			if (carve_mp->b_datap->db_ref == 1 &&
11785 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11786 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11787 				/* Inline IP header */
11788 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11789 				    hdr_mp->b_rptr;
11790 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11791 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11792 				mp = carve_mp;
11793 				freeb(hdr_mp);
11794 				hdr_mp = mp;
11795 			} else {
11796 				mp = hdr_mp;
11797 				/* Get priority marking, if any. */
11798 				mp->b_band = priority;
11799 				mp->b_cont = carve_mp;
11800 			}
11801 			ipha = (ipha_t *)mp->b_rptr;
11802 			/* A frag of a frag might have IPH_MF non-zero */
11803 			offset_and_flags =
11804 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11805 			    IPH_MF;
11806 		}
11807 		offset_and_flags |= (uint16_t)(offset >> 3);
11808 		offset_and_flags |= (uint16_t)frag_flag;
11809 		/* Store the offset and flags in the IP header. */
11810 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11811 
11812 		/* Store the length in the IP header. */
11813 		ip_len = (uint16_t)(len + hdr_len);
11814 		ipha->ipha_length = htons(ip_len);
11815 
11816 		/*
11817 		 * Set the IP header checksum.	Note that mp is just
11818 		 * the header, so this is easy to pass to ip_csum.
11819 		 */
11820 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11821 
11822 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11823 
11824 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11825 		    nolzid, ixa_cookie);
11826 		/* All done if we just consumed the hdr_mp. */
11827 		if (mp == hdr_mp) {
11828 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11829 			return (error);
11830 		}
11831 		if (error != 0 && error != EWOULDBLOCK) {
11832 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11833 			    mblk_t *, hdr_mp);
11834 			/* No point in sending the other fragments */
11835 			break;
11836 		}
11837 
11838 		/* Otherwise, advance and loop. */
11839 		offset += len;
11840 	}
11841 	/* Clean up following allocation failure. */
11842 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11843 	ip_drop_output("FragFails: loop ended", NULL, ill);
11844 	if (mp != hdr_mp)
11845 		freeb(hdr_mp);
11846 	if (mp != mp_orig)
11847 		freemsg(mp_orig);
11848 	return (error);
11849 }
11850 
11851 /*
11852  * Copy the header plus those options which have the copy bit set
11853  */
11854 static mblk_t *
11855 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11856     mblk_t *src)
11857 {
11858 	mblk_t	*mp;
11859 	uchar_t	*up;
11860 
11861 	/*
11862 	 * Quick check if we need to look for options without the copy bit
11863 	 * set
11864 	 */
11865 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11866 	if (!mp)
11867 		return (mp);
11868 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11869 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11870 		bcopy(rptr, mp->b_rptr, hdr_len);
11871 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11872 		return (mp);
11873 	}
11874 	up  = mp->b_rptr;
11875 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11876 	up += IP_SIMPLE_HDR_LENGTH;
11877 	rptr += IP_SIMPLE_HDR_LENGTH;
11878 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11879 	while (hdr_len > 0) {
11880 		uint32_t optval;
11881 		uint32_t optlen;
11882 
11883 		optval = *rptr;
11884 		if (optval == IPOPT_EOL)
11885 			break;
11886 		if (optval == IPOPT_NOP)
11887 			optlen = 1;
11888 		else
11889 			optlen = rptr[1];
11890 		if (optval & IPOPT_COPY) {
11891 			bcopy(rptr, up, optlen);
11892 			up += optlen;
11893 		}
11894 		rptr += optlen;
11895 		hdr_len -= optlen;
11896 	}
11897 	/*
11898 	 * Make sure that we drop an even number of words by filling
11899 	 * with EOL to the next word boundary.
11900 	 */
11901 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11902 	    hdr_len & 0x3; hdr_len++)
11903 		*up++ = IPOPT_EOL;
11904 	mp->b_wptr = up;
11905 	/* Update header length */
11906 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11907 	return (mp);
11908 }
11909 
11910 /*
11911  * Update any source route, record route, or timestamp options when
11912  * sending a packet back to ourselves.
11913  * Check that we are at end of strict source route.
11914  * The options have been sanity checked by ip_output_options().
11915  */
11916 void
11917 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11918 {
11919 	ipoptp_t	opts;
11920 	uchar_t		*opt;
11921 	uint8_t		optval;
11922 	uint8_t		optlen;
11923 	ipaddr_t	dst;
11924 	uint32_t	ts;
11925 	timestruc_t	now;
11926 
11927 	for (optval = ipoptp_first(&opts, ipha);
11928 	    optval != IPOPT_EOL;
11929 	    optval = ipoptp_next(&opts)) {
11930 		opt = opts.ipoptp_cur;
11931 		optlen = opts.ipoptp_len;
11932 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11933 		switch (optval) {
11934 			uint32_t off;
11935 		case IPOPT_SSRR:
11936 		case IPOPT_LSRR:
11937 			off = opt[IPOPT_OFFSET];
11938 			off--;
11939 			if (optlen < IP_ADDR_LEN ||
11940 			    off > optlen - IP_ADDR_LEN) {
11941 				/* End of source route */
11942 				break;
11943 			}
11944 			/*
11945 			 * This will only happen if two consecutive entries
11946 			 * in the source route contains our address or if
11947 			 * it is a packet with a loose source route which
11948 			 * reaches us before consuming the whole source route
11949 			 */
11950 
11951 			if (optval == IPOPT_SSRR) {
11952 				return;
11953 			}
11954 			/*
11955 			 * Hack: instead of dropping the packet truncate the
11956 			 * source route to what has been used by filling the
11957 			 * rest with IPOPT_NOP.
11958 			 */
11959 			opt[IPOPT_OLEN] = (uint8_t)off;
11960 			while (off < optlen) {
11961 				opt[off++] = IPOPT_NOP;
11962 			}
11963 			break;
11964 		case IPOPT_RR:
11965 			off = opt[IPOPT_OFFSET];
11966 			off--;
11967 			if (optlen < IP_ADDR_LEN ||
11968 			    off > optlen - IP_ADDR_LEN) {
11969 				/* No more room - ignore */
11970 				ip1dbg((
11971 				    "ip_output_local_options: end of RR\n"));
11972 				break;
11973 			}
11974 			dst = htonl(INADDR_LOOPBACK);
11975 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11976 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11977 			break;
11978 		case IPOPT_TS:
11979 			/* Insert timestamp if there is romm */
11980 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
11981 			case IPOPT_TS_TSONLY:
11982 				off = IPOPT_TS_TIMELEN;
11983 				break;
11984 			case IPOPT_TS_PRESPEC:
11985 			case IPOPT_TS_PRESPEC_RFC791:
11986 				/* Verify that the address matched */
11987 				off = opt[IPOPT_OFFSET] - 1;
11988 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
11989 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11990 					/* Not for us */
11991 					break;
11992 				}
11993 				/* FALLTHRU */
11994 			case IPOPT_TS_TSANDADDR:
11995 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
11996 				break;
11997 			default:
11998 				/*
11999 				 * ip_*put_options should have already
12000 				 * dropped this packet.
12001 				 */
12002 				cmn_err(CE_PANIC, "ip_output_local_options: "
12003 				    "unknown IT - bug in ip_output_options?\n");
12004 				return;	/* Keep "lint" happy */
12005 			}
12006 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
12007 				/* Increase overflow counter */
12008 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
12009 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
12010 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
12011 				    (off << 4);
12012 				break;
12013 			}
12014 			off = opt[IPOPT_OFFSET] - 1;
12015 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12016 			case IPOPT_TS_PRESPEC:
12017 			case IPOPT_TS_PRESPEC_RFC791:
12018 			case IPOPT_TS_TSANDADDR:
12019 				dst = htonl(INADDR_LOOPBACK);
12020 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12021 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12022 				/* FALLTHRU */
12023 			case IPOPT_TS_TSONLY:
12024 				off = opt[IPOPT_OFFSET] - 1;
12025 				/* Compute # of milliseconds since midnight */
12026 				gethrestime(&now);
12027 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
12028 				    NSEC2MSEC(now.tv_nsec);
12029 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
12030 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
12031 				break;
12032 			}
12033 			break;
12034 		}
12035 	}
12036 }
12037 
12038 /*
12039  * Prepend an M_DATA fastpath header, and if none present prepend a
12040  * DL_UNITDATA_REQ. Frees the mblk on failure.
12041  *
12042  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
12043  * If there is a change to them, the nce will be deleted (condemned) and
12044  * a new nce_t will be created when packets are sent. Thus we need no locks
12045  * to access those fields.
12046  *
12047  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
12048  * we place b_band in dl_priority.dl_max.
12049  */
12050 static mblk_t *
12051 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
12052 {
12053 	uint_t	hlen;
12054 	mblk_t *mp1;
12055 	uint_t	priority;
12056 	uchar_t *rptr;
12057 
12058 	rptr = mp->b_rptr;
12059 
12060 	ASSERT(DB_TYPE(mp) == M_DATA);
12061 	priority = mp->b_band;
12062 
12063 	ASSERT(nce != NULL);
12064 	if ((mp1 = nce->nce_fp_mp) != NULL) {
12065 		hlen = MBLKL(mp1);
12066 		/*
12067 		 * Check if we have enough room to prepend fastpath
12068 		 * header
12069 		 */
12070 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
12071 			rptr -= hlen;
12072 			bcopy(mp1->b_rptr, rptr, hlen);
12073 			/*
12074 			 * Set the b_rptr to the start of the link layer
12075 			 * header
12076 			 */
12077 			mp->b_rptr = rptr;
12078 			return (mp);
12079 		}
12080 		mp1 = copyb(mp1);
12081 		if (mp1 == NULL) {
12082 			ill_t *ill = nce->nce_ill;
12083 
12084 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12085 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12086 			freemsg(mp);
12087 			return (NULL);
12088 		}
12089 		mp1->b_band = priority;
12090 		mp1->b_cont = mp;
12091 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12092 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12093 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12094 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12095 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12096 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12097 		/*
12098 		 * XXX disable ICK_VALID and compute checksum
12099 		 * here; can happen if nce_fp_mp changes and
12100 		 * it can't be copied now due to insufficient
12101 		 * space. (unlikely, fp mp can change, but it
12102 		 * does not increase in length)
12103 		 */
12104 		return (mp1);
12105 	}
12106 	mp1 = copyb(nce->nce_dlur_mp);
12107 
12108 	if (mp1 == NULL) {
12109 		ill_t *ill = nce->nce_ill;
12110 
12111 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12112 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12113 		freemsg(mp);
12114 		return (NULL);
12115 	}
12116 	mp1->b_cont = mp;
12117 	if (priority != 0) {
12118 		mp1->b_band = priority;
12119 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12120 		    priority;
12121 	}
12122 	return (mp1);
12123 }
12124 
12125 /*
12126  * Finish the outbound IPsec processing. This function is called from
12127  * ipsec_out_process() if the IPsec packet was processed
12128  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12129  * asynchronously.
12130  *
12131  * This is common to IPv4 and IPv6.
12132  */
12133 int
12134 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12135 {
12136 	iaflags_t	ixaflags = ixa->ixa_flags;
12137 	uint_t		pktlen;
12138 
12139 
12140 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12141 	if (ixaflags & IXAF_IS_IPV4) {
12142 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12143 
12144 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12145 		pktlen = ntohs(ipha->ipha_length);
12146 	} else {
12147 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12148 
12149 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12150 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12151 	}
12152 
12153 	/*
12154 	 * We release any hard reference on the SAs here to make
12155 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12156 	 * on the SAs.
12157 	 * If in the future we want the hard latching of the SAs in the
12158 	 * ip_xmit_attr_t then we should remove this.
12159 	 */
12160 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12161 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12162 		ixa->ixa_ipsec_esp_sa = NULL;
12163 	}
12164 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12165 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12166 		ixa->ixa_ipsec_ah_sa = NULL;
12167 	}
12168 
12169 	/* Do we need to fragment? */
12170 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12171 	    pktlen > ixa->ixa_fragsize) {
12172 		if (ixaflags & IXAF_IS_IPV4) {
12173 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12174 			/*
12175 			 * We check for the DF case in ipsec_out_process
12176 			 * hence this only handles the non-DF case.
12177 			 */
12178 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12179 			    pktlen, ixa->ixa_fragsize,
12180 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12181 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12182 			    &ixa->ixa_cookie));
12183 		} else {
12184 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12185 			if (mp == NULL) {
12186 				/* MIB and ip_drop_output already done */
12187 				return (ENOMEM);
12188 			}
12189 			pktlen += sizeof (ip6_frag_t);
12190 			if (pktlen > ixa->ixa_fragsize) {
12191 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12192 				    ixa->ixa_flags, pktlen,
12193 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12194 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12195 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12196 			}
12197 		}
12198 	}
12199 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12200 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12201 	    ixa->ixa_no_loop_zoneid, NULL));
12202 }
12203 
12204 /*
12205  * Finish the inbound IPsec processing. This function is called from
12206  * ipsec_out_process() if the IPsec packet was processed
12207  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12208  * asynchronously.
12209  *
12210  * This is common to IPv4 and IPv6.
12211  */
12212 void
12213 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12214 {
12215 	iaflags_t	iraflags = ira->ira_flags;
12216 
12217 	/* Length might have changed */
12218 	if (iraflags & IRAF_IS_IPV4) {
12219 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12220 
12221 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12222 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12223 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12224 		ira->ira_protocol = ipha->ipha_protocol;
12225 
12226 		ip_fanout_v4(mp, ipha, ira);
12227 	} else {
12228 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12229 		uint8_t		*nexthdrp;
12230 
12231 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12232 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12233 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12234 		    &nexthdrp)) {
12235 			/* Malformed packet */
12236 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12237 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12238 			freemsg(mp);
12239 			return;
12240 		}
12241 		ira->ira_protocol = *nexthdrp;
12242 		ip_fanout_v6(mp, ip6h, ira);
12243 	}
12244 }
12245 
12246 /*
12247  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12248  *
12249  * If this function returns B_TRUE, the requested SA's have been filled
12250  * into the ixa_ipsec_*_sa pointers.
12251  *
12252  * If the function returns B_FALSE, the packet has been "consumed", most
12253  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12254  *
12255  * The SA references created by the protocol-specific "select"
12256  * function will be released in ip_output_post_ipsec.
12257  */
12258 static boolean_t
12259 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12260 {
12261 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12262 	ipsec_policy_t *pp;
12263 	ipsec_action_t *ap;
12264 
12265 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12266 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12267 	    (ixa->ixa_ipsec_action != NULL));
12268 
12269 	ap = ixa->ixa_ipsec_action;
12270 	if (ap == NULL) {
12271 		pp = ixa->ixa_ipsec_policy;
12272 		ASSERT(pp != NULL);
12273 		ap = pp->ipsp_act;
12274 		ASSERT(ap != NULL);
12275 	}
12276 
12277 	/*
12278 	 * We have an action.  now, let's select SA's.
12279 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12280 	 * be cached in the conn_t.
12281 	 */
12282 	if (ap->ipa_want_esp) {
12283 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12284 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12285 			    IPPROTO_ESP);
12286 		}
12287 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12288 	}
12289 
12290 	if (ap->ipa_want_ah) {
12291 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12292 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12293 			    IPPROTO_AH);
12294 		}
12295 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12296 		/*
12297 		 * The ESP and AH processing order needs to be preserved
12298 		 * when both protocols are required (ESP should be applied
12299 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12300 		 * when both ESP and AH are required, and an AH ACQUIRE
12301 		 * is needed.
12302 		 */
12303 		if (ap->ipa_want_esp && need_ah_acquire)
12304 			need_esp_acquire = B_TRUE;
12305 	}
12306 
12307 	/*
12308 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12309 	 * Release SAs that got referenced, but will not be used until we
12310 	 * acquire _all_ of the SAs we need.
12311 	 */
12312 	if (need_ah_acquire || need_esp_acquire) {
12313 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12314 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12315 			ixa->ixa_ipsec_ah_sa = NULL;
12316 		}
12317 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12318 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12319 			ixa->ixa_ipsec_esp_sa = NULL;
12320 		}
12321 
12322 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12323 		return (B_FALSE);
12324 	}
12325 
12326 	return (B_TRUE);
12327 }
12328 
12329 /*
12330  * Handle IPsec output processing.
12331  * This function is only entered once for a given packet.
12332  * We try to do things synchronously, but if we need to have user-level
12333  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12334  * will be completed
12335  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12336  *  - when asynchronous ESP is done it will do AH
12337  *
12338  * In all cases we come back in ip_output_post_ipsec() to fragment and
12339  * send out the packet.
12340  */
12341 int
12342 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12343 {
12344 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12345 	ip_stack_t	*ipst = ixa->ixa_ipst;
12346 	ipsec_stack_t	*ipss;
12347 	ipsec_policy_t	*pp;
12348 	ipsec_action_t	*ap;
12349 
12350 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12351 
12352 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12353 	    (ixa->ixa_ipsec_action != NULL));
12354 
12355 	ipss = ipst->ips_netstack->netstack_ipsec;
12356 	if (!ipsec_loaded(ipss)) {
12357 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12358 		ip_drop_packet(mp, B_TRUE, ill,
12359 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12360 		    &ipss->ipsec_dropper);
12361 		return (ENOTSUP);
12362 	}
12363 
12364 	ap = ixa->ixa_ipsec_action;
12365 	if (ap == NULL) {
12366 		pp = ixa->ixa_ipsec_policy;
12367 		ASSERT(pp != NULL);
12368 		ap = pp->ipsp_act;
12369 		ASSERT(ap != NULL);
12370 	}
12371 
12372 	/* Handle explicit drop action and bypass. */
12373 	switch (ap->ipa_act.ipa_type) {
12374 	case IPSEC_ACT_DISCARD:
12375 	case IPSEC_ACT_REJECT:
12376 		ip_drop_packet(mp, B_FALSE, ill,
12377 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12378 		return (EHOSTUNREACH);	/* IPsec policy failure */
12379 	case IPSEC_ACT_BYPASS:
12380 		return (ip_output_post_ipsec(mp, ixa));
12381 	}
12382 
12383 	/*
12384 	 * The order of processing is first insert a IP header if needed.
12385 	 * Then insert the ESP header and then the AH header.
12386 	 */
12387 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12388 		/*
12389 		 * First get the outer IP header before sending
12390 		 * it to ESP.
12391 		 */
12392 		ipha_t *oipha, *iipha;
12393 		mblk_t *outer_mp, *inner_mp;
12394 
12395 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12396 			(void) mi_strlog(ill->ill_rq, 0,
12397 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12398 			    "ipsec_out_process: "
12399 			    "Self-Encapsulation failed: Out of memory\n");
12400 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12401 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12402 			freemsg(mp);
12403 			return (ENOBUFS);
12404 		}
12405 		inner_mp = mp;
12406 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12407 		oipha = (ipha_t *)outer_mp->b_rptr;
12408 		iipha = (ipha_t *)inner_mp->b_rptr;
12409 		*oipha = *iipha;
12410 		outer_mp->b_wptr += sizeof (ipha_t);
12411 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12412 		    sizeof (ipha_t));
12413 		oipha->ipha_protocol = IPPROTO_ENCAP;
12414 		oipha->ipha_version_and_hdr_length =
12415 		    IP_SIMPLE_HDR_VERSION;
12416 		oipha->ipha_hdr_checksum = 0;
12417 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12418 		outer_mp->b_cont = inner_mp;
12419 		mp = outer_mp;
12420 
12421 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12422 	}
12423 
12424 	/* If we need to wait for a SA then we can't return any errno */
12425 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12426 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12427 	    !ipsec_out_select_sa(mp, ixa))
12428 		return (0);
12429 
12430 	/*
12431 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12432 	 * to do the heavy lifting.
12433 	 */
12434 	if (ap->ipa_want_esp) {
12435 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12436 
12437 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12438 		if (mp == NULL) {
12439 			/*
12440 			 * Either it failed or is pending. In the former case
12441 			 * ipIfStatsInDiscards was increased.
12442 			 */
12443 			return (0);
12444 		}
12445 	}
12446 
12447 	if (ap->ipa_want_ah) {
12448 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12449 
12450 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12451 		if (mp == NULL) {
12452 			/*
12453 			 * Either it failed or is pending. In the former case
12454 			 * ipIfStatsInDiscards was increased.
12455 			 */
12456 			return (0);
12457 		}
12458 	}
12459 	/*
12460 	 * We are done with IPsec processing. Send it over
12461 	 * the wire.
12462 	 */
12463 	return (ip_output_post_ipsec(mp, ixa));
12464 }
12465 
12466 /*
12467  * ioctls that go through a down/up sequence may need to wait for the down
12468  * to complete. This involves waiting for the ire and ipif refcnts to go down
12469  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12470  */
12471 /* ARGSUSED */
12472 void
12473 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12474 {
12475 	struct iocblk *iocp;
12476 	mblk_t *mp1;
12477 	ip_ioctl_cmd_t *ipip;
12478 	int err;
12479 	sin_t	*sin;
12480 	struct lifreq *lifr;
12481 	struct ifreq *ifr;
12482 
12483 	iocp = (struct iocblk *)mp->b_rptr;
12484 	ASSERT(ipsq != NULL);
12485 	/* Existence of mp1 verified in ip_wput_nondata */
12486 	mp1 = mp->b_cont->b_cont;
12487 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12488 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12489 		/*
12490 		 * Special case where ipx_current_ipif is not set:
12491 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12492 		 * We are here as were not able to complete the operation in
12493 		 * ipif_set_values because we could not become exclusive on
12494 		 * the new ipsq.
12495 		 */
12496 		ill_t *ill = q->q_ptr;
12497 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12498 	}
12499 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12500 
12501 	if (ipip->ipi_cmd_type == IF_CMD) {
12502 		/* This a old style SIOC[GS]IF* command */
12503 		ifr = (struct ifreq *)mp1->b_rptr;
12504 		sin = (sin_t *)&ifr->ifr_addr;
12505 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12506 		/* This a new style SIOC[GS]LIF* command */
12507 		lifr = (struct lifreq *)mp1->b_rptr;
12508 		sin = (sin_t *)&lifr->lifr_addr;
12509 	} else {
12510 		sin = NULL;
12511 	}
12512 
12513 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12514 	    q, mp, ipip, mp1->b_rptr);
12515 
12516 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12517 	    int, ipip->ipi_cmd,
12518 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12519 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12520 
12521 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12522 }
12523 
12524 /*
12525  * ioctl processing
12526  *
12527  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12528  * the ioctl command in the ioctl tables, determines the copyin data size
12529  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12530  *
12531  * ioctl processing then continues when the M_IOCDATA makes its way down to
12532  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12533  * associated 'conn' is refheld till the end of the ioctl and the general
12534  * ioctl processing function ip_process_ioctl() is called to extract the
12535  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12536  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12537  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12538  * is used to extract the ioctl's arguments.
12539  *
12540  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12541  * so goes thru the serialization primitive ipsq_try_enter. Then the
12542  * appropriate function to handle the ioctl is called based on the entry in
12543  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12544  * which also refreleases the 'conn' that was refheld at the start of the
12545  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12546  *
12547  * Many exclusive ioctls go thru an internal down up sequence as part of
12548  * the operation. For example an attempt to change the IP address of an
12549  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12550  * does all the cleanup such as deleting all ires that use this address.
12551  * Then we need to wait till all references to the interface go away.
12552  */
12553 void
12554 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12555 {
12556 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12557 	ip_ioctl_cmd_t *ipip = arg;
12558 	ip_extract_func_t *extract_funcp;
12559 	cmd_info_t ci;
12560 	int err;
12561 	boolean_t entered_ipsq = B_FALSE;
12562 
12563 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12564 
12565 	if (ipip == NULL)
12566 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12567 
12568 	/*
12569 	 * SIOCLIFADDIF needs to go thru a special path since the
12570 	 * ill may not exist yet. This happens in the case of lo0
12571 	 * which is created using this ioctl.
12572 	 */
12573 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12574 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12575 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12576 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12577 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12578 		return;
12579 	}
12580 
12581 	ci.ci_ipif = NULL;
12582 	switch (ipip->ipi_cmd_type) {
12583 	case MISC_CMD:
12584 	case MSFILT_CMD:
12585 		/*
12586 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12587 		 */
12588 		if (ipip->ipi_cmd == IF_UNITSEL) {
12589 			/* ioctl comes down the ill */
12590 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12591 			ipif_refhold(ci.ci_ipif);
12592 		}
12593 		err = 0;
12594 		ci.ci_sin = NULL;
12595 		ci.ci_sin6 = NULL;
12596 		ci.ci_lifr = NULL;
12597 		extract_funcp = NULL;
12598 		break;
12599 
12600 	case IF_CMD:
12601 	case LIF_CMD:
12602 		extract_funcp = ip_extract_lifreq;
12603 		break;
12604 
12605 	case ARP_CMD:
12606 	case XARP_CMD:
12607 		extract_funcp = ip_extract_arpreq;
12608 		break;
12609 
12610 	default:
12611 		ASSERT(0);
12612 	}
12613 
12614 	if (extract_funcp != NULL) {
12615 		err = (*extract_funcp)(q, mp, ipip, &ci);
12616 		if (err != 0) {
12617 			DTRACE_PROBE4(ipif__ioctl,
12618 			    char *, "ip_process_ioctl finish err",
12619 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12620 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12621 			return;
12622 		}
12623 
12624 		/*
12625 		 * All of the extraction functions return a refheld ipif.
12626 		 */
12627 		ASSERT(ci.ci_ipif != NULL);
12628 	}
12629 
12630 	if (!(ipip->ipi_flags & IPI_WR)) {
12631 		/*
12632 		 * A return value of EINPROGRESS means the ioctl is
12633 		 * either queued and waiting for some reason or has
12634 		 * already completed.
12635 		 */
12636 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12637 		    ci.ci_lifr);
12638 		if (ci.ci_ipif != NULL) {
12639 			DTRACE_PROBE4(ipif__ioctl,
12640 			    char *, "ip_process_ioctl finish RD",
12641 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12642 			    ipif_t *, ci.ci_ipif);
12643 			ipif_refrele(ci.ci_ipif);
12644 		} else {
12645 			DTRACE_PROBE4(ipif__ioctl,
12646 			    char *, "ip_process_ioctl finish RD",
12647 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12648 		}
12649 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12650 		return;
12651 	}
12652 
12653 	ASSERT(ci.ci_ipif != NULL);
12654 
12655 	/*
12656 	 * If ipsq is non-NULL, we are already being called exclusively
12657 	 */
12658 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12659 	if (ipsq == NULL) {
12660 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12661 		    NEW_OP, B_TRUE);
12662 		if (ipsq == NULL) {
12663 			ipif_refrele(ci.ci_ipif);
12664 			return;
12665 		}
12666 		entered_ipsq = B_TRUE;
12667 	}
12668 	/*
12669 	 * Release the ipif so that ipif_down and friends that wait for
12670 	 * references to go away are not misled about the current ipif_refcnt
12671 	 * values. We are writer so we can access the ipif even after releasing
12672 	 * the ipif.
12673 	 */
12674 	ipif_refrele(ci.ci_ipif);
12675 
12676 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12677 
12678 	/*
12679 	 * A return value of EINPROGRESS means the ioctl is
12680 	 * either queued and waiting for some reason or has
12681 	 * already completed.
12682 	 */
12683 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12684 
12685 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12686 	    int, ipip->ipi_cmd,
12687 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12688 	    ipif_t *, ci.ci_ipif);
12689 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12690 
12691 	if (entered_ipsq)
12692 		ipsq_exit(ipsq);
12693 }
12694 
12695 /*
12696  * Complete the ioctl. Typically ioctls use the mi package and need to
12697  * do mi_copyout/mi_copy_done.
12698  */
12699 void
12700 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12701 {
12702 	conn_t	*connp = NULL;
12703 
12704 	if (err == EINPROGRESS)
12705 		return;
12706 
12707 	if (CONN_Q(q)) {
12708 		connp = Q_TO_CONN(q);
12709 		ASSERT(connp->conn_ref >= 2);
12710 	}
12711 
12712 	switch (mode) {
12713 	case COPYOUT:
12714 		if (err == 0)
12715 			mi_copyout(q, mp);
12716 		else
12717 			mi_copy_done(q, mp, err);
12718 		break;
12719 
12720 	case NO_COPYOUT:
12721 		mi_copy_done(q, mp, err);
12722 		break;
12723 
12724 	default:
12725 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12726 		break;
12727 	}
12728 
12729 	/*
12730 	 * The conn refhold and ioctlref placed on the conn at the start of the
12731 	 * ioctl are released here.
12732 	 */
12733 	if (connp != NULL) {
12734 		CONN_DEC_IOCTLREF(connp);
12735 		CONN_OPER_PENDING_DONE(connp);
12736 	}
12737 
12738 	if (ipsq != NULL)
12739 		ipsq_current_finish(ipsq);
12740 }
12741 
12742 /* Handles all non data messages */
12743 void
12744 ip_wput_nondata(queue_t *q, mblk_t *mp)
12745 {
12746 	mblk_t		*mp1;
12747 	struct iocblk	*iocp;
12748 	ip_ioctl_cmd_t	*ipip;
12749 	conn_t		*connp;
12750 	cred_t		*cr;
12751 	char		*proto_str;
12752 
12753 	if (CONN_Q(q))
12754 		connp = Q_TO_CONN(q);
12755 	else
12756 		connp = NULL;
12757 
12758 	switch (DB_TYPE(mp)) {
12759 	case M_IOCTL:
12760 		/*
12761 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12762 		 * will arrange to copy in associated control structures.
12763 		 */
12764 		ip_sioctl_copyin_setup(q, mp);
12765 		return;
12766 	case M_IOCDATA:
12767 		/*
12768 		 * Ensure that this is associated with one of our trans-
12769 		 * parent ioctls.  If it's not ours, discard it if we're
12770 		 * running as a driver, or pass it on if we're a module.
12771 		 */
12772 		iocp = (struct iocblk *)mp->b_rptr;
12773 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12774 		if (ipip == NULL) {
12775 			if (q->q_next == NULL) {
12776 				goto nak;
12777 			} else {
12778 				putnext(q, mp);
12779 			}
12780 			return;
12781 		}
12782 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12783 			/*
12784 			 * The ioctl is one we recognise, but is not consumed
12785 			 * by IP as a module and we are a module, so we drop
12786 			 */
12787 			goto nak;
12788 		}
12789 
12790 		/* IOCTL continuation following copyin or copyout. */
12791 		if (mi_copy_state(q, mp, NULL) == -1) {
12792 			/*
12793 			 * The copy operation failed.  mi_copy_state already
12794 			 * cleaned up, so we're out of here.
12795 			 */
12796 			return;
12797 		}
12798 		/*
12799 		 * If we just completed a copy in, we become writer and
12800 		 * continue processing in ip_sioctl_copyin_done.  If it
12801 		 * was a copy out, we call mi_copyout again.  If there is
12802 		 * nothing more to copy out, it will complete the IOCTL.
12803 		 */
12804 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12805 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12806 				mi_copy_done(q, mp, EPROTO);
12807 				return;
12808 			}
12809 			/*
12810 			 * Check for cases that need more copying.  A return
12811 			 * value of 0 means a second copyin has been started,
12812 			 * so we return; a return value of 1 means no more
12813 			 * copying is needed, so we continue.
12814 			 */
12815 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12816 			    MI_COPY_COUNT(mp) == 1) {
12817 				if (ip_copyin_msfilter(q, mp) == 0)
12818 					return;
12819 			}
12820 			/*
12821 			 * Refhold the conn, till the ioctl completes. This is
12822 			 * needed in case the ioctl ends up in the pending mp
12823 			 * list. Every mp in the ipx_pending_mp list must have
12824 			 * a refhold on the conn to resume processing. The
12825 			 * refhold is released when the ioctl completes
12826 			 * (whether normally or abnormally). An ioctlref is also
12827 			 * placed on the conn to prevent TCP from removing the
12828 			 * queue needed to send the ioctl reply back.
12829 			 * In all cases ip_ioctl_finish is called to finish
12830 			 * the ioctl and release the refholds.
12831 			 */
12832 			if (connp != NULL) {
12833 				/* This is not a reentry */
12834 				CONN_INC_REF(connp);
12835 				CONN_INC_IOCTLREF(connp);
12836 			} else {
12837 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12838 					mi_copy_done(q, mp, EINVAL);
12839 					return;
12840 				}
12841 			}
12842 
12843 			ip_process_ioctl(NULL, q, mp, ipip);
12844 
12845 		} else {
12846 			mi_copyout(q, mp);
12847 		}
12848 		return;
12849 
12850 	case M_IOCNAK:
12851 		/*
12852 		 * The only way we could get here is if a resolver didn't like
12853 		 * an IOCTL we sent it.	 This shouldn't happen.
12854 		 */
12855 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12856 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12857 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12858 		freemsg(mp);
12859 		return;
12860 	case M_IOCACK:
12861 		/* /dev/ip shouldn't see this */
12862 		goto nak;
12863 	case M_FLUSH:
12864 		if (*mp->b_rptr & FLUSHW)
12865 			flushq(q, FLUSHALL);
12866 		if (q->q_next) {
12867 			putnext(q, mp);
12868 			return;
12869 		}
12870 		if (*mp->b_rptr & FLUSHR) {
12871 			*mp->b_rptr &= ~FLUSHW;
12872 			qreply(q, mp);
12873 			return;
12874 		}
12875 		freemsg(mp);
12876 		return;
12877 	case M_CTL:
12878 		break;
12879 	case M_PROTO:
12880 	case M_PCPROTO:
12881 		/*
12882 		 * The only PROTO messages we expect are SNMP-related.
12883 		 */
12884 		switch (((union T_primitives *)mp->b_rptr)->type) {
12885 		case T_SVR4_OPTMGMT_REQ:
12886 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12887 			    "flags %x\n",
12888 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12889 
12890 			if (connp == NULL) {
12891 				proto_str = "T_SVR4_OPTMGMT_REQ";
12892 				goto protonak;
12893 			}
12894 
12895 			/*
12896 			 * All Solaris components should pass a db_credp
12897 			 * for this TPI message, hence we ASSERT.
12898 			 * But in case there is some other M_PROTO that looks
12899 			 * like a TPI message sent by some other kernel
12900 			 * component, we check and return an error.
12901 			 */
12902 			cr = msg_getcred(mp, NULL);
12903 			ASSERT(cr != NULL);
12904 			if (cr == NULL) {
12905 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12906 				if (mp != NULL)
12907 					qreply(q, mp);
12908 				return;
12909 			}
12910 
12911 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12912 				proto_str = "Bad SNMPCOM request?";
12913 				goto protonak;
12914 			}
12915 			return;
12916 		default:
12917 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12918 			    (int)*(uint_t *)mp->b_rptr));
12919 			freemsg(mp);
12920 			return;
12921 		}
12922 	default:
12923 		break;
12924 	}
12925 	if (q->q_next) {
12926 		putnext(q, mp);
12927 	} else
12928 		freemsg(mp);
12929 	return;
12930 
12931 nak:
12932 	iocp->ioc_error = EINVAL;
12933 	mp->b_datap->db_type = M_IOCNAK;
12934 	iocp->ioc_count = 0;
12935 	qreply(q, mp);
12936 	return;
12937 
12938 protonak:
12939 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12940 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12941 		qreply(q, mp);
12942 }
12943 
12944 /*
12945  * Process IP options in an outbound packet.  Verify that the nexthop in a
12946  * strict source route is onlink.
12947  * Returns non-zero if something fails in which case an ICMP error has been
12948  * sent and mp freed.
12949  *
12950  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12951  */
12952 int
12953 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12954 {
12955 	ipoptp_t	opts;
12956 	uchar_t		*opt;
12957 	uint8_t		optval;
12958 	uint8_t		optlen;
12959 	ipaddr_t	dst;
12960 	intptr_t	code = 0;
12961 	ire_t		*ire;
12962 	ip_stack_t	*ipst = ixa->ixa_ipst;
12963 	ip_recv_attr_t	iras;
12964 
12965 	ip2dbg(("ip_output_options\n"));
12966 
12967 	dst = ipha->ipha_dst;
12968 	for (optval = ipoptp_first(&opts, ipha);
12969 	    optval != IPOPT_EOL;
12970 	    optval = ipoptp_next(&opts)) {
12971 		opt = opts.ipoptp_cur;
12972 		optlen = opts.ipoptp_len;
12973 		ip2dbg(("ip_output_options: opt %d, len %d\n",
12974 		    optval, optlen));
12975 		switch (optval) {
12976 			uint32_t off;
12977 		case IPOPT_SSRR:
12978 		case IPOPT_LSRR:
12979 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12980 				ip1dbg((
12981 				    "ip_output_options: bad option offset\n"));
12982 				code = (char *)&opt[IPOPT_OLEN] -
12983 				    (char *)ipha;
12984 				goto param_prob;
12985 			}
12986 			off = opt[IPOPT_OFFSET];
12987 			ip1dbg(("ip_output_options: next hop 0x%x\n",
12988 			    ntohl(dst)));
12989 			/*
12990 			 * For strict: verify that dst is directly
12991 			 * reachable.
12992 			 */
12993 			if (optval == IPOPT_SSRR) {
12994 				ire = ire_ftable_lookup_v4(dst, 0, 0,
12995 				    IRE_INTERFACE, NULL, ALL_ZONES,
12996 				    ixa->ixa_tsl,
12997 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
12998 				    NULL);
12999 				if (ire == NULL) {
13000 					ip1dbg(("ip_output_options: SSRR not"
13001 					    " directly reachable: 0x%x\n",
13002 					    ntohl(dst)));
13003 					goto bad_src_route;
13004 				}
13005 				ire_refrele(ire);
13006 			}
13007 			break;
13008 		case IPOPT_RR:
13009 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13010 				ip1dbg((
13011 				    "ip_output_options: bad option offset\n"));
13012 				code = (char *)&opt[IPOPT_OLEN] -
13013 				    (char *)ipha;
13014 				goto param_prob;
13015 			}
13016 			break;
13017 		case IPOPT_TS:
13018 			/*
13019 			 * Verify that length >=5 and that there is either
13020 			 * room for another timestamp or that the overflow
13021 			 * counter is not maxed out.
13022 			 */
13023 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
13024 			if (optlen < IPOPT_MINLEN_IT) {
13025 				goto param_prob;
13026 			}
13027 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13028 				ip1dbg((
13029 				    "ip_output_options: bad option offset\n"));
13030 				code = (char *)&opt[IPOPT_OFFSET] -
13031 				    (char *)ipha;
13032 				goto param_prob;
13033 			}
13034 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
13035 			case IPOPT_TS_TSONLY:
13036 				off = IPOPT_TS_TIMELEN;
13037 				break;
13038 			case IPOPT_TS_TSANDADDR:
13039 			case IPOPT_TS_PRESPEC:
13040 			case IPOPT_TS_PRESPEC_RFC791:
13041 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
13042 				break;
13043 			default:
13044 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
13045 				    (char *)ipha;
13046 				goto param_prob;
13047 			}
13048 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
13049 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
13050 				/*
13051 				 * No room and the overflow counter is 15
13052 				 * already.
13053 				 */
13054 				goto param_prob;
13055 			}
13056 			break;
13057 		}
13058 	}
13059 
13060 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
13061 		return (0);
13062 
13063 	ip1dbg(("ip_output_options: error processing IP options."));
13064 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
13065 
13066 param_prob:
13067 	bzero(&iras, sizeof (iras));
13068 	iras.ira_ill = iras.ira_rill = ill;
13069 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13070 	iras.ira_rifindex = iras.ira_ruifindex;
13071 	iras.ira_flags = IRAF_IS_IPV4;
13072 
13073 	ip_drop_output("ip_output_options", mp, ill);
13074 	icmp_param_problem(mp, (uint8_t)code, &iras);
13075 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13076 	return (-1);
13077 
13078 bad_src_route:
13079 	bzero(&iras, sizeof (iras));
13080 	iras.ira_ill = iras.ira_rill = ill;
13081 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13082 	iras.ira_rifindex = iras.ira_ruifindex;
13083 	iras.ira_flags = IRAF_IS_IPV4;
13084 
13085 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13086 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13087 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13088 	return (-1);
13089 }
13090 
13091 /*
13092  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13093  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13094  * thru /etc/system.
13095  */
13096 #define	CONN_MAXDRAINCNT	64
13097 
13098 static void
13099 conn_drain_init(ip_stack_t *ipst)
13100 {
13101 	int i, j;
13102 	idl_tx_list_t *itl_tx;
13103 
13104 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13105 
13106 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
13107 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13108 		/*
13109 		 * Default value of the number of drainers is the
13110 		 * number of cpus, subject to maximum of 8 drainers.
13111 		 */
13112 		if (boot_max_ncpus != -1)
13113 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13114 		else
13115 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13116 	}
13117 
13118 	ipst->ips_idl_tx_list =
13119 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13120 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13121 		itl_tx =  &ipst->ips_idl_tx_list[i];
13122 		itl_tx->txl_drain_list =
13123 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13124 		    sizeof (idl_t), KM_SLEEP);
13125 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13126 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13127 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13128 			    MUTEX_DEFAULT, NULL);
13129 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13130 		}
13131 	}
13132 }
13133 
13134 static void
13135 conn_drain_fini(ip_stack_t *ipst)
13136 {
13137 	int i;
13138 	idl_tx_list_t *itl_tx;
13139 
13140 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13141 		itl_tx =  &ipst->ips_idl_tx_list[i];
13142 		kmem_free(itl_tx->txl_drain_list,
13143 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13144 	}
13145 	kmem_free(ipst->ips_idl_tx_list,
13146 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13147 	ipst->ips_idl_tx_list = NULL;
13148 }
13149 
13150 /*
13151  * Flow control has blocked us from proceeding.  Insert the given conn in one
13152  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13153  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13154  * will call conn_walk_drain().  See the flow control notes at the top of this
13155  * file for more details.
13156  */
13157 void
13158 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13159 {
13160 	idl_t	*idl = tx_list->txl_drain_list;
13161 	uint_t	index;
13162 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13163 
13164 	mutex_enter(&connp->conn_lock);
13165 	if (connp->conn_state_flags & CONN_CLOSING) {
13166 		/*
13167 		 * The conn is closing as a result of which CONN_CLOSING
13168 		 * is set. Return.
13169 		 */
13170 		mutex_exit(&connp->conn_lock);
13171 		return;
13172 	} else if (connp->conn_idl == NULL) {
13173 		/*
13174 		 * Assign the next drain list round robin. We dont' use
13175 		 * a lock, and thus it may not be strictly round robin.
13176 		 * Atomicity of load/stores is enough to make sure that
13177 		 * conn_drain_list_index is always within bounds.
13178 		 */
13179 		index = tx_list->txl_drain_index;
13180 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13181 		connp->conn_idl = &tx_list->txl_drain_list[index];
13182 		index++;
13183 		if (index == ipst->ips_conn_drain_list_cnt)
13184 			index = 0;
13185 		tx_list->txl_drain_index = index;
13186 	} else {
13187 		ASSERT(connp->conn_idl->idl_itl == tx_list);
13188 	}
13189 	mutex_exit(&connp->conn_lock);
13190 
13191 	idl = connp->conn_idl;
13192 	mutex_enter(&idl->idl_lock);
13193 	if ((connp->conn_drain_prev != NULL) ||
13194 	    (connp->conn_state_flags & CONN_CLOSING)) {
13195 		/*
13196 		 * The conn is either already in the drain list or closing.
13197 		 * (We needed to check for CONN_CLOSING again since close can
13198 		 * sneak in between dropping conn_lock and acquiring idl_lock.)
13199 		 */
13200 		mutex_exit(&idl->idl_lock);
13201 		return;
13202 	}
13203 
13204 	/*
13205 	 * The conn is not in the drain list. Insert it at the
13206 	 * tail of the drain list. The drain list is circular
13207 	 * and doubly linked. idl_conn points to the 1st element
13208 	 * in the list.
13209 	 */
13210 	if (idl->idl_conn == NULL) {
13211 		idl->idl_conn = connp;
13212 		connp->conn_drain_next = connp;
13213 		connp->conn_drain_prev = connp;
13214 	} else {
13215 		conn_t *head = idl->idl_conn;
13216 
13217 		connp->conn_drain_next = head;
13218 		connp->conn_drain_prev = head->conn_drain_prev;
13219 		head->conn_drain_prev->conn_drain_next = connp;
13220 		head->conn_drain_prev = connp;
13221 	}
13222 	/*
13223 	 * For non streams based sockets assert flow control.
13224 	 */
13225 	conn_setqfull(connp, NULL);
13226 	mutex_exit(&idl->idl_lock);
13227 }
13228 
13229 static void
13230 conn_drain_remove(conn_t *connp)
13231 {
13232 	idl_t *idl = connp->conn_idl;
13233 
13234 	if (idl != NULL) {
13235 		/*
13236 		 * Remove ourself from the drain list.
13237 		 */
13238 		if (connp->conn_drain_next == connp) {
13239 			/* Singleton in the list */
13240 			ASSERT(connp->conn_drain_prev == connp);
13241 			idl->idl_conn = NULL;
13242 		} else {
13243 			connp->conn_drain_prev->conn_drain_next =
13244 			    connp->conn_drain_next;
13245 			connp->conn_drain_next->conn_drain_prev =
13246 			    connp->conn_drain_prev;
13247 			if (idl->idl_conn == connp)
13248 				idl->idl_conn = connp->conn_drain_next;
13249 		}
13250 
13251 		/*
13252 		 * NOTE: because conn_idl is associated with a specific drain
13253 		 * list which in turn is tied to the index the TX ring
13254 		 * (txl_cookie) hashes to, and because the TX ring can change
13255 		 * over the lifetime of the conn_t, we must clear conn_idl so
13256 		 * a subsequent conn_drain_insert() will set conn_idl again
13257 		 * based on the latest txl_cookie.
13258 		 */
13259 		connp->conn_idl = NULL;
13260 	}
13261 	connp->conn_drain_next = NULL;
13262 	connp->conn_drain_prev = NULL;
13263 
13264 	conn_clrqfull(connp, NULL);
13265 	/*
13266 	 * For streams based sockets open up flow control.
13267 	 */
13268 	if (!IPCL_IS_NONSTR(connp))
13269 		enableok(connp->conn_wq);
13270 }
13271 
13272 /*
13273  * This conn is closing, and we are called from ip_close. OR
13274  * this conn is draining because flow-control on the ill has been relieved.
13275  *
13276  * We must also need to remove conn's on this idl from the list, and also
13277  * inform the sockfs upcalls about the change in flow-control.
13278  */
13279 static void
13280 conn_drain(conn_t *connp, boolean_t closing)
13281 {
13282 	idl_t *idl;
13283 	conn_t *next_connp;
13284 
13285 	/*
13286 	 * connp->conn_idl is stable at this point, and no lock is needed
13287 	 * to check it. If we are called from ip_close, close has already
13288 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13289 	 * called us only because conn_idl is non-null. If we are called thru
13290 	 * service, conn_idl could be null, but it cannot change because
13291 	 * service is single-threaded per queue, and there cannot be another
13292 	 * instance of service trying to call conn_drain_insert on this conn
13293 	 * now.
13294 	 */
13295 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13296 
13297 	/*
13298 	 * If the conn doesn't exist or is not on a drain list, bail.
13299 	 */
13300 	if (connp == NULL || connp->conn_idl == NULL ||
13301 	    connp->conn_drain_prev == NULL) {
13302 		return;
13303 	}
13304 
13305 	idl = connp->conn_idl;
13306 	ASSERT(MUTEX_HELD(&idl->idl_lock));
13307 
13308 	if (!closing) {
13309 		next_connp = connp->conn_drain_next;
13310 		while (next_connp != connp) {
13311 			conn_t *delconnp = next_connp;
13312 
13313 			next_connp = next_connp->conn_drain_next;
13314 			conn_drain_remove(delconnp);
13315 		}
13316 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13317 	}
13318 	conn_drain_remove(connp);
13319 }
13320 
13321 /*
13322  * Write service routine. Shared perimeter entry point.
13323  * The device queue's messages has fallen below the low water mark and STREAMS
13324  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13325  * each waiting conn.
13326  */
13327 void
13328 ip_wsrv(queue_t *q)
13329 {
13330 	ill_t	*ill;
13331 
13332 	ill = (ill_t *)q->q_ptr;
13333 	if (ill->ill_state_flags == 0) {
13334 		ip_stack_t *ipst = ill->ill_ipst;
13335 
13336 		/*
13337 		 * The device flow control has opened up.
13338 		 * Walk through conn drain lists and qenable the
13339 		 * first conn in each list. This makes sense only
13340 		 * if the stream is fully plumbed and setup.
13341 		 * Hence the ill_state_flags check above.
13342 		 */
13343 		ip1dbg(("ip_wsrv: walking\n"));
13344 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13345 		enableok(ill->ill_wq);
13346 	}
13347 }
13348 
13349 /*
13350  * Callback to disable flow control in IP.
13351  *
13352  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13353  * is enabled.
13354  *
13355  * When MAC_TX() is not able to send any more packets, dld sets its queue
13356  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13357  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13358  * function and wakes up corresponding mac worker threads, which in turn
13359  * calls this callback function, and disables flow control.
13360  */
13361 void
13362 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13363 {
13364 	ill_t *ill = (ill_t *)arg;
13365 	ip_stack_t *ipst = ill->ill_ipst;
13366 	idl_tx_list_t *idl_txl;
13367 
13368 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13369 	mutex_enter(&idl_txl->txl_lock);
13370 	/* add code to to set a flag to indicate idl_txl is enabled */
13371 	conn_walk_drain(ipst, idl_txl);
13372 	mutex_exit(&idl_txl->txl_lock);
13373 }
13374 
13375 /*
13376  * Flow control has been relieved and STREAMS has backenabled us; drain
13377  * all the conn lists on `tx_list'.
13378  */
13379 static void
13380 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13381 {
13382 	int i;
13383 	idl_t *idl;
13384 
13385 	IP_STAT(ipst, ip_conn_walk_drain);
13386 
13387 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13388 		idl = &tx_list->txl_drain_list[i];
13389 		mutex_enter(&idl->idl_lock);
13390 		conn_drain(idl->idl_conn, B_FALSE);
13391 		mutex_exit(&idl->idl_lock);
13392 	}
13393 }
13394 
13395 /*
13396  * Determine if the ill and multicast aspects of that packets
13397  * "matches" the conn.
13398  */
13399 boolean_t
13400 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13401 {
13402 	ill_t		*ill = ira->ira_rill;
13403 	zoneid_t	zoneid = ira->ira_zoneid;
13404 	uint_t		in_ifindex;
13405 	ipaddr_t	dst, src;
13406 
13407 	dst = ipha->ipha_dst;
13408 	src = ipha->ipha_src;
13409 
13410 	/*
13411 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13412 	 * unicast, broadcast and multicast reception to
13413 	 * conn_incoming_ifindex.
13414 	 * conn_wantpacket is called for unicast, broadcast and
13415 	 * multicast packets.
13416 	 */
13417 	in_ifindex = connp->conn_incoming_ifindex;
13418 
13419 	/* mpathd can bind to the under IPMP interface, which we allow */
13420 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13421 		if (!IS_UNDER_IPMP(ill))
13422 			return (B_FALSE);
13423 
13424 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13425 			return (B_FALSE);
13426 	}
13427 
13428 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13429 		return (B_FALSE);
13430 
13431 	if (!(ira->ira_flags & IRAF_MULTICAST))
13432 		return (B_TRUE);
13433 
13434 	if (connp->conn_multi_router) {
13435 		/* multicast packet and multicast router socket: send up */
13436 		return (B_TRUE);
13437 	}
13438 
13439 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13440 	    ipha->ipha_protocol == IPPROTO_RSVP)
13441 		return (B_TRUE);
13442 
13443 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13444 }
13445 
13446 void
13447 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13448 {
13449 	if (IPCL_IS_NONSTR(connp)) {
13450 		(*connp->conn_upcalls->su_txq_full)
13451 		    (connp->conn_upper_handle, B_TRUE);
13452 		if (flow_stopped != NULL)
13453 			*flow_stopped = B_TRUE;
13454 	} else {
13455 		queue_t *q = connp->conn_wq;
13456 
13457 		ASSERT(q != NULL);
13458 		if (!(q->q_flag & QFULL)) {
13459 			mutex_enter(QLOCK(q));
13460 			if (!(q->q_flag & QFULL)) {
13461 				/* still need to set QFULL */
13462 				q->q_flag |= QFULL;
13463 				/* set flow_stopped to true under QLOCK */
13464 				if (flow_stopped != NULL)
13465 					*flow_stopped = B_TRUE;
13466 				mutex_exit(QLOCK(q));
13467 			} else {
13468 				/* flow_stopped is left unchanged */
13469 				mutex_exit(QLOCK(q));
13470 			}
13471 		}
13472 	}
13473 }
13474 
13475 void
13476 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13477 {
13478 	if (IPCL_IS_NONSTR(connp)) {
13479 		(*connp->conn_upcalls->su_txq_full)
13480 		    (connp->conn_upper_handle, B_FALSE);
13481 		if (flow_stopped != NULL)
13482 			*flow_stopped = B_FALSE;
13483 	} else {
13484 		queue_t *q = connp->conn_wq;
13485 
13486 		ASSERT(q != NULL);
13487 		if (q->q_flag & QFULL) {
13488 			mutex_enter(QLOCK(q));
13489 			if (q->q_flag & QFULL) {
13490 				q->q_flag &= ~QFULL;
13491 				/* set flow_stopped to false under QLOCK */
13492 				if (flow_stopped != NULL)
13493 					*flow_stopped = B_FALSE;
13494 				mutex_exit(QLOCK(q));
13495 				if (q->q_flag & QWANTW)
13496 					qbackenable(q, 0);
13497 			} else {
13498 				/* flow_stopped is left unchanged */
13499 				mutex_exit(QLOCK(q));
13500 			}
13501 		}
13502 	}
13503 
13504 	mutex_enter(&connp->conn_lock);
13505 	connp->conn_blocked = B_FALSE;
13506 	mutex_exit(&connp->conn_lock);
13507 }
13508 
13509 /*
13510  * Return the length in bytes of the IPv4 headers (base header, label, and
13511  * other IP options) that will be needed based on the
13512  * ip_pkt_t structure passed by the caller.
13513  *
13514  * The returned length does not include the length of the upper level
13515  * protocol (ULP) header.
13516  * The caller needs to check that the length doesn't exceed the max for IPv4.
13517  */
13518 int
13519 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13520 {
13521 	int len;
13522 
13523 	len = IP_SIMPLE_HDR_LENGTH;
13524 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13525 		ASSERT(ipp->ipp_label_len_v4 != 0);
13526 		/* We need to round up here */
13527 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13528 	}
13529 
13530 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13531 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13532 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13533 		len += ipp->ipp_ipv4_options_len;
13534 	}
13535 	return (len);
13536 }
13537 
13538 /*
13539  * All-purpose routine to build an IPv4 header with options based
13540  * on the abstract ip_pkt_t.
13541  *
13542  * The caller has to set the source and destination address as well as
13543  * ipha_length. The caller has to massage any source route and compensate
13544  * for the ULP pseudo-header checksum due to the source route.
13545  */
13546 void
13547 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13548     uint8_t protocol)
13549 {
13550 	ipha_t	*ipha = (ipha_t *)buf;
13551 	uint8_t *cp;
13552 
13553 	/* Initialize IPv4 header */
13554 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13555 	ipha->ipha_length = 0;	/* Caller will set later */
13556 	ipha->ipha_ident = 0;
13557 	ipha->ipha_fragment_offset_and_flags = 0;
13558 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13559 	ipha->ipha_protocol = protocol;
13560 	ipha->ipha_hdr_checksum = 0;
13561 
13562 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13563 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13564 		ipha->ipha_src = ipp->ipp_addr_v4;
13565 
13566 	cp = (uint8_t *)&ipha[1];
13567 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13568 		ASSERT(ipp->ipp_label_len_v4 != 0);
13569 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13570 		cp += ipp->ipp_label_len_v4;
13571 		/* We need to round up here */
13572 		while ((uintptr_t)cp & 0x3) {
13573 			*cp++ = IPOPT_NOP;
13574 		}
13575 	}
13576 
13577 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13578 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13579 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13580 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13581 		cp += ipp->ipp_ipv4_options_len;
13582 	}
13583 	ipha->ipha_version_and_hdr_length =
13584 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13585 
13586 	ASSERT((int)(cp - buf) == buf_len);
13587 }
13588 
13589 /* Allocate the private structure */
13590 static int
13591 ip_priv_alloc(void **bufp)
13592 {
13593 	void	*buf;
13594 
13595 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13596 		return (ENOMEM);
13597 
13598 	*bufp = buf;
13599 	return (0);
13600 }
13601 
13602 /* Function to delete the private structure */
13603 void
13604 ip_priv_free(void *buf)
13605 {
13606 	ASSERT(buf != NULL);
13607 	kmem_free(buf, sizeof (ip_priv_t));
13608 }
13609 
13610 /*
13611  * The entry point for IPPF processing.
13612  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13613  * routine just returns.
13614  *
13615  * When called, ip_process generates an ipp_packet_t structure
13616  * which holds the state information for this packet and invokes the
13617  * the classifier (via ipp_packet_process). The classification, depending on
13618  * configured filters, results in a list of actions for this packet. Invoking
13619  * an action may cause the packet to be dropped, in which case we return NULL.
13620  * proc indicates the callout position for
13621  * this packet and ill is the interface this packet arrived on or will leave
13622  * on (inbound and outbound resp.).
13623  *
13624  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13625  * on the ill corrsponding to the destination IP address.
13626  */
13627 mblk_t *
13628 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13629 {
13630 	ip_priv_t	*priv;
13631 	ipp_action_id_t	aid;
13632 	int		rc = 0;
13633 	ipp_packet_t	*pp;
13634 
13635 	/* If the classifier is not loaded, return  */
13636 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13637 		return (mp);
13638 	}
13639 
13640 	ASSERT(mp != NULL);
13641 
13642 	/* Allocate the packet structure */
13643 	rc = ipp_packet_alloc(&pp, "ip", aid);
13644 	if (rc != 0)
13645 		goto drop;
13646 
13647 	/* Allocate the private structure */
13648 	rc = ip_priv_alloc((void **)&priv);
13649 	if (rc != 0) {
13650 		ipp_packet_free(pp);
13651 		goto drop;
13652 	}
13653 	priv->proc = proc;
13654 	priv->ill_index = ill_get_upper_ifindex(rill);
13655 
13656 	ipp_packet_set_private(pp, priv, ip_priv_free);
13657 	ipp_packet_set_data(pp, mp);
13658 
13659 	/* Invoke the classifier */
13660 	rc = ipp_packet_process(&pp);
13661 	if (pp != NULL) {
13662 		mp = ipp_packet_get_data(pp);
13663 		ipp_packet_free(pp);
13664 		if (rc != 0)
13665 			goto drop;
13666 		return (mp);
13667 	} else {
13668 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13669 		mp = NULL;
13670 	}
13671 drop:
13672 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13673 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13674 		ip_drop_input("ip_process", mp, ill);
13675 	} else {
13676 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13677 		ip_drop_output("ip_process", mp, ill);
13678 	}
13679 	freemsg(mp);
13680 	return (NULL);
13681 }
13682 
13683 /*
13684  * Propagate a multicast group membership operation (add/drop) on
13685  * all the interfaces crossed by the related multirt routes.
13686  * The call is considered successful if the operation succeeds
13687  * on at least one interface.
13688  *
13689  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13690  * multicast addresses with the ire argument being the first one.
13691  * We walk the bucket to find all the of those.
13692  *
13693  * Common to IPv4 and IPv6.
13694  */
13695 static int
13696 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13697     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13698     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13699     mcast_record_t fmode, const in6_addr_t *v6src)
13700 {
13701 	ire_t		*ire_gw;
13702 	irb_t		*irb;
13703 	int		ifindex;
13704 	int		error = 0;
13705 	int		result;
13706 	ip_stack_t	*ipst = ire->ire_ipst;
13707 	ipaddr_t	group;
13708 	boolean_t	isv6;
13709 	int		match_flags;
13710 
13711 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13712 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13713 		isv6 = B_FALSE;
13714 	} else {
13715 		isv6 = B_TRUE;
13716 	}
13717 
13718 	irb = ire->ire_bucket;
13719 	ASSERT(irb != NULL);
13720 
13721 	result = 0;
13722 	irb_refhold(irb);
13723 	for (; ire != NULL; ire = ire->ire_next) {
13724 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13725 			continue;
13726 
13727 		/* We handle -ifp routes by matching on the ill if set */
13728 		match_flags = MATCH_IRE_TYPE;
13729 		if (ire->ire_ill != NULL)
13730 			match_flags |= MATCH_IRE_ILL;
13731 
13732 		if (isv6) {
13733 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13734 				continue;
13735 
13736 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13737 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13738 			    match_flags, 0, ipst, NULL);
13739 		} else {
13740 			if (ire->ire_addr != group)
13741 				continue;
13742 
13743 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13744 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13745 			    match_flags, 0, ipst, NULL);
13746 		}
13747 		/* No interface route exists for the gateway; skip this ire. */
13748 		if (ire_gw == NULL)
13749 			continue;
13750 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13751 			ire_refrele(ire_gw);
13752 			continue;
13753 		}
13754 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13755 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13756 
13757 		/*
13758 		 * The operation is considered a success if
13759 		 * it succeeds at least once on any one interface.
13760 		 */
13761 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13762 		    fmode, v6src);
13763 		if (error == 0)
13764 			result = CGTP_MCAST_SUCCESS;
13765 
13766 		ire_refrele(ire_gw);
13767 	}
13768 	irb_refrele(irb);
13769 	/*
13770 	 * Consider the call as successful if we succeeded on at least
13771 	 * one interface. Otherwise, return the last encountered error.
13772 	 */
13773 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13774 }
13775 
13776 /*
13777  * Return the expected CGTP hooks version number.
13778  */
13779 int
13780 ip_cgtp_filter_supported(void)
13781 {
13782 	return (ip_cgtp_filter_rev);
13783 }
13784 
13785 /*
13786  * CGTP hooks can be registered by invoking this function.
13787  * Checks that the version number matches.
13788  */
13789 int
13790 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13791 {
13792 	netstack_t *ns;
13793 	ip_stack_t *ipst;
13794 
13795 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13796 		return (ENOTSUP);
13797 
13798 	ns = netstack_find_by_stackid(stackid);
13799 	if (ns == NULL)
13800 		return (EINVAL);
13801 	ipst = ns->netstack_ip;
13802 	ASSERT(ipst != NULL);
13803 
13804 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13805 		netstack_rele(ns);
13806 		return (EALREADY);
13807 	}
13808 
13809 	ipst->ips_ip_cgtp_filter_ops = ops;
13810 
13811 	ill_set_inputfn_all(ipst);
13812 
13813 	netstack_rele(ns);
13814 	return (0);
13815 }
13816 
13817 /*
13818  * CGTP hooks can be unregistered by invoking this function.
13819  * Returns ENXIO if there was no registration.
13820  * Returns EBUSY if the ndd variable has not been turned off.
13821  */
13822 int
13823 ip_cgtp_filter_unregister(netstackid_t stackid)
13824 {
13825 	netstack_t *ns;
13826 	ip_stack_t *ipst;
13827 
13828 	ns = netstack_find_by_stackid(stackid);
13829 	if (ns == NULL)
13830 		return (EINVAL);
13831 	ipst = ns->netstack_ip;
13832 	ASSERT(ipst != NULL);
13833 
13834 	if (ipst->ips_ip_cgtp_filter) {
13835 		netstack_rele(ns);
13836 		return (EBUSY);
13837 	}
13838 
13839 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13840 		netstack_rele(ns);
13841 		return (ENXIO);
13842 	}
13843 	ipst->ips_ip_cgtp_filter_ops = NULL;
13844 
13845 	ill_set_inputfn_all(ipst);
13846 
13847 	netstack_rele(ns);
13848 	return (0);
13849 }
13850 
13851 /*
13852  * Check whether there is a CGTP filter registration.
13853  * Returns non-zero if there is a registration, otherwise returns zero.
13854  * Note: returns zero if bad stackid.
13855  */
13856 int
13857 ip_cgtp_filter_is_registered(netstackid_t stackid)
13858 {
13859 	netstack_t *ns;
13860 	ip_stack_t *ipst;
13861 	int ret;
13862 
13863 	ns = netstack_find_by_stackid(stackid);
13864 	if (ns == NULL)
13865 		return (0);
13866 	ipst = ns->netstack_ip;
13867 	ASSERT(ipst != NULL);
13868 
13869 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
13870 		ret = 1;
13871 	else
13872 		ret = 0;
13873 
13874 	netstack_rele(ns);
13875 	return (ret);
13876 }
13877 
13878 static int
13879 ip_squeue_switch(int val)
13880 {
13881 	int rval;
13882 
13883 	switch (val) {
13884 	case IP_SQUEUE_ENTER_NODRAIN:
13885 		rval = SQ_NODRAIN;
13886 		break;
13887 	case IP_SQUEUE_ENTER:
13888 		rval = SQ_PROCESS;
13889 		break;
13890 	case IP_SQUEUE_FILL:
13891 	default:
13892 		rval = SQ_FILL;
13893 		break;
13894 	}
13895 	return (rval);
13896 }
13897 
13898 static void *
13899 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13900 {
13901 	kstat_t *ksp;
13902 
13903 	ip_stat_t template = {
13904 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
13905 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
13906 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
13907 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
13908 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
13909 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
13910 		{ "ip_opt",			KSTAT_DATA_UINT64 },
13911 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
13912 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
13913 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
13914 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
13915 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
13916 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
13917 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
13918 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
13919 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
13920 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13921 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
13922 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13923 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13924 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13925 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
13926 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13927 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13928 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
13929 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
13930 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
13931 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
13932 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
13933 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
13934 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
13935 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
13936 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
13937 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
13938 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
13939 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
13940 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
13941 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
13942 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
13943 	};
13944 
13945 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13946 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13947 	    KSTAT_FLAG_VIRTUAL, stackid);
13948 
13949 	if (ksp == NULL)
13950 		return (NULL);
13951 
13952 	bcopy(&template, ip_statisticsp, sizeof (template));
13953 	ksp->ks_data = (void *)ip_statisticsp;
13954 	ksp->ks_private = (void *)(uintptr_t)stackid;
13955 
13956 	kstat_install(ksp);
13957 	return (ksp);
13958 }
13959 
13960 static void
13961 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13962 {
13963 	if (ksp != NULL) {
13964 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13965 		kstat_delete_netstack(ksp, stackid);
13966 	}
13967 }
13968 
13969 static void *
13970 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13971 {
13972 	kstat_t	*ksp;
13973 
13974 	ip_named_kstat_t template = {
13975 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
13976 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
13977 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
13978 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
13979 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
13980 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
13981 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
13982 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
13983 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
13984 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
13985 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
13986 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
13987 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
13988 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
13989 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
13990 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
13991 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
13992 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
13993 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
13994 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
13995 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
13996 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
13997 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
13998 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
13999 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
14000 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
14001 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
14002 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
14003 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
14004 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
14005 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
14006 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
14007 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
14008 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
14009 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
14010 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
14011 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
14012 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
14013 	};
14014 
14015 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
14016 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
14017 	if (ksp == NULL || ksp->ks_data == NULL)
14018 		return (NULL);
14019 
14020 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
14021 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
14022 	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
14023 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
14024 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
14025 
14026 	template.netToMediaEntrySize.value.i32 =
14027 	    sizeof (mib2_ipNetToMediaEntry_t);
14028 
14029 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
14030 
14031 	bcopy(&template, ksp->ks_data, sizeof (template));
14032 	ksp->ks_update = ip_kstat_update;
14033 	ksp->ks_private = (void *)(uintptr_t)stackid;
14034 
14035 	kstat_install(ksp);
14036 	return (ksp);
14037 }
14038 
14039 static void
14040 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14041 {
14042 	if (ksp != NULL) {
14043 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14044 		kstat_delete_netstack(ksp, stackid);
14045 	}
14046 }
14047 
14048 static int
14049 ip_kstat_update(kstat_t *kp, int rw)
14050 {
14051 	ip_named_kstat_t *ipkp;
14052 	mib2_ipIfStatsEntry_t ipmib;
14053 	ill_walk_context_t ctx;
14054 	ill_t *ill;
14055 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14056 	netstack_t	*ns;
14057 	ip_stack_t	*ipst;
14058 
14059 	if (kp == NULL || kp->ks_data == NULL)
14060 		return (EIO);
14061 
14062 	if (rw == KSTAT_WRITE)
14063 		return (EACCES);
14064 
14065 	ns = netstack_find_by_stackid(stackid);
14066 	if (ns == NULL)
14067 		return (-1);
14068 	ipst = ns->netstack_ip;
14069 	if (ipst == NULL) {
14070 		netstack_rele(ns);
14071 		return (-1);
14072 	}
14073 	ipkp = (ip_named_kstat_t *)kp->ks_data;
14074 
14075 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14076 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14077 	ill = ILL_START_WALK_V4(&ctx, ipst);
14078 	for (; ill != NULL; ill = ill_next(&ctx, ill))
14079 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14080 	rw_exit(&ipst->ips_ill_g_lock);
14081 
14082 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
14083 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
14084 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
14085 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
14086 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
14087 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14088 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
14089 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
14090 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
14091 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
14092 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
14093 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
14094 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
14095 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
14096 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
14097 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
14098 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
14099 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
14100 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
14101 
14102 	ipkp->routingDiscards.value.ui32 =	0;
14103 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
14104 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
14105 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
14106 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
14107 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
14108 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
14109 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
14110 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
14111 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
14112 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
14113 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
14114 
14115 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
14116 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
14117 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14118 
14119 	netstack_rele(ns);
14120 
14121 	return (0);
14122 }
14123 
14124 static void *
14125 icmp_kstat_init(netstackid_t stackid)
14126 {
14127 	kstat_t	*ksp;
14128 
14129 	icmp_named_kstat_t template = {
14130 		{ "inMsgs",		KSTAT_DATA_UINT32 },
14131 		{ "inErrors",		KSTAT_DATA_UINT32 },
14132 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
14133 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
14134 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
14135 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
14136 		{ "inRedirects",	KSTAT_DATA_UINT32 },
14137 		{ "inEchos",		KSTAT_DATA_UINT32 },
14138 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14139 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14140 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14141 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14142 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14143 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14144 		{ "outErrors",		KSTAT_DATA_UINT32 },
14145 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14146 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14147 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14148 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14149 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14150 		{ "outEchos",		KSTAT_DATA_UINT32 },
14151 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14152 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14153 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14154 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14155 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14156 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14157 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14158 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14159 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14160 		{ "outDrops",		KSTAT_DATA_UINT32 },
14161 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14162 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14163 	};
14164 
14165 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14166 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14167 	if (ksp == NULL || ksp->ks_data == NULL)
14168 		return (NULL);
14169 
14170 	bcopy(&template, ksp->ks_data, sizeof (template));
14171 
14172 	ksp->ks_update = icmp_kstat_update;
14173 	ksp->ks_private = (void *)(uintptr_t)stackid;
14174 
14175 	kstat_install(ksp);
14176 	return (ksp);
14177 }
14178 
14179 static void
14180 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14181 {
14182 	if (ksp != NULL) {
14183 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14184 		kstat_delete_netstack(ksp, stackid);
14185 	}
14186 }
14187 
14188 static int
14189 icmp_kstat_update(kstat_t *kp, int rw)
14190 {
14191 	icmp_named_kstat_t *icmpkp;
14192 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14193 	netstack_t	*ns;
14194 	ip_stack_t	*ipst;
14195 
14196 	if ((kp == NULL) || (kp->ks_data == NULL))
14197 		return (EIO);
14198 
14199 	if (rw == KSTAT_WRITE)
14200 		return (EACCES);
14201 
14202 	ns = netstack_find_by_stackid(stackid);
14203 	if (ns == NULL)
14204 		return (-1);
14205 	ipst = ns->netstack_ip;
14206 	if (ipst == NULL) {
14207 		netstack_rele(ns);
14208 		return (-1);
14209 	}
14210 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14211 
14212 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14213 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14214 	icmpkp->inDestUnreachs.value.ui32 =
14215 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14216 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14217 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14218 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14219 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14220 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14221 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14222 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14223 	icmpkp->inTimestampReps.value.ui32 =
14224 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14225 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14226 	icmpkp->inAddrMaskReps.value.ui32 =
14227 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14228 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14229 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14230 	icmpkp->outDestUnreachs.value.ui32 =
14231 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14232 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14233 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14234 	icmpkp->outSrcQuenchs.value.ui32 =
14235 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14236 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14237 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14238 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14239 	icmpkp->outTimestamps.value.ui32 =
14240 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14241 	icmpkp->outTimestampReps.value.ui32 =
14242 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14243 	icmpkp->outAddrMasks.value.ui32 =
14244 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14245 	icmpkp->outAddrMaskReps.value.ui32 =
14246 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14247 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14248 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14249 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14250 	icmpkp->outFragNeeded.value.ui32 =
14251 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14252 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14253 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14254 	icmpkp->inBadRedirects.value.ui32 =
14255 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14256 
14257 	netstack_rele(ns);
14258 	return (0);
14259 }
14260 
14261 /*
14262  * This is the fanout function for raw socket opened for SCTP.  Note
14263  * that it is called after SCTP checks that there is no socket which
14264  * wants a packet.  Then before SCTP handles this out of the blue packet,
14265  * this function is called to see if there is any raw socket for SCTP.
14266  * If there is and it is bound to the correct address, the packet will
14267  * be sent to that socket.  Note that only one raw socket can be bound to
14268  * a port.  This is assured in ipcl_sctp_hash_insert();
14269  */
14270 void
14271 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14272     ip_recv_attr_t *ira)
14273 {
14274 	conn_t		*connp;
14275 	queue_t		*rq;
14276 	boolean_t	secure;
14277 	ill_t		*ill = ira->ira_ill;
14278 	ip_stack_t	*ipst = ill->ill_ipst;
14279 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14280 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14281 	iaflags_t	iraflags = ira->ira_flags;
14282 	ill_t		*rill = ira->ira_rill;
14283 
14284 	secure = iraflags & IRAF_IPSEC_SECURE;
14285 
14286 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14287 	    ira, ipst);
14288 	if (connp == NULL) {
14289 		/*
14290 		 * Although raw sctp is not summed, OOB chunks must be.
14291 		 * Drop the packet here if the sctp checksum failed.
14292 		 */
14293 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14294 			SCTPS_BUMP_MIB(sctps, sctpChecksumError);
14295 			freemsg(mp);
14296 			return;
14297 		}
14298 		ira->ira_ill = ira->ira_rill = NULL;
14299 		sctp_ootb_input(mp, ira, ipst);
14300 		ira->ira_ill = ill;
14301 		ira->ira_rill = rill;
14302 		return;
14303 	}
14304 	rq = connp->conn_rq;
14305 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14306 		CONN_DEC_REF(connp);
14307 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14308 		freemsg(mp);
14309 		return;
14310 	}
14311 	if (((iraflags & IRAF_IS_IPV4) ?
14312 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14313 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14314 	    secure) {
14315 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14316 		    ip6h, ira);
14317 		if (mp == NULL) {
14318 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14319 			/* Note that mp is NULL */
14320 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14321 			CONN_DEC_REF(connp);
14322 			return;
14323 		}
14324 	}
14325 
14326 	if (iraflags & IRAF_ICMP_ERROR) {
14327 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14328 	} else {
14329 		ill_t *rill = ira->ira_rill;
14330 
14331 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14332 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14333 		ira->ira_ill = ira->ira_rill = NULL;
14334 		(connp->conn_recv)(connp, mp, NULL, ira);
14335 		ira->ira_ill = ill;
14336 		ira->ira_rill = rill;
14337 	}
14338 	CONN_DEC_REF(connp);
14339 }
14340 
14341 /*
14342  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14343  * header before the ip payload.
14344  */
14345 static void
14346 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14347 {
14348 	int len = (mp->b_wptr - mp->b_rptr);
14349 	mblk_t *ip_mp;
14350 
14351 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14352 	if (is_fp_mp || len != fp_mp_len) {
14353 		if (len > fp_mp_len) {
14354 			/*
14355 			 * fastpath header and ip header in the first mblk
14356 			 */
14357 			mp->b_rptr += fp_mp_len;
14358 		} else {
14359 			/*
14360 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14361 			 * attach the fastpath header before ip header.
14362 			 */
14363 			ip_mp = mp->b_cont;
14364 			freeb(mp);
14365 			mp = ip_mp;
14366 			mp->b_rptr += (fp_mp_len - len);
14367 		}
14368 	} else {
14369 		ip_mp = mp->b_cont;
14370 		freeb(mp);
14371 		mp = ip_mp;
14372 	}
14373 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14374 	freemsg(mp);
14375 }
14376 
14377 /*
14378  * Normal post fragmentation function.
14379  *
14380  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14381  * using the same state machine.
14382  *
14383  * We return an error on failure. In particular we return EWOULDBLOCK
14384  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14385  * (currently by canputnext failure resulting in backenabling from GLD.)
14386  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14387  * indication that they can flow control until ip_wsrv() tells then to restart.
14388  *
14389  * If the nce passed by caller is incomplete, this function
14390  * queues the packet and if necessary, sends ARP request and bails.
14391  * If the Neighbor Cache passed is fully resolved, we simply prepend
14392  * the link-layer header to the packet, do ipsec hw acceleration
14393  * work if necessary, and send the packet out on the wire.
14394  */
14395 /* ARGSUSED6 */
14396 int
14397 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14398     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14399 {
14400 	queue_t		*wq;
14401 	ill_t		*ill = nce->nce_ill;
14402 	ip_stack_t	*ipst = ill->ill_ipst;
14403 	uint64_t	delta;
14404 	boolean_t	isv6 = ill->ill_isv6;
14405 	boolean_t	fp_mp;
14406 	ncec_t		*ncec = nce->nce_common;
14407 	int64_t		now = LBOLT_FASTPATH64;
14408 	boolean_t	is_probe;
14409 
14410 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14411 
14412 	ASSERT(mp != NULL);
14413 	ASSERT(mp->b_datap->db_type == M_DATA);
14414 	ASSERT(pkt_len == msgdsize(mp));
14415 
14416 	/*
14417 	 * If we have already been here and are coming back after ARP/ND.
14418 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14419 	 * in that case since they have seen the packet when it came here
14420 	 * the first time.
14421 	 */
14422 	if (ixaflags & IXAF_NO_TRACE)
14423 		goto sendit;
14424 
14425 	if (ixaflags & IXAF_IS_IPV4) {
14426 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14427 
14428 		ASSERT(!isv6);
14429 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14430 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14431 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14432 			int	error;
14433 
14434 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14435 			    ipst->ips_ipv4firewall_physical_out,
14436 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14437 			DTRACE_PROBE1(ip4__physical__out__end,
14438 			    mblk_t *, mp);
14439 			if (mp == NULL)
14440 				return (error);
14441 
14442 			/* The length could have changed */
14443 			pkt_len = msgdsize(mp);
14444 		}
14445 		if (ipst->ips_ip4_observe.he_interested) {
14446 			/*
14447 			 * Note that for TX the zoneid is the sending
14448 			 * zone, whether or not MLP is in play.
14449 			 * Since the szone argument is the IP zoneid (i.e.,
14450 			 * zero for exclusive-IP zones) and ipobs wants
14451 			 * the system zoneid, we map it here.
14452 			 */
14453 			szone = IP_REAL_ZONEID(szone, ipst);
14454 
14455 			/*
14456 			 * On the outbound path the destination zone will be
14457 			 * unknown as we're sending this packet out on the
14458 			 * wire.
14459 			 */
14460 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14461 			    ill, ipst);
14462 		}
14463 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14464 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14465 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14466 	} else {
14467 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14468 
14469 		ASSERT(isv6);
14470 		ASSERT(pkt_len ==
14471 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14472 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14473 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14474 			int	error;
14475 
14476 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14477 			    ipst->ips_ipv6firewall_physical_out,
14478 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14479 			DTRACE_PROBE1(ip6__physical__out__end,
14480 			    mblk_t *, mp);
14481 			if (mp == NULL)
14482 				return (error);
14483 
14484 			/* The length could have changed */
14485 			pkt_len = msgdsize(mp);
14486 		}
14487 		if (ipst->ips_ip6_observe.he_interested) {
14488 			/* See above */
14489 			szone = IP_REAL_ZONEID(szone, ipst);
14490 
14491 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14492 			    ill, ipst);
14493 		}
14494 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14495 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14496 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14497 	}
14498 
14499 sendit:
14500 	/*
14501 	 * We check the state without a lock because the state can never
14502 	 * move "backwards" to initial or incomplete.
14503 	 */
14504 	switch (ncec->ncec_state) {
14505 	case ND_REACHABLE:
14506 	case ND_STALE:
14507 	case ND_DELAY:
14508 	case ND_PROBE:
14509 		mp = ip_xmit_attach_llhdr(mp, nce);
14510 		if (mp == NULL) {
14511 			/*
14512 			 * ip_xmit_attach_llhdr has increased
14513 			 * ipIfStatsOutDiscards and called ip_drop_output()
14514 			 */
14515 			return (ENOBUFS);
14516 		}
14517 		/*
14518 		 * check if nce_fastpath completed and we tagged on a
14519 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14520 		 */
14521 		fp_mp = (mp->b_datap->db_type == M_DATA);
14522 
14523 		if (fp_mp &&
14524 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14525 			ill_dld_direct_t *idd;
14526 
14527 			idd = &ill->ill_dld_capab->idc_direct;
14528 			/*
14529 			 * Send the packet directly to DLD, where it
14530 			 * may be queued depending on the availability
14531 			 * of transmit resources at the media layer.
14532 			 * Return value should be taken into
14533 			 * account and flow control the TCP.
14534 			 */
14535 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14536 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14537 			    pkt_len);
14538 
14539 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14540 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14541 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14542 			} else {
14543 				uintptr_t cookie;
14544 
14545 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14546 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14547 					if (ixacookie != NULL)
14548 						*ixacookie = cookie;
14549 					return (EWOULDBLOCK);
14550 				}
14551 			}
14552 		} else {
14553 			wq = ill->ill_wq;
14554 
14555 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14556 			    !canputnext(wq)) {
14557 				if (ixacookie != NULL)
14558 					*ixacookie = 0;
14559 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14560 				    nce->nce_fp_mp != NULL ?
14561 				    MBLKL(nce->nce_fp_mp) : 0);
14562 				return (EWOULDBLOCK);
14563 			}
14564 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14565 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14566 			    pkt_len);
14567 			putnext(wq, mp);
14568 		}
14569 
14570 		/*
14571 		 * The rest of this function implements Neighbor Unreachability
14572 		 * detection. Determine if the ncec is eligible for NUD.
14573 		 */
14574 		if (ncec->ncec_flags & NCE_F_NONUD)
14575 			return (0);
14576 
14577 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14578 
14579 		/*
14580 		 * Check for upper layer advice
14581 		 */
14582 		if (ixaflags & IXAF_REACH_CONF) {
14583 			timeout_id_t tid;
14584 
14585 			/*
14586 			 * It should be o.k. to check the state without
14587 			 * a lock here, at most we lose an advice.
14588 			 */
14589 			ncec->ncec_last = TICK_TO_MSEC(now);
14590 			if (ncec->ncec_state != ND_REACHABLE) {
14591 				mutex_enter(&ncec->ncec_lock);
14592 				ncec->ncec_state = ND_REACHABLE;
14593 				tid = ncec->ncec_timeout_id;
14594 				ncec->ncec_timeout_id = 0;
14595 				mutex_exit(&ncec->ncec_lock);
14596 				(void) untimeout(tid);
14597 				if (ip_debug > 2) {
14598 					/* ip1dbg */
14599 					pr_addr_dbg("ip_xmit: state"
14600 					    " for %s changed to"
14601 					    " REACHABLE\n", AF_INET6,
14602 					    &ncec->ncec_addr);
14603 				}
14604 			}
14605 			return (0);
14606 		}
14607 
14608 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14609 		ip1dbg(("ip_xmit: delta = %" PRId64
14610 		    " ill_reachable_time = %d \n", delta,
14611 		    ill->ill_reachable_time));
14612 		if (delta > (uint64_t)ill->ill_reachable_time) {
14613 			mutex_enter(&ncec->ncec_lock);
14614 			switch (ncec->ncec_state) {
14615 			case ND_REACHABLE:
14616 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14617 				/* FALLTHROUGH */
14618 			case ND_STALE:
14619 				/*
14620 				 * ND_REACHABLE is identical to
14621 				 * ND_STALE in this specific case. If
14622 				 * reachable time has expired for this
14623 				 * neighbor (delta is greater than
14624 				 * reachable time), conceptually, the
14625 				 * neighbor cache is no longer in
14626 				 * REACHABLE state, but already in
14627 				 * STALE state.  So the correct
14628 				 * transition here is to ND_DELAY.
14629 				 */
14630 				ncec->ncec_state = ND_DELAY;
14631 				mutex_exit(&ncec->ncec_lock);
14632 				nce_restart_timer(ncec,
14633 				    ipst->ips_delay_first_probe_time);
14634 				if (ip_debug > 3) {
14635 					/* ip2dbg */
14636 					pr_addr_dbg("ip_xmit: state"
14637 					    " for %s changed to"
14638 					    " DELAY\n", AF_INET6,
14639 					    &ncec->ncec_addr);
14640 				}
14641 				break;
14642 			case ND_DELAY:
14643 			case ND_PROBE:
14644 				mutex_exit(&ncec->ncec_lock);
14645 				/* Timers have already started */
14646 				break;
14647 			case ND_UNREACHABLE:
14648 				/*
14649 				 * nce_timer has detected that this ncec
14650 				 * is unreachable and initiated deleting
14651 				 * this ncec.
14652 				 * This is a harmless race where we found the
14653 				 * ncec before it was deleted and have
14654 				 * just sent out a packet using this
14655 				 * unreachable ncec.
14656 				 */
14657 				mutex_exit(&ncec->ncec_lock);
14658 				break;
14659 			default:
14660 				ASSERT(0);
14661 				mutex_exit(&ncec->ncec_lock);
14662 			}
14663 		}
14664 		return (0);
14665 
14666 	case ND_INCOMPLETE:
14667 		/*
14668 		 * the state could have changed since we didn't hold the lock.
14669 		 * Re-verify state under lock.
14670 		 */
14671 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14672 		mutex_enter(&ncec->ncec_lock);
14673 		if (NCE_ISREACHABLE(ncec)) {
14674 			mutex_exit(&ncec->ncec_lock);
14675 			goto sendit;
14676 		}
14677 		/* queue the packet */
14678 		nce_queue_mp(ncec, mp, is_probe);
14679 		mutex_exit(&ncec->ncec_lock);
14680 		DTRACE_PROBE2(ip__xmit__incomplete,
14681 		    (ncec_t *), ncec, (mblk_t *), mp);
14682 		return (0);
14683 
14684 	case ND_INITIAL:
14685 		/*
14686 		 * State could have changed since we didn't hold the lock, so
14687 		 * re-verify state.
14688 		 */
14689 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14690 		mutex_enter(&ncec->ncec_lock);
14691 		if (NCE_ISREACHABLE(ncec))  {
14692 			mutex_exit(&ncec->ncec_lock);
14693 			goto sendit;
14694 		}
14695 		nce_queue_mp(ncec, mp, is_probe);
14696 		if (ncec->ncec_state == ND_INITIAL) {
14697 			ncec->ncec_state = ND_INCOMPLETE;
14698 			mutex_exit(&ncec->ncec_lock);
14699 			/*
14700 			 * figure out the source we want to use
14701 			 * and resolve it.
14702 			 */
14703 			ip_ndp_resolve(ncec);
14704 		} else  {
14705 			mutex_exit(&ncec->ncec_lock);
14706 		}
14707 		return (0);
14708 
14709 	case ND_UNREACHABLE:
14710 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14711 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14712 		    mp, ill);
14713 		freemsg(mp);
14714 		return (0);
14715 
14716 	default:
14717 		ASSERT(0);
14718 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14719 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14720 		    mp, ill);
14721 		freemsg(mp);
14722 		return (ENETUNREACH);
14723 	}
14724 }
14725 
14726 /*
14727  * Return B_TRUE if the buffers differ in length or content.
14728  * This is used for comparing extension header buffers.
14729  * Note that an extension header would be declared different
14730  * even if all that changed was the next header value in that header i.e.
14731  * what really changed is the next extension header.
14732  */
14733 boolean_t
14734 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14735     uint_t blen)
14736 {
14737 	if (!b_valid)
14738 		blen = 0;
14739 
14740 	if (alen != blen)
14741 		return (B_TRUE);
14742 	if (alen == 0)
14743 		return (B_FALSE);	/* Both zero length */
14744 	return (bcmp(abuf, bbuf, alen));
14745 }
14746 
14747 /*
14748  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14749  * Return B_FALSE if memory allocation fails - don't change any state!
14750  */
14751 boolean_t
14752 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14753     const void *src, uint_t srclen)
14754 {
14755 	void *dst;
14756 
14757 	if (!src_valid)
14758 		srclen = 0;
14759 
14760 	ASSERT(*dstlenp == 0);
14761 	if (src != NULL && srclen != 0) {
14762 		dst = mi_alloc(srclen, BPRI_MED);
14763 		if (dst == NULL)
14764 			return (B_FALSE);
14765 	} else {
14766 		dst = NULL;
14767 	}
14768 	if (*dstp != NULL)
14769 		mi_free(*dstp);
14770 	*dstp = dst;
14771 	*dstlenp = dst == NULL ? 0 : srclen;
14772 	return (B_TRUE);
14773 }
14774 
14775 /*
14776  * Replace what is in *dst, *dstlen with the source.
14777  * Assumes ip_allocbuf has already been called.
14778  */
14779 void
14780 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14781     const void *src, uint_t srclen)
14782 {
14783 	if (!src_valid)
14784 		srclen = 0;
14785 
14786 	ASSERT(*dstlenp == srclen);
14787 	if (src != NULL && srclen != 0)
14788 		bcopy(src, *dstp, srclen);
14789 }
14790 
14791 /*
14792  * Free the storage pointed to by the members of an ip_pkt_t.
14793  */
14794 void
14795 ip_pkt_free(ip_pkt_t *ipp)
14796 {
14797 	uint_t	fields = ipp->ipp_fields;
14798 
14799 	if (fields & IPPF_HOPOPTS) {
14800 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14801 		ipp->ipp_hopopts = NULL;
14802 		ipp->ipp_hopoptslen = 0;
14803 	}
14804 	if (fields & IPPF_RTHDRDSTOPTS) {
14805 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14806 		ipp->ipp_rthdrdstopts = NULL;
14807 		ipp->ipp_rthdrdstoptslen = 0;
14808 	}
14809 	if (fields & IPPF_DSTOPTS) {
14810 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14811 		ipp->ipp_dstopts = NULL;
14812 		ipp->ipp_dstoptslen = 0;
14813 	}
14814 	if (fields & IPPF_RTHDR) {
14815 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14816 		ipp->ipp_rthdr = NULL;
14817 		ipp->ipp_rthdrlen = 0;
14818 	}
14819 	if (fields & IPPF_IPV4_OPTIONS) {
14820 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14821 		ipp->ipp_ipv4_options = NULL;
14822 		ipp->ipp_ipv4_options_len = 0;
14823 	}
14824 	if (fields & IPPF_LABEL_V4) {
14825 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14826 		ipp->ipp_label_v4 = NULL;
14827 		ipp->ipp_label_len_v4 = 0;
14828 	}
14829 	if (fields & IPPF_LABEL_V6) {
14830 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14831 		ipp->ipp_label_v6 = NULL;
14832 		ipp->ipp_label_len_v6 = 0;
14833 	}
14834 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14835 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14836 }
14837 
14838 /*
14839  * Copy from src to dst and allocate as needed.
14840  * Returns zero or ENOMEM.
14841  *
14842  * The caller must initialize dst to zero.
14843  */
14844 int
14845 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14846 {
14847 	uint_t	fields = src->ipp_fields;
14848 
14849 	/* Start with fields that don't require memory allocation */
14850 	dst->ipp_fields = fields &
14851 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14852 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14853 
14854 	dst->ipp_addr = src->ipp_addr;
14855 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
14856 	dst->ipp_hoplimit = src->ipp_hoplimit;
14857 	dst->ipp_tclass = src->ipp_tclass;
14858 	dst->ipp_type_of_service = src->ipp_type_of_service;
14859 
14860 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14861 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14862 		return (0);
14863 
14864 	if (fields & IPPF_HOPOPTS) {
14865 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14866 		if (dst->ipp_hopopts == NULL) {
14867 			ip_pkt_free(dst);
14868 			return (ENOMEM);
14869 		}
14870 		dst->ipp_fields |= IPPF_HOPOPTS;
14871 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14872 		    src->ipp_hopoptslen);
14873 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
14874 	}
14875 	if (fields & IPPF_RTHDRDSTOPTS) {
14876 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14877 		    kmflag);
14878 		if (dst->ipp_rthdrdstopts == NULL) {
14879 			ip_pkt_free(dst);
14880 			return (ENOMEM);
14881 		}
14882 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14883 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14884 		    src->ipp_rthdrdstoptslen);
14885 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14886 	}
14887 	if (fields & IPPF_DSTOPTS) {
14888 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14889 		if (dst->ipp_dstopts == NULL) {
14890 			ip_pkt_free(dst);
14891 			return (ENOMEM);
14892 		}
14893 		dst->ipp_fields |= IPPF_DSTOPTS;
14894 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14895 		    src->ipp_dstoptslen);
14896 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
14897 	}
14898 	if (fields & IPPF_RTHDR) {
14899 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14900 		if (dst->ipp_rthdr == NULL) {
14901 			ip_pkt_free(dst);
14902 			return (ENOMEM);
14903 		}
14904 		dst->ipp_fields |= IPPF_RTHDR;
14905 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14906 		    src->ipp_rthdrlen);
14907 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
14908 	}
14909 	if (fields & IPPF_IPV4_OPTIONS) {
14910 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14911 		    kmflag);
14912 		if (dst->ipp_ipv4_options == NULL) {
14913 			ip_pkt_free(dst);
14914 			return (ENOMEM);
14915 		}
14916 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14917 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14918 		    src->ipp_ipv4_options_len);
14919 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14920 	}
14921 	if (fields & IPPF_LABEL_V4) {
14922 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14923 		if (dst->ipp_label_v4 == NULL) {
14924 			ip_pkt_free(dst);
14925 			return (ENOMEM);
14926 		}
14927 		dst->ipp_fields |= IPPF_LABEL_V4;
14928 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14929 		    src->ipp_label_len_v4);
14930 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14931 	}
14932 	if (fields & IPPF_LABEL_V6) {
14933 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14934 		if (dst->ipp_label_v6 == NULL) {
14935 			ip_pkt_free(dst);
14936 			return (ENOMEM);
14937 		}
14938 		dst->ipp_fields |= IPPF_LABEL_V6;
14939 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14940 		    src->ipp_label_len_v6);
14941 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14942 	}
14943 	if (fields & IPPF_FRAGHDR) {
14944 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14945 		if (dst->ipp_fraghdr == NULL) {
14946 			ip_pkt_free(dst);
14947 			return (ENOMEM);
14948 		}
14949 		dst->ipp_fields |= IPPF_FRAGHDR;
14950 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14951 		    src->ipp_fraghdrlen);
14952 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14953 	}
14954 	return (0);
14955 }
14956 
14957 /*
14958  * Returns INADDR_ANY if no source route
14959  */
14960 ipaddr_t
14961 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14962 {
14963 	ipaddr_t	nexthop = INADDR_ANY;
14964 	ipoptp_t	opts;
14965 	uchar_t		*opt;
14966 	uint8_t		optval;
14967 	uint8_t		optlen;
14968 	uint32_t	totallen;
14969 
14970 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14971 		return (INADDR_ANY);
14972 
14973 	totallen = ipp->ipp_ipv4_options_len;
14974 	if (totallen & 0x3)
14975 		return (INADDR_ANY);
14976 
14977 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14978 	    optval != IPOPT_EOL;
14979 	    optval = ipoptp_next(&opts)) {
14980 		opt = opts.ipoptp_cur;
14981 		switch (optval) {
14982 			uint8_t off;
14983 		case IPOPT_SSRR:
14984 		case IPOPT_LSRR:
14985 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
14986 				break;
14987 			}
14988 			optlen = opts.ipoptp_len;
14989 			off = opt[IPOPT_OFFSET];
14990 			off--;
14991 			if (optlen < IP_ADDR_LEN ||
14992 			    off > optlen - IP_ADDR_LEN) {
14993 				/* End of source route */
14994 				break;
14995 			}
14996 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
14997 			if (nexthop == htonl(INADDR_LOOPBACK)) {
14998 				/* Ignore */
14999 				nexthop = INADDR_ANY;
15000 				break;
15001 			}
15002 			break;
15003 		}
15004 	}
15005 	return (nexthop);
15006 }
15007 
15008 /*
15009  * Reverse a source route.
15010  */
15011 void
15012 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
15013 {
15014 	ipaddr_t	tmp;
15015 	ipoptp_t	opts;
15016 	uchar_t		*opt;
15017 	uint8_t		optval;
15018 	uint32_t	totallen;
15019 
15020 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15021 		return;
15022 
15023 	totallen = ipp->ipp_ipv4_options_len;
15024 	if (totallen & 0x3)
15025 		return;
15026 
15027 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15028 	    optval != IPOPT_EOL;
15029 	    optval = ipoptp_next(&opts)) {
15030 		uint8_t off1, off2;
15031 
15032 		opt = opts.ipoptp_cur;
15033 		switch (optval) {
15034 		case IPOPT_SSRR:
15035 		case IPOPT_LSRR:
15036 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15037 				break;
15038 			}
15039 			off1 = IPOPT_MINOFF_SR - 1;
15040 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
15041 			while (off2 > off1) {
15042 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
15043 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
15044 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
15045 				off2 -= IP_ADDR_LEN;
15046 				off1 += IP_ADDR_LEN;
15047 			}
15048 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
15049 			break;
15050 		}
15051 	}
15052 }
15053 
15054 /*
15055  * Returns NULL if no routing header
15056  */
15057 in6_addr_t *
15058 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
15059 {
15060 	in6_addr_t	*nexthop = NULL;
15061 	ip6_rthdr0_t	*rthdr;
15062 
15063 	if (!(ipp->ipp_fields & IPPF_RTHDR))
15064 		return (NULL);
15065 
15066 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
15067 	if (rthdr->ip6r0_segleft == 0)
15068 		return (NULL);
15069 
15070 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
15071 	return (nexthop);
15072 }
15073 
15074 zoneid_t
15075 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15076     zoneid_t lookup_zoneid)
15077 {
15078 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15079 	ire_t		*ire;
15080 	int		ire_flags = MATCH_IRE_TYPE;
15081 	zoneid_t	zoneid = ALL_ZONES;
15082 
15083 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15084 		return (ALL_ZONES);
15085 
15086 	if (lookup_zoneid != ALL_ZONES)
15087 		ire_flags |= MATCH_IRE_ZONEONLY;
15088 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15089 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15090 	if (ire != NULL) {
15091 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15092 		ire_refrele(ire);
15093 	}
15094 	return (zoneid);
15095 }
15096 
15097 zoneid_t
15098 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15099     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15100 {
15101 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15102 	ire_t		*ire;
15103 	int		ire_flags = MATCH_IRE_TYPE;
15104 	zoneid_t	zoneid = ALL_ZONES;
15105 
15106 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15107 		return (ALL_ZONES);
15108 
15109 	if (IN6_IS_ADDR_LINKLOCAL(addr))
15110 		ire_flags |= MATCH_IRE_ILL;
15111 
15112 	if (lookup_zoneid != ALL_ZONES)
15113 		ire_flags |= MATCH_IRE_ZONEONLY;
15114 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15115 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15116 	if (ire != NULL) {
15117 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15118 		ire_refrele(ire);
15119 	}
15120 	return (zoneid);
15121 }
15122 
15123 /*
15124  * IP obserability hook support functions.
15125  */
15126 static void
15127 ipobs_init(ip_stack_t *ipst)
15128 {
15129 	netid_t id;
15130 
15131 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15132 
15133 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15134 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
15135 
15136 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15137 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
15138 }
15139 
15140 static void
15141 ipobs_fini(ip_stack_t *ipst)
15142 {
15143 
15144 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15145 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15146 }
15147 
15148 /*
15149  * hook_pkt_observe_t is composed in network byte order so that the
15150  * entire mblk_t chain handed into hook_run can be used as-is.
15151  * The caveat is that use of the fields, such as the zone fields,
15152  * requires conversion into host byte order first.
15153  */
15154 void
15155 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15156     const ill_t *ill, ip_stack_t *ipst)
15157 {
15158 	hook_pkt_observe_t *hdr;
15159 	uint64_t grifindex;
15160 	mblk_t *imp;
15161 
15162 	imp = allocb(sizeof (*hdr), BPRI_HI);
15163 	if (imp == NULL)
15164 		return;
15165 
15166 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15167 	/*
15168 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15169 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15170 	 */
15171 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15172 	imp->b_cont = mp;
15173 
15174 	ASSERT(DB_TYPE(mp) == M_DATA);
15175 
15176 	if (IS_UNDER_IPMP(ill))
15177 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15178 	else
15179 		grifindex = 0;
15180 
15181 	hdr->hpo_version = 1;
15182 	hdr->hpo_htype = htons(htype);
15183 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15184 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15185 	hdr->hpo_grifindex = htonl(grifindex);
15186 	hdr->hpo_zsrc = htonl(zsrc);
15187 	hdr->hpo_zdst = htonl(zdst);
15188 	hdr->hpo_pkt = imp;
15189 	hdr->hpo_ctx = ipst->ips_netstack;
15190 
15191 	if (ill->ill_isv6) {
15192 		hdr->hpo_family = AF_INET6;
15193 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15194 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15195 	} else {
15196 		hdr->hpo_family = AF_INET;
15197 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15198 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15199 	}
15200 
15201 	imp->b_cont = NULL;
15202 	freemsg(imp);
15203 }
15204 
15205 /*
15206  * Utility routine that checks if `v4srcp' is a valid address on underlying
15207  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15208  * associated with `v4srcp' on success.  NOTE: if this is not called from
15209  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15210  * group during or after this lookup.
15211  */
15212 boolean_t
15213 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15214 {
15215 	ipif_t *ipif;
15216 
15217 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15218 	if (ipif != NULL) {
15219 		if (ipifp != NULL)
15220 			*ipifp = ipif;
15221 		else
15222 			ipif_refrele(ipif);
15223 		return (B_TRUE);
15224 	}
15225 
15226 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15227 	    *v4srcp));
15228 	return (B_FALSE);
15229 }
15230 
15231 /*
15232  * Transport protocol call back function for CPU state change.
15233  */
15234 /* ARGSUSED */
15235 static int
15236 ip_tp_cpu_update(cpu_setup_t what, int id, void *arg)
15237 {
15238 	processorid_t cpu_seqid;
15239 	netstack_handle_t nh;
15240 	netstack_t *ns;
15241 
15242 	ASSERT(MUTEX_HELD(&cpu_lock));
15243 
15244 	switch (what) {
15245 	case CPU_CONFIG:
15246 	case CPU_ON:
15247 	case CPU_INIT:
15248 	case CPU_CPUPART_IN:
15249 		cpu_seqid = cpu[id]->cpu_seqid;
15250 		netstack_next_init(&nh);
15251 		while ((ns = netstack_next(&nh)) != NULL) {
15252 			tcp_stack_cpu_add(ns->netstack_tcp, cpu_seqid);
15253 			sctp_stack_cpu_add(ns->netstack_sctp, cpu_seqid);
15254 			udp_stack_cpu_add(ns->netstack_udp, cpu_seqid);
15255 			netstack_rele(ns);
15256 		}
15257 		netstack_next_fini(&nh);
15258 		break;
15259 	case CPU_UNCONFIG:
15260 	case CPU_OFF:
15261 	case CPU_CPUPART_OUT:
15262 		/*
15263 		 * Nothing to do.  We don't remove the per CPU stats from
15264 		 * the IP stack even when the CPU goes offline.
15265 		 */
15266 		break;
15267 	default:
15268 		break;
15269 	}
15270 	return (0);
15271 }
15272