xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 5e1743f0)
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) 2017 OmniTI Computer Consulting, Inc. All rights reserved.
26  * Copyright (c) 2016 by Delphix. All rights reserved.
27  * Copyright (c) 2018 Joyent, Inc. All rights reserved.
28  */
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/suntpi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 #include <sys/taskq.h>
52 
53 #include <sys/systm.h>
54 #include <sys/param.h>
55 #include <sys/kmem.h>
56 #include <sys/sdt.h>
57 #include <sys/socket.h>
58 #include <sys/vtrace.h>
59 #include <sys/isa_defs.h>
60 #include <sys/mac.h>
61 #include <net/if.h>
62 #include <net/if_arp.h>
63 #include <net/route.h>
64 #include <sys/sockio.h>
65 #include <netinet/in.h>
66 #include <net/if_dl.h>
67 
68 #include <inet/common.h>
69 #include <inet/mi.h>
70 #include <inet/mib2.h>
71 #include <inet/nd.h>
72 #include <inet/arp.h>
73 #include <inet/snmpcom.h>
74 #include <inet/optcom.h>
75 #include <inet/kstatcom.h>
76 
77 #include <netinet/igmp_var.h>
78 #include <netinet/ip6.h>
79 #include <netinet/icmp6.h>
80 #include <netinet/sctp.h>
81 
82 #include <inet/ip.h>
83 #include <inet/ip_impl.h>
84 #include <inet/ip6.h>
85 #include <inet/ip6_asp.h>
86 #include <inet/tcp.h>
87 #include <inet/tcp_impl.h>
88 #include <inet/ip_multi.h>
89 #include <inet/ip_if.h>
90 #include <inet/ip_ire.h>
91 #include <inet/ip_ftable.h>
92 #include <inet/ip_rts.h>
93 #include <inet/ip_ndp.h>
94 #include <inet/ip_listutils.h>
95 #include <netinet/igmp.h>
96 #include <netinet/ip_mroute.h>
97 #include <inet/ipp_common.h>
98 
99 #include <net/pfkeyv2.h>
100 #include <inet/sadb.h>
101 #include <inet/ipsec_impl.h>
102 #include <inet/iptun/iptun_impl.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 #include <inet/ilb_ip.h>
106 
107 #include <sys/ethernet.h>
108 #include <net/if_types.h>
109 #include <sys/cpuvar.h>
110 
111 #include <ipp/ipp.h>
112 #include <ipp/ipp_impl.h>
113 #include <ipp/ipgpc/ipgpc.h>
114 
115 #include <sys/pattr.h>
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <sys/squeue_impl.h>
127 #include <inet/ip_arp.h>
128 
129 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
130 
131 /*
132  * Values for squeue switch:
133  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
134  * IP_SQUEUE_ENTER: SQ_PROCESS
135  * IP_SQUEUE_FILL: SQ_FILL
136  */
137 int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */
138 
139 int ip_squeue_flag;
140 
141 /*
142  * Setable in /etc/system
143  */
144 int ip_poll_normal_ms = 100;
145 int ip_poll_normal_ticks = 0;
146 int ip_modclose_ackwait_ms = 3000;
147 
148 /*
149  * It would be nice to have these present only in DEBUG systems, but the
150  * current design of the global symbol checking logic requires them to be
151  * unconditionally present.
152  */
153 uint_t ip_thread_data;			/* TSD key for debug support */
154 krwlock_t ip_thread_rwlock;
155 list_t	ip_thread_list;
156 
157 /*
158  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
159  */
160 
161 struct listptr_s {
162 	mblk_t	*lp_head;	/* pointer to the head of the list */
163 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
164 };
165 
166 typedef struct listptr_s listptr_t;
167 
168 /*
169  * This is used by ip_snmp_get_mib2_ip_route_media and
170  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
171  */
172 typedef struct iproutedata_s {
173 	uint_t		ird_idx;
174 	uint_t		ird_flags;	/* see below */
175 	listptr_t	ird_route;	/* ipRouteEntryTable */
176 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
177 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
178 } iproutedata_t;
179 
180 /* Include ire_testhidden and IRE_IF_CLONE routes */
181 #define	IRD_REPORT_ALL	0x01
182 
183 /*
184  * Cluster specific hooks. These should be NULL when booted as a non-cluster
185  */
186 
187 /*
188  * Hook functions to enable cluster networking
189  * On non-clustered systems these vectors must always be NULL.
190  *
191  * Hook function to Check ip specified ip address is a shared ip address
192  * in the cluster
193  *
194  */
195 int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
196     sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;
197 
198 /*
199  * Hook function to generate cluster wide ip fragment identifier
200  */
201 uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
202     sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
203     void *args) = NULL;
204 
205 /*
206  * Hook function to generate cluster wide SPI.
207  */
208 void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
209     void *) = NULL;
210 
211 /*
212  * Hook function to verify if the SPI is already utlized.
213  */
214 
215 int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
216 
217 /*
218  * Hook function to delete the SPI from the cluster wide repository.
219  */
220 
221 void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;
222 
223 /*
224  * Hook function to inform the cluster when packet received on an IDLE SA
225  */
226 
227 void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
228     in6_addr_t, in6_addr_t, void *) = NULL;
229 
230 /*
231  * Synchronization notes:
232  *
233  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
234  * MT level protection given by STREAMS. IP uses a combination of its own
235  * internal serialization mechanism and standard Solaris locking techniques.
236  * The internal serialization is per phyint.  This is used to serialize
237  * plumbing operations, IPMP operations, most set ioctls, etc.
238  *
239  * Plumbing is a long sequence of operations involving message
240  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
241  * involved in plumbing operations. A natural model is to serialize these
242  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
243  * parallel without any interference. But various set ioctls on hme0 are best
244  * serialized, along with IPMP operations and processing of DLPI control
245  * messages received from drivers on a per phyint basis. This serialization is
246  * provided by the ipsq_t and primitives operating on this. Details can
247  * be found in ip_if.c above the core primitives operating on ipsq_t.
248  *
249  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
250  * Simiarly lookup of an ire by a thread also returns a refheld ire.
251  * In addition ipif's and ill's referenced by the ire are also indirectly
252  * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
253  * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
254  * address of an ipif has to go through the ipsq_t. This ensures that only
255  * one such exclusive operation proceeds at any time on the ipif. It then
256  * waits for all refcnts
257  * associated with this ipif to come down to zero. The address is changed
258  * only after the ipif has been quiesced. Then the ipif is brought up again.
259  * More details are described above the comment in ip_sioctl_flags.
260  *
261  * Packet processing is based mostly on IREs and are fully multi-threaded
262  * using standard Solaris MT techniques.
263  *
264  * There are explicit locks in IP to handle:
265  * - The ip_g_head list maintained by mi_open_link() and friends.
266  *
267  * - The reassembly data structures (one lock per hash bucket)
268  *
269  * - conn_lock is meant to protect conn_t fields. The fields actually
270  *   protected by conn_lock are documented in the conn_t definition.
271  *
272  * - ire_lock to protect some of the fields of the ire, IRE tables
273  *   (one lock per hash bucket). Refer to ip_ire.c for details.
274  *
275  * - ndp_g_lock and ncec_lock for protecting NCEs.
276  *
277  * - ill_lock protects fields of the ill and ipif. Details in ip.h
278  *
279  * - ill_g_lock: This is a global reader/writer lock. Protects the following
280  *	* The AVL tree based global multi list of all ills.
281  *	* The linked list of all ipifs of an ill
282  *	* The <ipsq-xop> mapping
283  *	* <ill-phyint> association
284  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
285  *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
286  *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
287  *   writer for the actual duration of the insertion/deletion/change.
288  *
289  * - ill_lock:  This is a per ill mutex.
290  *   It protects some members of the ill_t struct; see ip.h for details.
291  *   It also protects the <ill-phyint> assoc.
292  *   It also protects the list of ipifs hanging off the ill.
293  *
294  * - ipsq_lock: This is a per ipsq_t mutex lock.
295  *   This protects some members of the ipsq_t struct; see ip.h for details.
296  *   It also protects the <ipsq-ipxop> mapping
297  *
298  * - ipx_lock: This is a per ipxop_t mutex lock.
299  *   This protects some members of the ipxop_t struct; see ip.h for details.
300  *
301  * - phyint_lock: This is a per phyint mutex lock. Protects just the
302  *   phyint_flags
303  *
304  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
305  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
306  *   uniqueness check also done atomically.
307  *
308  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
309  *   group list linked by ill_usesrc_grp_next. It also protects the
310  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
311  *   group is being added or deleted.  This lock is taken as a reader when
312  *   walking the list/group(eg: to get the number of members in a usesrc group).
313  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
314  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
315  *   example, it is not necessary to take this lock in the initial portion
316  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
317  *   operations are executed exclusively and that ensures that the "usesrc
318  *   group state" cannot change. The "usesrc group state" change can happen
319  *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
320  *
321  * Changing <ill-phyint>, <ipsq-xop> assocications:
322  *
323  * To change the <ill-phyint> association, the ill_g_lock must be held
324  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
325  * must be held.
326  *
327  * To change the <ipsq-xop> association, the ill_g_lock must be held as
328  * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
329  * This is only done when ills are added or removed from IPMP groups.
330  *
331  * To add or delete an ipif from the list of ipifs hanging off the ill,
332  * ill_g_lock (writer) and ill_lock must be held and the thread must be
333  * a writer on the associated ipsq.
334  *
335  * To add or delete an ill to the system, the ill_g_lock must be held as
336  * writer and the thread must be a writer on the associated ipsq.
337  *
338  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
339  * must be a writer on the associated ipsq.
340  *
341  * Lock hierarchy
342  *
343  * Some lock hierarchy scenarios are listed below.
344  *
345  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
346  * ill_g_lock -> ill_lock(s) -> phyint_lock
347  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
348  * ill_g_lock -> ip_addr_avail_lock
349  * conn_lock -> irb_lock -> ill_lock -> ire_lock
350  * ill_g_lock -> ip_g_nd_lock
351  * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
352  * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
353  * arl_lock -> ill_lock
354  * ips_ire_dep_lock -> irb_lock
355  *
356  * When more than 1 ill lock is needed to be held, all ill lock addresses
357  * are sorted on address and locked starting from highest addressed lock
358  * downward.
359  *
360  * Multicast scenarios
361  * ips_ill_g_lock -> ill_mcast_lock
362  * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
363  * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
364  * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
365  * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
366  * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
367  *
368  * IPsec scenarios
369  *
370  * ipsa_lock -> ill_g_lock -> ill_lock
371  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
372  *
373  * Trusted Solaris scenarios
374  *
375  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
376  * igsa_lock -> gcdb_lock
377  * gcgrp_rwlock -> ire_lock
378  * gcgrp_rwlock -> gcdb_lock
379  *
380  * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
381  *
382  * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
383  * sq_lock -> conn_lock -> QLOCK(q)
384  * ill_lock -> ft_lock -> fe_lock
385  *
386  * Routing/forwarding table locking notes:
387  *
388  * Lock acquisition order: Radix tree lock, irb_lock.
389  * Requirements:
390  * i.  Walker must not hold any locks during the walker callback.
391  * ii  Walker must not see a truncated tree during the walk because of any node
392  *     deletion.
393  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
394  *     in many places in the code to walk the irb list. Thus even if all the
395  *     ires in a bucket have been deleted, we still can't free the radix node
396  *     until the ires have actually been inactive'd (freed).
397  *
398  * Tree traversal - Need to hold the global tree lock in read mode.
399  * Before dropping the global tree lock, need to either increment the ire_refcnt
400  * to ensure that the radix node can't be deleted.
401  *
402  * Tree add - Need to hold the global tree lock in write mode to add a
403  * radix node. To prevent the node from being deleted, increment the
404  * irb_refcnt, after the node is added to the tree. The ire itself is
405  * added later while holding the irb_lock, but not the tree lock.
406  *
407  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
408  * All associated ires must be inactive (i.e. freed), and irb_refcnt
409  * must be zero.
410  *
411  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
412  * global tree lock (read mode) for traversal.
413  *
414  * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
415  * hence we will acquire irb_lock while holding ips_ire_dep_lock.
416  *
417  * IPsec notes :
418  *
419  * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
420  * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
421  * ip_xmit_attr_t has the
422  * information used by the IPsec code for applying the right level of
423  * protection. The information initialized by IP in the ip_xmit_attr_t
424  * is determined by the per-socket policy or global policy in the system.
425  * For inbound datagrams, the ip_recv_attr_t
426  * starts out with nothing in it. It gets filled
427  * with the right information if it goes through the AH/ESP code, which
428  * happens if the incoming packet is secure. The information initialized
429  * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
430  * the policy requirements needed by per-socket policy or global policy
431  * is met or not.
432  *
433  * For fully connected sockets i.e dst, src [addr, port] is known,
434  * conn_policy_cached is set indicating that policy has been cached.
435  * conn_in_enforce_policy may or may not be set depending on whether
436  * there is a global policy match or per-socket policy match.
437  * Policy inheriting happpens in ip_policy_set once the destination is known.
438  * Once the right policy is set on the conn_t, policy cannot change for
439  * this socket. This makes life simpler for TCP (UDP ?) where
440  * re-transmissions go out with the same policy. For symmetry, policy
441  * is cached for fully connected UDP sockets also. Thus if policy is cached,
442  * it also implies that policy is latched i.e policy cannot change
443  * on these sockets. As we have the right policy on the conn, we don't
444  * have to lookup global policy for every outbound and inbound datagram
445  * and thus serving as an optimization. Note that a global policy change
446  * does not affect fully connected sockets if they have policy. If fully
447  * connected sockets did not have any policy associated with it, global
448  * policy change may affect them.
449  *
450  * IP Flow control notes:
451  * ---------------------
452  * Non-TCP streams are flow controlled by IP. The way this is accomplished
453  * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
454  * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
455  * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
456  * functions.
457  *
458  * Per Tx ring udp flow control:
459  * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
460  * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
461  *
462  * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
463  * To achieve best performance, outgoing traffic need to be fanned out among
464  * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
465  * traffic out of the NIC and it takes a fanout hint. UDP connections pass
466  * the address of connp as fanout hint to mac_tx(). Under flow controlled
467  * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
468  * cookie points to a specific Tx ring that is blocked. The cookie is used to
469  * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
470  * point to drain_lists (idl_t's). These drain list will store the blocked UDP
471  * connp's. The drain list is not a single list but a configurable number of
472  * lists.
473  *
474  * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
475  * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
476  * which is equal to 128. This array in turn contains a pointer to idl_t[],
477  * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
478  * list will point to the list of connp's that are flow controlled.
479  *
480  *                      ---------------   -------   -------   -------
481  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
482  *                   |  ---------------   -------   -------   -------
483  *                   |  ---------------   -------   -------   -------
484  *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
485  * ----------------  |  ---------------   -------   -------   -------
486  * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
487  * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
488  *                   |  ---------------   -------   -------   -------
489  *                   .        .              .         .         .
490  *                   |  ---------------   -------   -------   -------
491  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
492  *                      ---------------   -------   -------   -------
493  *                      ---------------   -------   -------   -------
494  *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
495  *                   |  ---------------   -------   -------   -------
496  *                   |  ---------------   -------   -------   -------
497  * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
498  * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
499  * ----------------  |        .              .         .         .
500  *                   |  ---------------   -------   -------   -------
501  *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
502  *                      ---------------   -------   -------   -------
503  *     .....
504  * ----------------
505  * |idl_tx_list[n]|-> ...
506  * ----------------
507  *
508  * When mac_tx() returns a cookie, the cookie is hashed into an index into
509  * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
510  * to insert the conn onto.  conn_drain_insert() asserts flow control for the
511  * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
512  * Further, conn_blocked is set to indicate that the conn is blocked.
513  *
514  * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
515  * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
516  * is again hashed to locate the appropriate idl_tx_list, which is then
517  * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
518  * the drain list and calls conn_drain_remove() to clear flow control (via
519  * calling su_txq_full() or clearing QFULL), and remove the conn from the
520  * drain list.
521  *
522  * Note that the drain list is not a single list but a (configurable) array of
523  * lists (8 elements by default).  Synchronization between drain insertion and
524  * flow control wakeup is handled by using idl_txl->txl_lock, and only
525  * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
526  *
527  * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
528  * On the send side, if the packet cannot be sent down to the driver by IP
529  * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
530  * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
531  * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
532  * control has been relieved, the blocked conns in the 0'th drain list are
533  * drained as in the non-STREAMS case.
534  *
535  * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
536  * is done when the conn is inserted into the drain list (conn_drain_insert())
537  * and cleared when the conn is removed from the it (conn_drain_remove()).
538  *
539  * IPQOS notes:
540  *
541  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
542  * and IPQoS modules. IPPF includes hooks in IP at different control points
543  * (callout positions) which direct packets to IPQoS modules for policy
544  * processing. Policies, if present, are global.
545  *
546  * The callout positions are located in the following paths:
547  *		o local_in (packets destined for this host)
548  *		o local_out (packets orginating from this host )
549  *		o fwd_in  (packets forwarded by this m/c - inbound)
550  *		o fwd_out (packets forwarded by this m/c - outbound)
551  * Hooks at these callout points can be enabled/disabled using the ndd variable
552  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
553  * By default all the callout positions are enabled.
554  *
555  * Outbound (local_out)
556  * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
557  *
558  * Inbound (local_in)
559  * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
560  *
561  * Forwarding (in and out)
562  * Hooks are placed in ire_recv_forward_v4/v6.
563  *
564  * IP Policy Framework processing (IPPF processing)
565  * Policy processing for a packet is initiated by ip_process, which ascertains
566  * that the classifier (ipgpc) is loaded and configured, failing which the
567  * packet resumes normal processing in IP. If the clasifier is present, the
568  * packet is acted upon by one or more IPQoS modules (action instances), per
569  * filters configured in ipgpc and resumes normal IP processing thereafter.
570  * An action instance can drop a packet in course of its processing.
571  *
572  * Zones notes:
573  *
574  * The partitioning rules for networking are as follows:
575  * 1) Packets coming from a zone must have a source address belonging to that
576  * zone.
577  * 2) Packets coming from a zone can only be sent on a physical interface on
578  * which the zone has an IP address.
579  * 3) Between two zones on the same machine, packet delivery is only allowed if
580  * there's a matching route for the destination and zone in the forwarding
581  * table.
582  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
583  * different zones can bind to the same port with the wildcard address
584  * (INADDR_ANY).
585  *
586  * The granularity of interface partitioning is at the logical interface level.
587  * Therefore, every zone has its own IP addresses, and incoming packets can be
588  * attributed to a zone unambiguously. A logical interface is placed into a zone
589  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
590  * structure. Rule (1) is implemented by modifying the source address selection
591  * algorithm so that the list of eligible addresses is filtered based on the
592  * sending process zone.
593  *
594  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
595  * across all zones, depending on their type. Here is the break-up:
596  *
597  * IRE type				Shared/exclusive
598  * --------				----------------
599  * IRE_BROADCAST			Exclusive
600  * IRE_DEFAULT (default routes)		Shared (*)
601  * IRE_LOCAL				Exclusive (x)
602  * IRE_LOOPBACK				Exclusive
603  * IRE_PREFIX (net routes)		Shared (*)
604  * IRE_IF_NORESOLVER (interface routes)	Exclusive
605  * IRE_IF_RESOLVER (interface routes)	Exclusive
606  * IRE_IF_CLONE (interface routes)	Exclusive
607  * IRE_HOST (host routes)		Shared (*)
608  *
609  * (*) A zone can only use a default or off-subnet route if the gateway is
610  * directly reachable from the zone, that is, if the gateway's address matches
611  * one of the zone's logical interfaces.
612  *
613  * (x) IRE_LOCAL are handled a bit differently.
614  * When ip_restrict_interzone_loopback is set (the default),
615  * ire_route_recursive restricts loopback using an IRE_LOCAL
616  * between zone to the case when L2 would have conceptually looped the packet
617  * back, i.e. the loopback which is required since neither Ethernet drivers
618  * nor Ethernet hardware loops them back. This is the case when the normal
619  * routes (ignoring IREs with different zoneids) would send out the packet on
620  * the same ill as the ill with which is IRE_LOCAL is associated.
621  *
622  * Multiple zones can share a common broadcast address; typically all zones
623  * share the 255.255.255.255 address. Incoming as well as locally originated
624  * broadcast packets must be dispatched to all the zones on the broadcast
625  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
626  * since some zones may not be on the 10.16.72/24 network. To handle this, each
627  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
628  * sent to every zone that has an IRE_BROADCAST entry for the destination
629  * address on the input ill, see ip_input_broadcast().
630  *
631  * Applications in different zones can join the same multicast group address.
632  * The same logic applies for multicast as for broadcast. ip_input_multicast
633  * dispatches packets to all zones that have members on the physical interface.
634  */
635 
636 /*
637  * Squeue Fanout flags:
638  *	0: No fanout.
639  *	1: Fanout across all squeues
640  */
641 boolean_t	ip_squeue_fanout = 0;
642 
643 /*
644  * Maximum dups allowed per packet.
645  */
646 uint_t ip_max_frag_dups = 10;
647 
648 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
649 		    cred_t *credp, boolean_t isv6);
650 static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);
651 
652 static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
653 static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
654 static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
655     ip_recv_attr_t *);
656 static void	icmp_options_update(ipha_t *);
657 static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
658 static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
659 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
660 static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
661     ip_recv_attr_t *);
662 static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
663 static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
664     ip_recv_attr_t *);
665 
666 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
667 char		*ip_dot_addr(ipaddr_t, char *);
668 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
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 		/* FALLTHROUGH */
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 	}
2286 	/* FALLTHROUGH */
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 		/* FALLTHROUGH */
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 	 * For multirouted IPv6 packets, the IP layer will insert a 8-byte
3862 	 * fragment header in every packet. We compensate for those cases by
3863 	 * returning a smaller path MTU to the ULP.
3864 	 *
3865 	 * In the case of CGTP then ip_output will add a fragment header.
3866 	 * Make sure there is room for it by telling a smaller number
3867 	 * to the transport.
3868 	 *
3869 	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
3870 	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
3871 	 * which is the size of the packets it can send.
3872 	 */
3873 	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
3874 		if ((ire->ire_flags & RTF_MULTIRT) ||
3875 		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
3876 			pmtu -= sizeof (ip6_frag_t);
3877 			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
3878 		}
3879 	}
3880 
3881 	return (pmtu);
3882 }
3883 
3884 /*
3885  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
3886  * the final piece where we don't.  Return a pointer to the first mblk in the
3887  * result, and update the pointer to the next mblk to chew on.  If anything
3888  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
3889  * NULL pointer.
3890  */
3891 mblk_t *
3892 ip_carve_mp(mblk_t **mpp, ssize_t len)
3893 {
3894 	mblk_t	*mp0;
3895 	mblk_t	*mp1;
3896 	mblk_t	*mp2;
3897 
3898 	if (!len || !mpp || !(mp0 = *mpp))
3899 		return (NULL);
3900 	/* If we aren't going to consume the first mblk, we need a dup. */
3901 	if (mp0->b_wptr - mp0->b_rptr > len) {
3902 		mp1 = dupb(mp0);
3903 		if (mp1) {
3904 			/* Partition the data between the two mblks. */
3905 			mp1->b_wptr = mp1->b_rptr + len;
3906 			mp0->b_rptr = mp1->b_wptr;
3907 			/*
3908 			 * after adjustments if mblk not consumed is now
3909 			 * unaligned, try to align it. If this fails free
3910 			 * all messages and let upper layer recover.
3911 			 */
3912 			if (!OK_32PTR(mp0->b_rptr)) {
3913 				if (!pullupmsg(mp0, -1)) {
3914 					freemsg(mp0);
3915 					freemsg(mp1);
3916 					*mpp = NULL;
3917 					return (NULL);
3918 				}
3919 			}
3920 		}
3921 		return (mp1);
3922 	}
3923 	/* Eat through as many mblks as we need to get len bytes. */
3924 	len -= mp0->b_wptr - mp0->b_rptr;
3925 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
3926 		if (mp2->b_wptr - mp2->b_rptr > len) {
3927 			/*
3928 			 * We won't consume the entire last mblk.  Like
3929 			 * above, dup and partition it.
3930 			 */
3931 			mp1->b_cont = dupb(mp2);
3932 			mp1 = mp1->b_cont;
3933 			if (!mp1) {
3934 				/*
3935 				 * Trouble.  Rather than go to a lot of
3936 				 * trouble to clean up, we free the messages.
3937 				 * This won't be any worse than losing it on
3938 				 * the wire.
3939 				 */
3940 				freemsg(mp0);
3941 				freemsg(mp2);
3942 				*mpp = NULL;
3943 				return (NULL);
3944 			}
3945 			mp1->b_wptr = mp1->b_rptr + len;
3946 			mp2->b_rptr = mp1->b_wptr;
3947 			/*
3948 			 * after adjustments if mblk not consumed is now
3949 			 * unaligned, try to align it. If this fails free
3950 			 * all messages and let upper layer recover.
3951 			 */
3952 			if (!OK_32PTR(mp2->b_rptr)) {
3953 				if (!pullupmsg(mp2, -1)) {
3954 					freemsg(mp0);
3955 					freemsg(mp2);
3956 					*mpp = NULL;
3957 					return (NULL);
3958 				}
3959 			}
3960 			*mpp = mp2;
3961 			return (mp0);
3962 		}
3963 		/* Decrement len by the amount we just got. */
3964 		len -= mp2->b_wptr - mp2->b_rptr;
3965 	}
3966 	/*
3967 	 * len should be reduced to zero now.  If not our caller has
3968 	 * screwed up.
3969 	 */
3970 	if (len) {
3971 		/* Shouldn't happen! */
3972 		freemsg(mp0);
3973 		*mpp = NULL;
3974 		return (NULL);
3975 	}
3976 	/*
3977 	 * We consumed up to exactly the end of an mblk.  Detach the part
3978 	 * we are returning from the rest of the chain.
3979 	 */
3980 	mp1->b_cont = NULL;
3981 	*mpp = mp2;
3982 	return (mp0);
3983 }
3984 
3985 /* The ill stream is being unplumbed. Called from ip_close */
3986 int
3987 ip_modclose(ill_t *ill)
3988 {
3989 	boolean_t success;
3990 	ipsq_t	*ipsq;
3991 	ipif_t	*ipif;
3992 	queue_t	*q = ill->ill_rq;
3993 	ip_stack_t	*ipst = ill->ill_ipst;
3994 	int	i;
3995 	arl_ill_common_t *ai = ill->ill_common;
3996 
3997 	/*
3998 	 * The punlink prior to this may have initiated a capability
3999 	 * negotiation. But ipsq_enter will block until that finishes or
4000 	 * times out.
4001 	 */
4002 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
4003 
4004 	/*
4005 	 * Open/close/push/pop is guaranteed to be single threaded
4006 	 * per stream by STREAMS. FS guarantees that all references
4007 	 * from top are gone before close is called. So there can't
4008 	 * be another close thread that has set CONDEMNED on this ill.
4009 	 * and cause ipsq_enter to return failure.
4010 	 */
4011 	ASSERT(success);
4012 	ipsq = ill->ill_phyint->phyint_ipsq;
4013 
4014 	/*
4015 	 * Mark it condemned. No new reference will be made to this ill.
4016 	 * Lookup functions will return an error. Threads that try to
4017 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
4018 	 * that the refcnt will drop down to zero.
4019 	 */
4020 	mutex_enter(&ill->ill_lock);
4021 	ill->ill_state_flags |= ILL_CONDEMNED;
4022 	for (ipif = ill->ill_ipif; ipif != NULL;
4023 	    ipif = ipif->ipif_next) {
4024 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
4025 	}
4026 	/*
4027 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
4028 	 * returns  error if ILL_CONDEMNED is set
4029 	 */
4030 	cv_broadcast(&ill->ill_cv);
4031 	mutex_exit(&ill->ill_lock);
4032 
4033 	/*
4034 	 * Send all the deferred DLPI messages downstream which came in
4035 	 * during the small window right before ipsq_enter(). We do this
4036 	 * without waiting for the ACKs because all the ACKs for M_PROTO
4037 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
4038 	 */
4039 	ill_dlpi_send_deferred(ill);
4040 
4041 	/*
4042 	 * Shut down fragmentation reassembly.
4043 	 * ill_frag_timer won't start a timer again.
4044 	 * Now cancel any existing timer
4045 	 */
4046 	(void) untimeout(ill->ill_frag_timer_id);
4047 	(void) ill_frag_timeout(ill, 0);
4048 
4049 	/*
4050 	 * Call ill_delete to bring down the ipifs, ilms and ill on
4051 	 * this ill. Then wait for the refcnts to drop to zero.
4052 	 * ill_is_freeable checks whether the ill is really quiescent.
4053 	 * Then make sure that threads that are waiting to enter the
4054 	 * ipsq have seen the error returned by ipsq_enter and have
4055 	 * gone away. Then we call ill_delete_tail which does the
4056 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
4057 	 */
4058 	ill_delete(ill);
4059 	mutex_enter(&ill->ill_lock);
4060 	while (!ill_is_freeable(ill))
4061 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4062 
4063 	while (ill->ill_waiters)
4064 		cv_wait(&ill->ill_cv, &ill->ill_lock);
4065 
4066 	mutex_exit(&ill->ill_lock);
4067 
4068 	/*
4069 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
4070 	 * it held until the end of the function since the cleanup
4071 	 * below needs to be able to use the ip_stack_t.
4072 	 */
4073 	netstack_hold(ipst->ips_netstack);
4074 
4075 	/* qprocsoff is done via ill_delete_tail */
4076 	ill_delete_tail(ill);
4077 	/*
4078 	 * synchronously wait for arp stream to unbind. After this, we
4079 	 * cannot get any data packets up from the driver.
4080 	 */
4081 	arp_unbind_complete(ill);
4082 	ASSERT(ill->ill_ipst == NULL);
4083 
4084 	/*
4085 	 * Walk through all conns and qenable those that have queued data.
4086 	 * Close synchronization needs this to
4087 	 * be done to ensure that all upper layers blocked
4088 	 * due to flow control to the closing device
4089 	 * get unblocked.
4090 	 */
4091 	ip1dbg(("ip_wsrv: walking\n"));
4092 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
4093 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
4094 	}
4095 
4096 	/*
4097 	 * ai can be null if this is an IPv6 ill, or if the IPv4
4098 	 * stream is being torn down before ARP was plumbed (e.g.,
4099 	 * /sbin/ifconfig plumbing a stream twice, and encountering
4100 	 * an error
4101 	 */
4102 	if (ai != NULL) {
4103 		ASSERT(!ill->ill_isv6);
4104 		mutex_enter(&ai->ai_lock);
4105 		ai->ai_ill = NULL;
4106 		if (ai->ai_arl == NULL) {
4107 			mutex_destroy(&ai->ai_lock);
4108 			kmem_free(ai, sizeof (*ai));
4109 		} else {
4110 			cv_signal(&ai->ai_ill_unplumb_done);
4111 			mutex_exit(&ai->ai_lock);
4112 		}
4113 	}
4114 
4115 	mutex_enter(&ipst->ips_ip_mi_lock);
4116 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
4117 	mutex_exit(&ipst->ips_ip_mi_lock);
4118 
4119 	/*
4120 	 * credp could be null if the open didn't succeed and ip_modopen
4121 	 * itself calls ip_close.
4122 	 */
4123 	if (ill->ill_credp != NULL)
4124 		crfree(ill->ill_credp);
4125 
4126 	mutex_destroy(&ill->ill_saved_ire_lock);
4127 	mutex_destroy(&ill->ill_lock);
4128 	rw_destroy(&ill->ill_mcast_lock);
4129 	mutex_destroy(&ill->ill_mcast_serializer);
4130 	list_destroy(&ill->ill_nce);
4131 
4132 	/*
4133 	 * Now we are done with the module close pieces that
4134 	 * need the netstack_t.
4135 	 */
4136 	netstack_rele(ipst->ips_netstack);
4137 
4138 	mi_close_free((IDP)ill);
4139 	q->q_ptr = WR(q)->q_ptr = NULL;
4140 
4141 	ipsq_exit(ipsq);
4142 
4143 	return (0);
4144 }
4145 
4146 /*
4147  * This is called as part of close() for IP, UDP, ICMP, and RTS
4148  * in order to quiesce the conn.
4149  */
4150 void
4151 ip_quiesce_conn(conn_t *connp)
4152 {
4153 	boolean_t	drain_cleanup_reqd = B_FALSE;
4154 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4155 	boolean_t	ilg_cleanup_reqd = B_FALSE;
4156 	ip_stack_t	*ipst;
4157 
4158 	ASSERT(!IPCL_IS_TCP(connp));
4159 	ipst = connp->conn_netstack->netstack_ip;
4160 
4161 	/*
4162 	 * Mark the conn as closing, and this conn must not be
4163 	 * inserted in future into any list. Eg. conn_drain_insert(),
4164 	 * won't insert this conn into the conn_drain_list.
4165 	 *
4166 	 * conn_idl, and conn_ilg cannot get set henceforth.
4167 	 */
4168 	mutex_enter(&connp->conn_lock);
4169 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
4170 	connp->conn_state_flags |= CONN_CLOSING;
4171 	if (connp->conn_idl != NULL)
4172 		drain_cleanup_reqd = B_TRUE;
4173 	if (connp->conn_oper_pending_ill != NULL)
4174 		conn_ioctl_cleanup_reqd = B_TRUE;
4175 	if (connp->conn_dhcpinit_ill != NULL) {
4176 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
4177 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
4178 		ill_set_inputfn(connp->conn_dhcpinit_ill);
4179 		connp->conn_dhcpinit_ill = NULL;
4180 	}
4181 	if (connp->conn_ilg != NULL)
4182 		ilg_cleanup_reqd = B_TRUE;
4183 	mutex_exit(&connp->conn_lock);
4184 
4185 	if (conn_ioctl_cleanup_reqd)
4186 		conn_ioctl_cleanup(connp);
4187 
4188 	if (is_system_labeled() && connp->conn_anon_port) {
4189 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4190 		    connp->conn_mlp_type, connp->conn_proto,
4191 		    ntohs(connp->conn_lport), B_FALSE);
4192 		connp->conn_anon_port = 0;
4193 	}
4194 	connp->conn_mlp_type = mlptSingle;
4195 
4196 	/*
4197 	 * Remove this conn from any fanout list it is on.
4198 	 * and then wait for any threads currently operating
4199 	 * on this endpoint to finish
4200 	 */
4201 	ipcl_hash_remove(connp);
4202 
4203 	/*
4204 	 * Remove this conn from the drain list, and do any other cleanup that
4205 	 * may be required.  (TCP conns are never flow controlled, and
4206 	 * conn_idl will be NULL.)
4207 	 */
4208 	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
4209 		idl_t *idl = connp->conn_idl;
4210 
4211 		mutex_enter(&idl->idl_lock);
4212 		conn_drain(connp, B_TRUE);
4213 		mutex_exit(&idl->idl_lock);
4214 	}
4215 
4216 	if (connp == ipst->ips_ip_g_mrouter)
4217 		(void) ip_mrouter_done(ipst);
4218 
4219 	if (ilg_cleanup_reqd)
4220 		ilg_delete_all(connp);
4221 
4222 	/*
4223 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
4224 	 * callers from write side can't be there now because close
4225 	 * is in progress. The only other caller is ipcl_walk
4226 	 * which checks for the condemned flag.
4227 	 */
4228 	mutex_enter(&connp->conn_lock);
4229 	connp->conn_state_flags |= CONN_CONDEMNED;
4230 	while (connp->conn_ref != 1)
4231 		cv_wait(&connp->conn_cv, &connp->conn_lock);
4232 	connp->conn_state_flags |= CONN_QUIESCED;
4233 	mutex_exit(&connp->conn_lock);
4234 }
4235 
4236 /* ARGSUSED */
4237 int
4238 ip_close(queue_t *q, int flags, cred_t *credp __unused)
4239 {
4240 	conn_t		*connp;
4241 
4242 	/*
4243 	 * Call the appropriate delete routine depending on whether this is
4244 	 * a module or device.
4245 	 */
4246 	if (WR(q)->q_next != NULL) {
4247 		/* This is a module close */
4248 		return (ip_modclose((ill_t *)q->q_ptr));
4249 	}
4250 
4251 	connp = q->q_ptr;
4252 	ip_quiesce_conn(connp);
4253 
4254 	qprocsoff(q);
4255 
4256 	/*
4257 	 * Now we are truly single threaded on this stream, and can
4258 	 * delete the things hanging off the connp, and finally the connp.
4259 	 * We removed this connp from the fanout list, it cannot be
4260 	 * accessed thru the fanouts, and we already waited for the
4261 	 * conn_ref to drop to 0. We are already in close, so
4262 	 * there cannot be any other thread from the top. qprocsoff
4263 	 * has completed, and service has completed or won't run in
4264 	 * future.
4265 	 */
4266 	ASSERT(connp->conn_ref == 1);
4267 
4268 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4269 
4270 	connp->conn_ref--;
4271 	ipcl_conn_destroy(connp);
4272 
4273 	q->q_ptr = WR(q)->q_ptr = NULL;
4274 	return (0);
4275 }
4276 
4277 /*
4278  * Wapper around putnext() so that ip_rts_request can merely use
4279  * conn_recv.
4280  */
4281 /*ARGSUSED2*/
4282 static void
4283 ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4284 {
4285 	conn_t *connp = (conn_t *)arg1;
4286 
4287 	putnext(connp->conn_rq, mp);
4288 }
4289 
4290 /* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
4291 /* ARGSUSED */
4292 static void
4293 ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4294 {
4295 	freemsg(mp);
4296 }
4297 
4298 /*
4299  * Called when the module is about to be unloaded
4300  */
4301 void
4302 ip_ddi_destroy(void)
4303 {
4304 	/* This needs to be called before destroying any transports. */
4305 	mutex_enter(&cpu_lock);
4306 	unregister_cpu_setup_func(ip_tp_cpu_update, NULL);
4307 	mutex_exit(&cpu_lock);
4308 
4309 	tnet_fini();
4310 
4311 	icmp_ddi_g_destroy();
4312 	rts_ddi_g_destroy();
4313 	udp_ddi_g_destroy();
4314 	sctp_ddi_g_destroy();
4315 	tcp_ddi_g_destroy();
4316 	ilb_ddi_g_destroy();
4317 	dce_g_destroy();
4318 	ipsec_policy_g_destroy();
4319 	ipcl_g_destroy();
4320 	ip_net_g_destroy();
4321 	ip_ire_g_fini();
4322 	inet_minor_destroy(ip_minor_arena_sa);
4323 #if defined(_LP64)
4324 	inet_minor_destroy(ip_minor_arena_la);
4325 #endif
4326 
4327 #ifdef DEBUG
4328 	list_destroy(&ip_thread_list);
4329 	rw_destroy(&ip_thread_rwlock);
4330 	tsd_destroy(&ip_thread_data);
4331 #endif
4332 
4333 	netstack_unregister(NS_IP);
4334 }
4335 
4336 /*
4337  * First step in cleanup.
4338  */
4339 /* ARGSUSED */
4340 static void
4341 ip_stack_shutdown(netstackid_t stackid, void *arg)
4342 {
4343 	ip_stack_t *ipst = (ip_stack_t *)arg;
4344 	kt_did_t ktid;
4345 
4346 #ifdef NS_DEBUG
4347 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
4348 #endif
4349 
4350 	/*
4351 	 * Perform cleanup for special interfaces (loopback and IPMP).
4352 	 */
4353 	ip_interface_cleanup(ipst);
4354 
4355 	/*
4356 	 * The *_hook_shutdown()s start the process of notifying any
4357 	 * consumers that things are going away.... nothing is destroyed.
4358 	 */
4359 	ipv4_hook_shutdown(ipst);
4360 	ipv6_hook_shutdown(ipst);
4361 	arp_hook_shutdown(ipst);
4362 
4363 	mutex_enter(&ipst->ips_capab_taskq_lock);
4364 	ktid = ipst->ips_capab_taskq_thread->t_did;
4365 	ipst->ips_capab_taskq_quit = B_TRUE;
4366 	cv_signal(&ipst->ips_capab_taskq_cv);
4367 	mutex_exit(&ipst->ips_capab_taskq_lock);
4368 
4369 	/*
4370 	 * In rare occurrences, particularly on virtual hardware where CPUs can
4371 	 * be de-scheduled, the thread that we just signaled will not run until
4372 	 * after we have gotten through parts of ip_stack_fini. If that happens
4373 	 * then we'll try to grab the ips_capab_taskq_lock as part of returning
4374 	 * from cv_wait which no longer exists.
4375 	 */
4376 	thread_join(ktid);
4377 }
4378 
4379 /*
4380  * Free the IP stack instance.
4381  */
4382 static void
4383 ip_stack_fini(netstackid_t stackid, void *arg)
4384 {
4385 	ip_stack_t *ipst = (ip_stack_t *)arg;
4386 	int ret;
4387 
4388 #ifdef NS_DEBUG
4389 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
4390 #endif
4391 	/*
4392 	 * At this point, all of the notifications that the events and
4393 	 * protocols are going away have been run, meaning that we can
4394 	 * now set about starting to clean things up.
4395 	 */
4396 	ipobs_fini(ipst);
4397 	ipv4_hook_destroy(ipst);
4398 	ipv6_hook_destroy(ipst);
4399 	arp_hook_destroy(ipst);
4400 	ip_net_destroy(ipst);
4401 
4402 	ipmp_destroy(ipst);
4403 
4404 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
4405 	ipst->ips_ip_mibkp = NULL;
4406 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
4407 	ipst->ips_icmp_mibkp = NULL;
4408 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
4409 	ipst->ips_ip_kstat = NULL;
4410 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
4411 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
4412 	ipst->ips_ip6_kstat = NULL;
4413 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
4414 
4415 	kmem_free(ipst->ips_propinfo_tbl,
4416 	    ip_propinfo_count * sizeof (mod_prop_info_t));
4417 	ipst->ips_propinfo_tbl = NULL;
4418 
4419 	dce_stack_destroy(ipst);
4420 	ip_mrouter_stack_destroy(ipst);
4421 
4422 	/*
4423 	 * Quiesce all of our timers. Note we set the quiesce flags before we
4424 	 * call untimeout. The slowtimers may actually kick off another instance
4425 	 * of the non-slow timers.
4426 	 */
4427 	mutex_enter(&ipst->ips_igmp_timer_lock);
4428 	ipst->ips_igmp_timer_quiesce = B_TRUE;
4429 	mutex_exit(&ipst->ips_igmp_timer_lock);
4430 
4431 	mutex_enter(&ipst->ips_mld_timer_lock);
4432 	ipst->ips_mld_timer_quiesce = B_TRUE;
4433 	mutex_exit(&ipst->ips_mld_timer_lock);
4434 
4435 	mutex_enter(&ipst->ips_igmp_slowtimeout_lock);
4436 	ipst->ips_igmp_slowtimeout_quiesce = B_TRUE;
4437 	mutex_exit(&ipst->ips_igmp_slowtimeout_lock);
4438 
4439 	mutex_enter(&ipst->ips_mld_slowtimeout_lock);
4440 	ipst->ips_mld_slowtimeout_quiesce = B_TRUE;
4441 	mutex_exit(&ipst->ips_mld_slowtimeout_lock);
4442 
4443 	ret = untimeout(ipst->ips_igmp_timeout_id);
4444 	if (ret == -1) {
4445 		ASSERT(ipst->ips_igmp_timeout_id == 0);
4446 	} else {
4447 		ASSERT(ipst->ips_igmp_timeout_id != 0);
4448 		ipst->ips_igmp_timeout_id = 0;
4449 	}
4450 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
4451 	if (ret == -1) {
4452 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
4453 	} else {
4454 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
4455 		ipst->ips_igmp_slowtimeout_id = 0;
4456 	}
4457 	ret = untimeout(ipst->ips_mld_timeout_id);
4458 	if (ret == -1) {
4459 		ASSERT(ipst->ips_mld_timeout_id == 0);
4460 	} else {
4461 		ASSERT(ipst->ips_mld_timeout_id != 0);
4462 		ipst->ips_mld_timeout_id = 0;
4463 	}
4464 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
4465 	if (ret == -1) {
4466 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
4467 	} else {
4468 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
4469 		ipst->ips_mld_slowtimeout_id = 0;
4470 	}
4471 
4472 	ip_ire_fini(ipst);
4473 	ip6_asp_free(ipst);
4474 	conn_drain_fini(ipst);
4475 	ipcl_destroy(ipst);
4476 
4477 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
4478 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
4479 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
4480 	ipst->ips_ndp4 = NULL;
4481 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
4482 	ipst->ips_ndp6 = NULL;
4483 
4484 	if (ipst->ips_loopback_ksp != NULL) {
4485 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
4486 		ipst->ips_loopback_ksp = NULL;
4487 	}
4488 
4489 	mutex_destroy(&ipst->ips_capab_taskq_lock);
4490 	cv_destroy(&ipst->ips_capab_taskq_cv);
4491 
4492 	rw_destroy(&ipst->ips_srcid_lock);
4493 
4494 	mutex_destroy(&ipst->ips_ip_mi_lock);
4495 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
4496 
4497 	mutex_destroy(&ipst->ips_igmp_timer_lock);
4498 	mutex_destroy(&ipst->ips_mld_timer_lock);
4499 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
4500 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
4501 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
4502 	rw_destroy(&ipst->ips_ill_g_lock);
4503 
4504 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
4505 	ipst->ips_phyint_g_list = NULL;
4506 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
4507 	ipst->ips_ill_g_heads = NULL;
4508 
4509 	ldi_ident_release(ipst->ips_ldi_ident);
4510 	kmem_free(ipst, sizeof (*ipst));
4511 }
4512 
4513 /*
4514  * This function is called from the TSD destructor, and is used to debug
4515  * reference count issues in IP. See block comment in <inet/ip_if.h> for
4516  * details.
4517  */
4518 static void
4519 ip_thread_exit(void *phash)
4520 {
4521 	th_hash_t *thh = phash;
4522 
4523 	rw_enter(&ip_thread_rwlock, RW_WRITER);
4524 	list_remove(&ip_thread_list, thh);
4525 	rw_exit(&ip_thread_rwlock);
4526 	mod_hash_destroy_hash(thh->thh_hash);
4527 	kmem_free(thh, sizeof (*thh));
4528 }
4529 
4530 /*
4531  * Called when the IP kernel module is loaded into the kernel
4532  */
4533 void
4534 ip_ddi_init(void)
4535 {
4536 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
4537 
4538 	/*
4539 	 * For IP and TCP the minor numbers should start from 2 since we have 4
4540 	 * initial devices: ip, ip6, tcp, tcp6.
4541 	 */
4542 	/*
4543 	 * If this is a 64-bit kernel, then create two separate arenas -
4544 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
4545 	 * other for socket apps in the range 2^^18 through 2^^32-1.
4546 	 */
4547 	ip_minor_arena_la = NULL;
4548 	ip_minor_arena_sa = NULL;
4549 #if defined(_LP64)
4550 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4551 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
4552 		cmn_err(CE_PANIC,
4553 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4554 	}
4555 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
4556 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
4557 		cmn_err(CE_PANIC,
4558 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
4559 	}
4560 #else
4561 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
4562 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
4563 		cmn_err(CE_PANIC,
4564 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
4565 	}
4566 #endif
4567 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
4568 
4569 	ipcl_g_init();
4570 	ip_ire_g_init();
4571 	ip_net_g_init();
4572 
4573 #ifdef DEBUG
4574 	tsd_create(&ip_thread_data, ip_thread_exit);
4575 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
4576 	list_create(&ip_thread_list, sizeof (th_hash_t),
4577 	    offsetof(th_hash_t, thh_link));
4578 #endif
4579 	ipsec_policy_g_init();
4580 	tcp_ddi_g_init();
4581 	sctp_ddi_g_init();
4582 	dce_g_init();
4583 
4584 	/*
4585 	 * We want to be informed each time a stack is created or
4586 	 * destroyed in the kernel, so we can maintain the
4587 	 * set of udp_stack_t's.
4588 	 */
4589 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
4590 	    ip_stack_fini);
4591 
4592 	tnet_init();
4593 
4594 	udp_ddi_g_init();
4595 	rts_ddi_g_init();
4596 	icmp_ddi_g_init();
4597 	ilb_ddi_g_init();
4598 
4599 	/* This needs to be called after all transports are initialized. */
4600 	mutex_enter(&cpu_lock);
4601 	register_cpu_setup_func(ip_tp_cpu_update, NULL);
4602 	mutex_exit(&cpu_lock);
4603 }
4604 
4605 /*
4606  * Initialize the IP stack instance.
4607  */
4608 static void *
4609 ip_stack_init(netstackid_t stackid, netstack_t *ns)
4610 {
4611 	ip_stack_t	*ipst;
4612 	size_t		arrsz;
4613 	major_t		major;
4614 
4615 #ifdef NS_DEBUG
4616 	printf("ip_stack_init(stack %d)\n", stackid);
4617 #endif
4618 
4619 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
4620 	ipst->ips_netstack = ns;
4621 
4622 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
4623 	    KM_SLEEP);
4624 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
4625 	    KM_SLEEP);
4626 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4627 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
4628 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4629 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
4630 
4631 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4632 	ipst->ips_igmp_deferred_next = INFINITY;
4633 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
4634 	ipst->ips_mld_deferred_next = INFINITY;
4635 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4636 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
4637 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
4638 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
4639 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
4640 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
4641 
4642 	ipcl_init(ipst);
4643 	ip_ire_init(ipst);
4644 	ip6_asp_init(ipst);
4645 	ipif_init(ipst);
4646 	conn_drain_init(ipst);
4647 	ip_mrouter_stack_init(ipst);
4648 	dce_stack_init(ipst);
4649 
4650 	ipst->ips_ip_multirt_log_interval = 1000;
4651 
4652 	ipst->ips_ill_index = 1;
4653 
4654 	ipst->ips_saved_ip_forwarding = -1;
4655 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
4656 
4657 	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
4658 	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
4659 	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);
4660 
4661 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
4662 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
4663 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
4664 	ipst->ips_ip6_kstat =
4665 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
4666 
4667 	ipst->ips_ip_src_id = 1;
4668 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
4669 
4670 	ipst->ips_src_generation = SRC_GENERATION_INITIAL;
4671 
4672 	ip_net_init(ipst, ns);
4673 	ipv4_hook_init(ipst);
4674 	ipv6_hook_init(ipst);
4675 	arp_hook_init(ipst);
4676 	ipmp_init(ipst);
4677 	ipobs_init(ipst);
4678 
4679 	/*
4680 	 * Create the taskq dispatcher thread and initialize related stuff.
4681 	 */
4682 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
4683 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
4684 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
4685 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
4686 
4687 	major = mod_name_to_major(INET_NAME);
4688 	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
4689 	return (ipst);
4690 }
4691 
4692 /*
4693  * Allocate and initialize a DLPI template of the specified length.  (May be
4694  * called as writer.)
4695  */
4696 mblk_t *
4697 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
4698 {
4699 	mblk_t	*mp;
4700 
4701 	mp = allocb(len, BPRI_MED);
4702 	if (!mp)
4703 		return (NULL);
4704 
4705 	/*
4706 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
4707 	 * of which we don't seem to use) are sent with M_PCPROTO, and
4708 	 * that other DLPI are M_PROTO.
4709 	 */
4710 	if (prim == DL_INFO_REQ) {
4711 		mp->b_datap->db_type = M_PCPROTO;
4712 	} else {
4713 		mp->b_datap->db_type = M_PROTO;
4714 	}
4715 
4716 	mp->b_wptr = mp->b_rptr + len;
4717 	bzero(mp->b_rptr, len);
4718 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
4719 	return (mp);
4720 }
4721 
4722 /*
4723  * Allocate and initialize a DLPI notification.  (May be called as writer.)
4724  */
4725 mblk_t *
4726 ip_dlnotify_alloc(uint_t notification, uint_t data)
4727 {
4728 	dl_notify_ind_t	*notifyp;
4729 	mblk_t		*mp;
4730 
4731 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4732 		return (NULL);
4733 
4734 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4735 	notifyp->dl_notification = notification;
4736 	notifyp->dl_data = data;
4737 	return (mp);
4738 }
4739 
4740 mblk_t *
4741 ip_dlnotify_alloc2(uint_t notification, uint_t data1, uint_t data2)
4742 {
4743 	dl_notify_ind_t	*notifyp;
4744 	mblk_t		*mp;
4745 
4746 	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
4747 		return (NULL);
4748 
4749 	notifyp = (dl_notify_ind_t *)mp->b_rptr;
4750 	notifyp->dl_notification = notification;
4751 	notifyp->dl_data1 = data1;
4752 	notifyp->dl_data2 = data2;
4753 	return (mp);
4754 }
4755 
4756 /*
4757  * Debug formatting routine.  Returns a character string representation of the
4758  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
4759  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
4760  *
4761  * Once the ndd table-printing interfaces are removed, this can be changed to
4762  * standard dotted-decimal form.
4763  */
4764 char *
4765 ip_dot_addr(ipaddr_t addr, char *buf)
4766 {
4767 	uint8_t *ap = (uint8_t *)&addr;
4768 
4769 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
4770 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
4771 	return (buf);
4772 }
4773 
4774 /*
4775  * Write the given MAC address as a printable string in the usual colon-
4776  * separated format.
4777  */
4778 const char *
4779 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
4780 {
4781 	char *bp;
4782 
4783 	if (alen == 0 || buflen < 4)
4784 		return ("?");
4785 	bp = buf;
4786 	for (;;) {
4787 		/*
4788 		 * If there are more MAC address bytes available, but we won't
4789 		 * have any room to print them, then add "..." to the string
4790 		 * instead.  See below for the 'magic number' explanation.
4791 		 */
4792 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
4793 			(void) strcpy(bp, "...");
4794 			break;
4795 		}
4796 		(void) sprintf(bp, "%02x", *addr++);
4797 		bp += 2;
4798 		if (--alen == 0)
4799 			break;
4800 		*bp++ = ':';
4801 		buflen -= 3;
4802 		/*
4803 		 * At this point, based on the first 'if' statement above,
4804 		 * either alen == 1 and buflen >= 3, or alen > 1 and
4805 		 * buflen >= 4.  The first case leaves room for the final "xx"
4806 		 * number and trailing NUL byte.  The second leaves room for at
4807 		 * least "...".  Thus the apparently 'magic' numbers chosen for
4808 		 * that statement.
4809 		 */
4810 	}
4811 	return (buf);
4812 }
4813 
4814 /*
4815  * Called when it is conceptually a ULP that would sent the packet
4816  * e.g., port unreachable and protocol unreachable. Check that the packet
4817  * would have passed the IPsec global policy before sending the error.
4818  *
4819  * Send an ICMP error after patching up the packet appropriately.
4820  * Uses ip_drop_input and bumps the appropriate MIB.
4821  */
4822 void
4823 ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
4824     ip_recv_attr_t *ira)
4825 {
4826 	ipha_t		*ipha;
4827 	boolean_t	secure;
4828 	ill_t		*ill = ira->ira_ill;
4829 	ip_stack_t	*ipst = ill->ill_ipst;
4830 	netstack_t	*ns = ipst->ips_netstack;
4831 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
4832 
4833 	secure = ira->ira_flags & IRAF_IPSEC_SECURE;
4834 
4835 	/*
4836 	 * We are generating an icmp error for some inbound packet.
4837 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
4838 	 * Before we generate an error, check with global policy
4839 	 * to see whether this is allowed to enter the system. As
4840 	 * there is no "conn", we are checking with global policy.
4841 	 */
4842 	ipha = (ipha_t *)mp->b_rptr;
4843 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
4844 		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
4845 		if (mp == NULL)
4846 			return;
4847 	}
4848 
4849 	/* We never send errors for protocols that we do implement */
4850 	if (ira->ira_protocol == IPPROTO_ICMP ||
4851 	    ira->ira_protocol == IPPROTO_IGMP) {
4852 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4853 		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
4854 		freemsg(mp);
4855 		return;
4856 	}
4857 	/*
4858 	 * Have to correct checksum since
4859 	 * the packet might have been
4860 	 * fragmented and the reassembly code in ip_rput
4861 	 * does not restore the IP checksum.
4862 	 */
4863 	ipha->ipha_hdr_checksum = 0;
4864 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
4865 
4866 	switch (icmp_type) {
4867 	case ICMP_DEST_UNREACHABLE:
4868 		switch (icmp_code) {
4869 		case ICMP_PROTOCOL_UNREACHABLE:
4870 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
4871 			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
4872 			break;
4873 		case ICMP_PORT_UNREACHABLE:
4874 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
4875 			ip_drop_input("ipIfStatsNoPorts", mp, ill);
4876 			break;
4877 		}
4878 
4879 		icmp_unreachable(mp, icmp_code, ira);
4880 		break;
4881 	default:
4882 #ifdef DEBUG
4883 		panic("ip_fanout_send_icmp_v4: wrong type");
4884 		/*NOTREACHED*/
4885 #else
4886 		freemsg(mp);
4887 		break;
4888 #endif
4889 	}
4890 }
4891 
4892 /*
4893  * Used to send an ICMP error message when a packet is received for
4894  * a protocol that is not supported. The mblk passed as argument
4895  * is consumed by this function.
4896  */
4897 void
4898 ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
4899 {
4900 	ipha_t		*ipha;
4901 
4902 	ipha = (ipha_t *)mp->b_rptr;
4903 	if (ira->ira_flags & IRAF_IS_IPV4) {
4904 		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
4905 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
4906 		    ICMP_PROTOCOL_UNREACHABLE, ira);
4907 	} else {
4908 		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
4909 		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
4910 		    ICMP6_PARAMPROB_NEXTHEADER, ira);
4911 	}
4912 }
4913 
4914 /*
4915  * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
4916  * Handles IPv4 and IPv6.
4917  * We are responsible for disposing of mp, such as by freemsg() or putnext()
4918  * Caller is responsible for dropping references to the conn.
4919  */
4920 void
4921 ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
4922     ip_recv_attr_t *ira)
4923 {
4924 	ill_t		*ill = ira->ira_ill;
4925 	ip_stack_t	*ipst = ill->ill_ipst;
4926 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
4927 	boolean_t	secure;
4928 	uint_t		protocol = ira->ira_protocol;
4929 	iaflags_t	iraflags = ira->ira_flags;
4930 	queue_t		*rq;
4931 
4932 	secure = iraflags & IRAF_IPSEC_SECURE;
4933 
4934 	rq = connp->conn_rq;
4935 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
4936 		switch (protocol) {
4937 		case IPPROTO_ICMPV6:
4938 			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
4939 			break;
4940 		case IPPROTO_ICMP:
4941 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
4942 			break;
4943 		default:
4944 			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
4945 			break;
4946 		}
4947 		freemsg(mp);
4948 		return;
4949 	}
4950 
4951 	ASSERT(!(IPCL_IS_IPTUN(connp)));
4952 
4953 	if (((iraflags & IRAF_IS_IPV4) ?
4954 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
4955 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
4956 	    secure) {
4957 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
4958 		    ip6h, ira);
4959 		if (mp == NULL) {
4960 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
4961 			/* Note that mp is NULL */
4962 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
4963 			return;
4964 		}
4965 	}
4966 
4967 	if (iraflags & IRAF_ICMP_ERROR) {
4968 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
4969 	} else {
4970 		ill_t *rill = ira->ira_rill;
4971 
4972 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
4973 		ira->ira_ill = ira->ira_rill = NULL;
4974 		/* Send it upstream */
4975 		(connp->conn_recv)(connp, mp, NULL, ira);
4976 		ira->ira_ill = ill;
4977 		ira->ira_rill = rill;
4978 	}
4979 }
4980 
4981 /*
4982  * Handle protocols with which IP is less intimate.  There
4983  * can be more than one stream bound to a particular
4984  * protocol.  When this is the case, normally each one gets a copy
4985  * of any incoming packets.
4986  *
4987  * IPsec NOTE :
4988  *
4989  * Don't allow a secure packet going up a non-secure connection.
4990  * We don't allow this because
4991  *
4992  * 1) Reply might go out in clear which will be dropped at
4993  *    the sending side.
4994  * 2) If the reply goes out in clear it will give the
4995  *    adversary enough information for getting the key in
4996  *    most of the cases.
4997  *
4998  * Moreover getting a secure packet when we expect clear
4999  * implies that SA's were added without checking for
5000  * policy on both ends. This should not happen once ISAKMP
5001  * is used to negotiate SAs as SAs will be added only after
5002  * verifying the policy.
5003  *
5004  * Zones notes:
5005  * Earlier in ip_input on a system with multiple shared-IP zones we
5006  * duplicate the multicast and broadcast packets and send them up
5007  * with each explicit zoneid that exists on that ill.
5008  * This means that here we can match the zoneid with SO_ALLZONES being special.
5009  */
5010 void
5011 ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
5012 {
5013 	mblk_t		*mp1;
5014 	ipaddr_t	laddr;
5015 	conn_t		*connp, *first_connp, *next_connp;
5016 	connf_t		*connfp;
5017 	ill_t		*ill = ira->ira_ill;
5018 	ip_stack_t	*ipst = ill->ill_ipst;
5019 
5020 	laddr = ipha->ipha_dst;
5021 
5022 	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
5023 	mutex_enter(&connfp->connf_lock);
5024 	connp = connfp->connf_head;
5025 	for (connp = connfp->connf_head; connp != NULL;
5026 	    connp = connp->conn_next) {
5027 		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5028 		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5029 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5030 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
5031 			break;
5032 		}
5033 	}
5034 
5035 	if (connp == NULL) {
5036 		/*
5037 		 * No one bound to these addresses.  Is
5038 		 * there a client that wants all
5039 		 * unclaimed datagrams?
5040 		 */
5041 		mutex_exit(&connfp->connf_lock);
5042 		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
5043 		    ICMP_PROTOCOL_UNREACHABLE, ira);
5044 		return;
5045 	}
5046 
5047 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5048 
5049 	CONN_INC_REF(connp);
5050 	first_connp = connp;
5051 	connp = connp->conn_next;
5052 
5053 	for (;;) {
5054 		while (connp != NULL) {
5055 			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
5056 			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
5057 			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5058 			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5059 			    ira, connp)))
5060 				break;
5061 			connp = connp->conn_next;
5062 		}
5063 
5064 		if (connp == NULL) {
5065 			/* No more interested clients */
5066 			connp = first_connp;
5067 			break;
5068 		}
5069 		if (((mp1 = dupmsg(mp)) == NULL) &&
5070 		    ((mp1 = copymsg(mp)) == NULL)) {
5071 			/* Memory allocation failed */
5072 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5073 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5074 			connp = first_connp;
5075 			break;
5076 		}
5077 
5078 		CONN_INC_REF(connp);
5079 		mutex_exit(&connfp->connf_lock);
5080 
5081 		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
5082 		    ira);
5083 
5084 		mutex_enter(&connfp->connf_lock);
5085 		/* Follow the next pointer before releasing the conn. */
5086 		next_connp = connp->conn_next;
5087 		CONN_DEC_REF(connp);
5088 		connp = next_connp;
5089 	}
5090 
5091 	/* Last one.  Send it upstream. */
5092 	mutex_exit(&connfp->connf_lock);
5093 
5094 	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);
5095 
5096 	CONN_DEC_REF(connp);
5097 }
5098 
5099 /*
5100  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
5101  * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
5102  * is not consumed.
5103  *
5104  * One of three things can happen, all of which affect the passed-in mblk:
5105  *
5106  * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
5107  *
5108  * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
5109  *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
5110  *
5111  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
5112  */
5113 mblk_t *
5114 zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
5115 {
5116 	int shift, plen, iph_len;
5117 	ipha_t *ipha;
5118 	udpha_t *udpha;
5119 	uint32_t *spi;
5120 	uint32_t esp_ports;
5121 	uint8_t *orptr;
5122 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
5123 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5124 
5125 	ipha = (ipha_t *)mp->b_rptr;
5126 	iph_len = ira->ira_ip_hdr_length;
5127 	plen = ira->ira_pktlen;
5128 
5129 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
5130 		/*
5131 		 * Most likely a keepalive for the benefit of an intervening
5132 		 * NAT.  These aren't for us, per se, so drop it.
5133 		 *
5134 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
5135 		 * byte packets (keepalives are 1-byte), but we'll drop them
5136 		 * also.
5137 		 */
5138 		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5139 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
5140 		return (NULL);
5141 	}
5142 
5143 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
5144 		/* might as well pull it all up - it might be ESP. */
5145 		if (!pullupmsg(mp, -1)) {
5146 			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
5147 			    DROPPER(ipss, ipds_esp_nomem),
5148 			    &ipss->ipsec_dropper);
5149 			return (NULL);
5150 		}
5151 
5152 		ipha = (ipha_t *)mp->b_rptr;
5153 	}
5154 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
5155 	if (*spi == 0) {
5156 		/* UDP packet - remove 0-spi. */
5157 		shift = sizeof (uint32_t);
5158 	} else {
5159 		/* ESP-in-UDP packet - reduce to ESP. */
5160 		ipha->ipha_protocol = IPPROTO_ESP;
5161 		shift = sizeof (udpha_t);
5162 	}
5163 
5164 	/* Fix IP header */
5165 	ira->ira_pktlen = (plen - shift);
5166 	ipha->ipha_length = htons(ira->ira_pktlen);
5167 	ipha->ipha_hdr_checksum = 0;
5168 
5169 	orptr = mp->b_rptr;
5170 	mp->b_rptr += shift;
5171 
5172 	udpha = (udpha_t *)(orptr + iph_len);
5173 	if (*spi == 0) {
5174 		ASSERT((uint8_t *)ipha == orptr);
5175 		udpha->uha_length = htons(plen - shift - iph_len);
5176 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
5177 		esp_ports = 0;
5178 	} else {
5179 		esp_ports = *((uint32_t *)udpha);
5180 		ASSERT(esp_ports != 0);
5181 	}
5182 	ovbcopy(orptr, orptr + shift, iph_len);
5183 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
5184 		ipha = (ipha_t *)(orptr + shift);
5185 
5186 		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
5187 		ira->ira_esp_udp_ports = esp_ports;
5188 		ip_fanout_v4(mp, ipha, ira);
5189 		return (NULL);
5190 	}
5191 	return (mp);
5192 }
5193 
5194 /*
5195  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
5196  * Handles IPv4 and IPv6.
5197  * We are responsible for disposing of mp, such as by freemsg() or putnext()
5198  * Caller is responsible for dropping references to the conn.
5199  */
5200 void
5201 ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
5202     ip_recv_attr_t *ira)
5203 {
5204 	ill_t		*ill = ira->ira_ill;
5205 	ip_stack_t	*ipst = ill->ill_ipst;
5206 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
5207 	boolean_t	secure;
5208 	iaflags_t	iraflags = ira->ira_flags;
5209 
5210 	secure = iraflags & IRAF_IPSEC_SECURE;
5211 
5212 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
5213 	    !canputnext(connp->conn_rq)) {
5214 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
5215 		freemsg(mp);
5216 		return;
5217 	}
5218 
5219 	if (((iraflags & IRAF_IS_IPV4) ?
5220 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
5221 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
5222 	    secure) {
5223 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
5224 		    ip6h, ira);
5225 		if (mp == NULL) {
5226 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5227 			/* Note that mp is NULL */
5228 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
5229 			return;
5230 		}
5231 	}
5232 
5233 	/*
5234 	 * Since this code is not used for UDP unicast we don't need a NAT_T
5235 	 * check. Only ip_fanout_v4 has that check.
5236 	 */
5237 	if (ira->ira_flags & IRAF_ICMP_ERROR) {
5238 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
5239 	} else {
5240 		ill_t *rill = ira->ira_rill;
5241 
5242 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
5243 		ira->ira_ill = ira->ira_rill = NULL;
5244 		/* Send it upstream */
5245 		(connp->conn_recv)(connp, mp, NULL, ira);
5246 		ira->ira_ill = ill;
5247 		ira->ira_rill = rill;
5248 	}
5249 }
5250 
5251 /*
5252  * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
5253  * (Unicast fanout is handled in ip_input_v4.)
5254  *
5255  * If SO_REUSEADDR is set all multicast and broadcast packets
5256  * will be delivered to all conns bound to the same port.
5257  *
5258  * If there is at least one matching AF_INET receiver, then we will
5259  * ignore any AF_INET6 receivers.
5260  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
5261  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
5262  * packets.
5263  *
5264  * Zones notes:
5265  * Earlier in ip_input on a system with multiple shared-IP zones we
5266  * duplicate the multicast and broadcast packets and send them up
5267  * with each explicit zoneid that exists on that ill.
5268  * This means that here we can match the zoneid with SO_ALLZONES being special.
5269  */
5270 void
5271 ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
5272     ip_recv_attr_t *ira)
5273 {
5274 	ipaddr_t	laddr;
5275 	in6_addr_t	v6faddr;
5276 	conn_t		*connp;
5277 	connf_t		*connfp;
5278 	ipaddr_t	faddr;
5279 	ill_t		*ill = ira->ira_ill;
5280 	ip_stack_t	*ipst = ill->ill_ipst;
5281 
5282 	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));
5283 
5284 	laddr = ipha->ipha_dst;
5285 	faddr = ipha->ipha_src;
5286 
5287 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5288 	mutex_enter(&connfp->connf_lock);
5289 	connp = connfp->connf_head;
5290 
5291 	/*
5292 	 * If SO_REUSEADDR has been set on the first we send the
5293 	 * packet to all clients that have joined the group and
5294 	 * match the port.
5295 	 */
5296 	while (connp != NULL) {
5297 		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
5298 		    conn_wantpacket(connp, ira, ipha) &&
5299 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5300 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5301 			break;
5302 		connp = connp->conn_next;
5303 	}
5304 
5305 	if (connp == NULL)
5306 		goto notfound;
5307 
5308 	CONN_INC_REF(connp);
5309 
5310 	if (connp->conn_reuseaddr) {
5311 		conn_t		*first_connp = connp;
5312 		conn_t		*next_connp;
5313 		mblk_t		*mp1;
5314 
5315 		connp = connp->conn_next;
5316 		for (;;) {
5317 			while (connp != NULL) {
5318 				if (IPCL_UDP_MATCH(connp, lport, laddr,
5319 				    fport, faddr) &&
5320 				    conn_wantpacket(connp, ira, ipha) &&
5321 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5322 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5323 				    ira, connp)))
5324 					break;
5325 				connp = connp->conn_next;
5326 			}
5327 			if (connp == NULL) {
5328 				/* No more interested clients */
5329 				connp = first_connp;
5330 				break;
5331 			}
5332 			if (((mp1 = dupmsg(mp)) == NULL) &&
5333 			    ((mp1 = copymsg(mp)) == NULL)) {
5334 				/* Memory allocation failed */
5335 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5336 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5337 				connp = first_connp;
5338 				break;
5339 			}
5340 			CONN_INC_REF(connp);
5341 			mutex_exit(&connfp->connf_lock);
5342 
5343 			IP_STAT(ipst, ip_udp_fanmb);
5344 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5345 			    NULL, ira);
5346 			mutex_enter(&connfp->connf_lock);
5347 			/* Follow the next pointer before releasing the conn */
5348 			next_connp = connp->conn_next;
5349 			CONN_DEC_REF(connp);
5350 			connp = next_connp;
5351 		}
5352 	}
5353 
5354 	/* Last one.  Send it upstream. */
5355 	mutex_exit(&connfp->connf_lock);
5356 	IP_STAT(ipst, ip_udp_fanmb);
5357 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5358 	CONN_DEC_REF(connp);
5359 	return;
5360 
5361 notfound:
5362 	mutex_exit(&connfp->connf_lock);
5363 	/*
5364 	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
5365 	 * have already been matched above, since they live in the IPv4
5366 	 * fanout tables. This implies we only need to
5367 	 * check for IPv6 in6addr_any endpoints here.
5368 	 * Thus we compare using ipv6_all_zeros instead of the destination
5369 	 * address, except for the multicast group membership lookup which
5370 	 * uses the IPv4 destination.
5371 	 */
5372 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
5373 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
5374 	mutex_enter(&connfp->connf_lock);
5375 	connp = connfp->connf_head;
5376 	/*
5377 	 * IPv4 multicast packet being delivered to an AF_INET6
5378 	 * in6addr_any endpoint.
5379 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
5380 	 * and not conn_wantpacket_v6() since any multicast membership is
5381 	 * for an IPv4-mapped multicast address.
5382 	 */
5383 	while (connp != NULL) {
5384 		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
5385 		    fport, v6faddr) &&
5386 		    conn_wantpacket(connp, ira, ipha) &&
5387 		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5388 		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
5389 			break;
5390 		connp = connp->conn_next;
5391 	}
5392 
5393 	if (connp == NULL) {
5394 		/*
5395 		 * No one bound to this port.  Is
5396 		 * there a client that wants all
5397 		 * unclaimed datagrams?
5398 		 */
5399 		mutex_exit(&connfp->connf_lock);
5400 
5401 		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
5402 		    NULL) {
5403 			ASSERT(ira->ira_protocol == IPPROTO_UDP);
5404 			ip_fanout_proto_v4(mp, ipha, ira);
5405 		} else {
5406 			/*
5407 			 * We used to attempt to send an icmp error here, but
5408 			 * since this is known to be a multicast packet
5409 			 * and we don't send icmp errors in response to
5410 			 * multicast, just drop the packet and give up sooner.
5411 			 */
5412 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
5413 			freemsg(mp);
5414 		}
5415 		return;
5416 	}
5417 	CONN_INC_REF(connp);
5418 	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);
5419 
5420 	/*
5421 	 * If SO_REUSEADDR has been set on the first we send the
5422 	 * packet to all clients that have joined the group and
5423 	 * match the port.
5424 	 */
5425 	if (connp->conn_reuseaddr) {
5426 		conn_t		*first_connp = connp;
5427 		conn_t		*next_connp;
5428 		mblk_t		*mp1;
5429 
5430 		connp = connp->conn_next;
5431 		for (;;) {
5432 			while (connp != NULL) {
5433 				if (IPCL_UDP_MATCH_V6(connp, lport,
5434 				    ipv6_all_zeros, fport, v6faddr) &&
5435 				    conn_wantpacket(connp, ira, ipha) &&
5436 				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
5437 				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
5438 				    ira, connp)))
5439 					break;
5440 				connp = connp->conn_next;
5441 			}
5442 			if (connp == NULL) {
5443 				/* No more interested clients */
5444 				connp = first_connp;
5445 				break;
5446 			}
5447 			if (((mp1 = dupmsg(mp)) == NULL) &&
5448 			    ((mp1 = copymsg(mp)) == NULL)) {
5449 				/* Memory allocation failed */
5450 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
5451 				ip_drop_input("ipIfStatsInDiscards", mp, ill);
5452 				connp = first_connp;
5453 				break;
5454 			}
5455 			CONN_INC_REF(connp);
5456 			mutex_exit(&connfp->connf_lock);
5457 
5458 			IP_STAT(ipst, ip_udp_fanmb);
5459 			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
5460 			    NULL, ira);
5461 			mutex_enter(&connfp->connf_lock);
5462 			/* Follow the next pointer before releasing the conn */
5463 			next_connp = connp->conn_next;
5464 			CONN_DEC_REF(connp);
5465 			connp = next_connp;
5466 		}
5467 	}
5468 
5469 	/* Last one.  Send it upstream. */
5470 	mutex_exit(&connfp->connf_lock);
5471 	IP_STAT(ipst, ip_udp_fanmb);
5472 	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
5473 	CONN_DEC_REF(connp);
5474 }
5475 
5476 /*
5477  * Split an incoming packet's IPv4 options into the label and the other options.
5478  * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
5479  * clearing out any leftover label or options.
5480  * Otherwise it just makes ipp point into the packet.
5481  *
5482  * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
5483  */
5484 int
5485 ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
5486 {
5487 	uchar_t		*opt;
5488 	uint32_t	totallen;
5489 	uint32_t	optval;
5490 	uint32_t	optlen;
5491 
5492 	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
5493 	ipp->ipp_hoplimit = ipha->ipha_ttl;
5494 	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
5495 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);
5496 
5497 	/*
5498 	 * Get length (in 4 byte octets) of IP header options.
5499 	 */
5500 	totallen = ipha->ipha_version_and_hdr_length -
5501 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5502 
5503 	if (totallen == 0) {
5504 		if (!allocate)
5505 			return (0);
5506 
5507 		/* Clear out anything from a previous packet */
5508 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5509 			kmem_free(ipp->ipp_ipv4_options,
5510 			    ipp->ipp_ipv4_options_len);
5511 			ipp->ipp_ipv4_options = NULL;
5512 			ipp->ipp_ipv4_options_len = 0;
5513 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5514 		}
5515 		if (ipp->ipp_fields & IPPF_LABEL_V4) {
5516 			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5517 			ipp->ipp_label_v4 = NULL;
5518 			ipp->ipp_label_len_v4 = 0;
5519 			ipp->ipp_fields &= ~IPPF_LABEL_V4;
5520 		}
5521 		return (0);
5522 	}
5523 
5524 	totallen <<= 2;
5525 	opt = (uchar_t *)&ipha[1];
5526 	if (!is_system_labeled()) {
5527 
5528 	copyall:
5529 		if (!allocate) {
5530 			if (totallen != 0) {
5531 				ipp->ipp_ipv4_options = opt;
5532 				ipp->ipp_ipv4_options_len = totallen;
5533 				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5534 			}
5535 			return (0);
5536 		}
5537 		/* Just copy all of options */
5538 		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
5539 			if (totallen == ipp->ipp_ipv4_options_len) {
5540 				bcopy(opt, ipp->ipp_ipv4_options, totallen);
5541 				return (0);
5542 			}
5543 			kmem_free(ipp->ipp_ipv4_options,
5544 			    ipp->ipp_ipv4_options_len);
5545 			ipp->ipp_ipv4_options = NULL;
5546 			ipp->ipp_ipv4_options_len = 0;
5547 			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
5548 		}
5549 		if (totallen == 0)
5550 			return (0);
5551 
5552 		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
5553 		if (ipp->ipp_ipv4_options == NULL)
5554 			return (ENOMEM);
5555 		ipp->ipp_ipv4_options_len = totallen;
5556 		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
5557 		bcopy(opt, ipp->ipp_ipv4_options, totallen);
5558 		return (0);
5559 	}
5560 
5561 	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
5562 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
5563 		ipp->ipp_label_v4 = NULL;
5564 		ipp->ipp_label_len_v4 = 0;
5565 		ipp->ipp_fields &= ~IPPF_LABEL_V4;
5566 	}
5567 
5568 	/*
5569 	 * Search for CIPSO option.
5570 	 * We assume CIPSO is first in options if it is present.
5571 	 * If it isn't, then ipp_opt_ipv4_options will not include the options
5572 	 * prior to the CIPSO option.
5573 	 */
5574 	while (totallen != 0) {
5575 		switch (optval = opt[IPOPT_OPTVAL]) {
5576 		case IPOPT_EOL:
5577 			return (0);
5578 		case IPOPT_NOP:
5579 			optlen = 1;
5580 			break;
5581 		default:
5582 			if (totallen <= IPOPT_OLEN)
5583 				return (EINVAL);
5584 			optlen = opt[IPOPT_OLEN];
5585 			if (optlen < 2)
5586 				return (EINVAL);
5587 		}
5588 		if (optlen > totallen)
5589 			return (EINVAL);
5590 
5591 		switch (optval) {
5592 		case IPOPT_COMSEC:
5593 			if (!allocate) {
5594 				ipp->ipp_label_v4 = opt;
5595 				ipp->ipp_label_len_v4 = optlen;
5596 				ipp->ipp_fields |= IPPF_LABEL_V4;
5597 			} else {
5598 				ipp->ipp_label_v4 = kmem_alloc(optlen,
5599 				    KM_NOSLEEP);
5600 				if (ipp->ipp_label_v4 == NULL)
5601 					return (ENOMEM);
5602 				ipp->ipp_label_len_v4 = optlen;
5603 				ipp->ipp_fields |= IPPF_LABEL_V4;
5604 				bcopy(opt, ipp->ipp_label_v4, optlen);
5605 			}
5606 			totallen -= optlen;
5607 			opt += optlen;
5608 
5609 			/* Skip padding bytes until we get to a multiple of 4 */
5610 			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
5611 				totallen--;
5612 				opt++;
5613 			}
5614 			/* Remaining as ipp_ipv4_options */
5615 			goto copyall;
5616 		}
5617 		totallen -= optlen;
5618 		opt += optlen;
5619 	}
5620 	/* No CIPSO found; return everything as ipp_ipv4_options */
5621 	totallen = ipha->ipha_version_and_hdr_length -
5622 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
5623 	totallen <<= 2;
5624 	opt = (uchar_t *)&ipha[1];
5625 	goto copyall;
5626 }
5627 
5628 /*
5629  * Efficient versions of lookup for an IRE when we only
5630  * match the address.
5631  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5632  * Does not handle multicast addresses.
5633  */
5634 uint_t
5635 ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
5636 {
5637 	ire_t *ire;
5638 	uint_t result;
5639 
5640 	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
5641 	ASSERT(ire != NULL);
5642 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5643 		result = IRE_NOROUTE;
5644 	else
5645 		result = ire->ire_type;
5646 	ire_refrele(ire);
5647 	return (result);
5648 }
5649 
5650 /*
5651  * Efficient versions of lookup for an IRE when we only
5652  * match the address.
5653  * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
5654  * Does not handle multicast addresses.
5655  */
5656 uint_t
5657 ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
5658 {
5659 	ire_t *ire;
5660 	uint_t result;
5661 
5662 	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
5663 	ASSERT(ire != NULL);
5664 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
5665 		result = IRE_NOROUTE;
5666 	else
5667 		result = ire->ire_type;
5668 	ire_refrele(ire);
5669 	return (result);
5670 }
5671 
5672 /*
5673  * Nobody should be sending
5674  * packets up this stream
5675  */
5676 static void
5677 ip_lrput(queue_t *q, mblk_t *mp)
5678 {
5679 	switch (mp->b_datap->db_type) {
5680 	case M_FLUSH:
5681 		/* Turn around */
5682 		if (*mp->b_rptr & FLUSHW) {
5683 			*mp->b_rptr &= ~FLUSHR;
5684 			qreply(q, mp);
5685 			return;
5686 		}
5687 		break;
5688 	}
5689 	freemsg(mp);
5690 }
5691 
5692 /* Nobody should be sending packets down this stream */
5693 /* ARGSUSED */
5694 void
5695 ip_lwput(queue_t *q, mblk_t *mp)
5696 {
5697 	freemsg(mp);
5698 }
5699 
5700 /*
5701  * Move the first hop in any source route to ipha_dst and remove that part of
5702  * the source route.  Called by other protocols.  Errors in option formatting
5703  * are ignored - will be handled by ip_output_options. Return the final
5704  * destination (either ipha_dst or the last entry in a source route.)
5705  */
5706 ipaddr_t
5707 ip_massage_options(ipha_t *ipha, netstack_t *ns)
5708 {
5709 	ipoptp_t	opts;
5710 	uchar_t		*opt;
5711 	uint8_t		optval;
5712 	uint8_t		optlen;
5713 	ipaddr_t	dst;
5714 	int		i;
5715 	ip_stack_t	*ipst = ns->netstack_ip;
5716 
5717 	ip2dbg(("ip_massage_options\n"));
5718 	dst = ipha->ipha_dst;
5719 	for (optval = ipoptp_first(&opts, ipha);
5720 	    optval != IPOPT_EOL;
5721 	    optval = ipoptp_next(&opts)) {
5722 		opt = opts.ipoptp_cur;
5723 		switch (optval) {
5724 			uint8_t off;
5725 		case IPOPT_SSRR:
5726 		case IPOPT_LSRR:
5727 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
5728 				ip1dbg(("ip_massage_options: bad src route\n"));
5729 				break;
5730 			}
5731 			optlen = opts.ipoptp_len;
5732 			off = opt[IPOPT_OFFSET];
5733 			off--;
5734 		redo_srr:
5735 			if (optlen < IP_ADDR_LEN ||
5736 			    off > optlen - IP_ADDR_LEN) {
5737 				/* End of source route */
5738 				ip1dbg(("ip_massage_options: end of SR\n"));
5739 				break;
5740 			}
5741 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
5742 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
5743 			    ntohl(dst)));
5744 			/*
5745 			 * Check if our address is present more than
5746 			 * once as consecutive hops in source route.
5747 			 * XXX verify per-interface ip_forwarding
5748 			 * for source route?
5749 			 */
5750 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
5751 				off += IP_ADDR_LEN;
5752 				goto redo_srr;
5753 			}
5754 			if (dst == htonl(INADDR_LOOPBACK)) {
5755 				ip1dbg(("ip_massage_options: loopback addr in "
5756 				    "source route!\n"));
5757 				break;
5758 			}
5759 			/*
5760 			 * Update ipha_dst to be the first hop and remove the
5761 			 * first hop from the source route (by overwriting
5762 			 * part of the option with NOP options).
5763 			 */
5764 			ipha->ipha_dst = dst;
5765 			/* Put the last entry in dst */
5766 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
5767 			    3;
5768 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
5769 
5770 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
5771 			    ntohl(dst)));
5772 			/* Move down and overwrite */
5773 			opt[IP_ADDR_LEN] = opt[0];
5774 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
5775 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
5776 			for (i = 0; i < IP_ADDR_LEN; i++)
5777 				opt[i] = IPOPT_NOP;
5778 			break;
5779 		}
5780 	}
5781 	return (dst);
5782 }
5783 
5784 /*
5785  * Return the network mask
5786  * associated with the specified address.
5787  */
5788 ipaddr_t
5789 ip_net_mask(ipaddr_t addr)
5790 {
5791 	uchar_t	*up = (uchar_t *)&addr;
5792 	ipaddr_t mask = 0;
5793 	uchar_t	*maskp = (uchar_t *)&mask;
5794 
5795 #if defined(__i386) || defined(__amd64)
5796 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
5797 #endif
5798 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
5799 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
5800 #endif
5801 	if (CLASSD(addr)) {
5802 		maskp[0] = 0xF0;
5803 		return (mask);
5804 	}
5805 
5806 	/* We assume Class E default netmask to be 32 */
5807 	if (CLASSE(addr))
5808 		return (0xffffffffU);
5809 
5810 	if (addr == 0)
5811 		return (0);
5812 	maskp[0] = 0xFF;
5813 	if ((up[0] & 0x80) == 0)
5814 		return (mask);
5815 
5816 	maskp[1] = 0xFF;
5817 	if ((up[0] & 0xC0) == 0x80)
5818 		return (mask);
5819 
5820 	maskp[2] = 0xFF;
5821 	if ((up[0] & 0xE0) == 0xC0)
5822 		return (mask);
5823 
5824 	/* Otherwise return no mask */
5825 	return ((ipaddr_t)0);
5826 }
5827 
5828 /* Name/Value Table Lookup Routine */
5829 char *
5830 ip_nv_lookup(nv_t *nv, int value)
5831 {
5832 	if (!nv)
5833 		return (NULL);
5834 	for (; nv->nv_name; nv++) {
5835 		if (nv->nv_value == value)
5836 			return (nv->nv_name);
5837 	}
5838 	return ("unknown");
5839 }
5840 
5841 static int
5842 ip_wait_for_info_ack(ill_t *ill)
5843 {
5844 	int err;
5845 
5846 	mutex_enter(&ill->ill_lock);
5847 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
5848 		/*
5849 		 * Return value of 0 indicates a pending signal.
5850 		 */
5851 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
5852 		if (err == 0) {
5853 			mutex_exit(&ill->ill_lock);
5854 			return (EINTR);
5855 		}
5856 	}
5857 	mutex_exit(&ill->ill_lock);
5858 	/*
5859 	 * ip_rput_other could have set an error  in ill_error on
5860 	 * receipt of M_ERROR.
5861 	 */
5862 	return (ill->ill_error);
5863 }
5864 
5865 /*
5866  * This is a module open, i.e. this is a control stream for access
5867  * to a DLPI device.  We allocate an ill_t as the instance data in
5868  * this case.
5869  */
5870 static int
5871 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5872 {
5873 	ill_t	*ill;
5874 	int	err;
5875 	zoneid_t zoneid;
5876 	netstack_t *ns;
5877 	ip_stack_t *ipst;
5878 
5879 	/*
5880 	 * Prevent unprivileged processes from pushing IP so that
5881 	 * they can't send raw IP.
5882 	 */
5883 	if (secpolicy_net_rawaccess(credp) != 0)
5884 		return (EPERM);
5885 
5886 	ns = netstack_find_by_cred(credp);
5887 	ASSERT(ns != NULL);
5888 	ipst = ns->netstack_ip;
5889 	ASSERT(ipst != NULL);
5890 
5891 	/*
5892 	 * For exclusive stacks we set the zoneid to zero
5893 	 * to make IP operate as if in the global zone.
5894 	 */
5895 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5896 		zoneid = GLOBAL_ZONEID;
5897 	else
5898 		zoneid = crgetzoneid(credp);
5899 
5900 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
5901 	q->q_ptr = WR(q)->q_ptr = ill;
5902 	ill->ill_ipst = ipst;
5903 	ill->ill_zoneid = zoneid;
5904 
5905 	/*
5906 	 * ill_init initializes the ill fields and then sends down
5907 	 * down a DL_INFO_REQ after calling qprocson.
5908 	 */
5909 	err = ill_init(q, ill);
5910 
5911 	if (err != 0) {
5912 		mi_free(ill);
5913 		netstack_rele(ipst->ips_netstack);
5914 		q->q_ptr = NULL;
5915 		WR(q)->q_ptr = NULL;
5916 		return (err);
5917 	}
5918 
5919 	/*
5920 	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
5921 	 *
5922 	 * ill_init initializes the ipsq marking this thread as
5923 	 * writer
5924 	 */
5925 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
5926 	err = ip_wait_for_info_ack(ill);
5927 	if (err == 0)
5928 		ill->ill_credp = credp;
5929 	else
5930 		goto fail;
5931 
5932 	crhold(credp);
5933 
5934 	mutex_enter(&ipst->ips_ip_mi_lock);
5935 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
5936 	    sflag, credp);
5937 	mutex_exit(&ipst->ips_ip_mi_lock);
5938 fail:
5939 	if (err) {
5940 		(void) ip_close(q, 0, credp);
5941 		return (err);
5942 	}
5943 	return (0);
5944 }
5945 
5946 /* For /dev/ip aka AF_INET open */
5947 int
5948 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5949 {
5950 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
5951 }
5952 
5953 /* For /dev/ip6 aka AF_INET6 open */
5954 int
5955 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
5956 {
5957 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
5958 }
5959 
5960 /* IP open routine. */
5961 int
5962 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
5963     boolean_t isv6)
5964 {
5965 	conn_t 		*connp;
5966 	major_t		maj;
5967 	zoneid_t	zoneid;
5968 	netstack_t	*ns;
5969 	ip_stack_t	*ipst;
5970 
5971 	/* Allow reopen. */
5972 	if (q->q_ptr != NULL)
5973 		return (0);
5974 
5975 	if (sflag & MODOPEN) {
5976 		/* This is a module open */
5977 		return (ip_modopen(q, devp, flag, sflag, credp));
5978 	}
5979 
5980 	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
5981 		/*
5982 		 * Non streams based socket looking for a stream
5983 		 * to access IP
5984 		 */
5985 		return (ip_helper_stream_setup(q, devp, flag, sflag,
5986 		    credp, isv6));
5987 	}
5988 
5989 	ns = netstack_find_by_cred(credp);
5990 	ASSERT(ns != NULL);
5991 	ipst = ns->netstack_ip;
5992 	ASSERT(ipst != NULL);
5993 
5994 	/*
5995 	 * For exclusive stacks we set the zoneid to zero
5996 	 * to make IP operate as if in the global zone.
5997 	 */
5998 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
5999 		zoneid = GLOBAL_ZONEID;
6000 	else
6001 		zoneid = crgetzoneid(credp);
6002 
6003 	/*
6004 	 * We are opening as a device. This is an IP client stream, and we
6005 	 * allocate an conn_t as the instance data.
6006 	 */
6007 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
6008 
6009 	/*
6010 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
6011 	 * done by netstack_find_by_cred()
6012 	 */
6013 	netstack_rele(ipst->ips_netstack);
6014 
6015 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
6016 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
6017 	connp->conn_ixa->ixa_zoneid = zoneid;
6018 	connp->conn_zoneid = zoneid;
6019 
6020 	connp->conn_rq = q;
6021 	q->q_ptr = WR(q)->q_ptr = connp;
6022 
6023 	/* Minor tells us which /dev entry was opened */
6024 	if (isv6) {
6025 		connp->conn_family = AF_INET6;
6026 		connp->conn_ipversion = IPV6_VERSION;
6027 		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
6028 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
6029 	} else {
6030 		connp->conn_family = AF_INET;
6031 		connp->conn_ipversion = IPV4_VERSION;
6032 		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
6033 	}
6034 
6035 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
6036 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
6037 		connp->conn_minor_arena = ip_minor_arena_la;
6038 	} else {
6039 		/*
6040 		 * Either minor numbers in the large arena were exhausted
6041 		 * or a non socket application is doing the open.
6042 		 * Try to allocate from the small arena.
6043 		 */
6044 		if ((connp->conn_dev =
6045 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
6046 			/* CONN_DEC_REF takes care of netstack_rele() */
6047 			q->q_ptr = WR(q)->q_ptr = NULL;
6048 			CONN_DEC_REF(connp);
6049 			return (EBUSY);
6050 		}
6051 		connp->conn_minor_arena = ip_minor_arena_sa;
6052 	}
6053 
6054 	maj = getemajor(*devp);
6055 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
6056 
6057 	/*
6058 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
6059 	 */
6060 	connp->conn_cred = credp;
6061 	connp->conn_cpid = curproc->p_pid;
6062 	/* Cache things in ixa without an extra refhold */
6063 	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
6064 	connp->conn_ixa->ixa_cred = connp->conn_cred;
6065 	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
6066 	if (is_system_labeled())
6067 		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);
6068 
6069 	/*
6070 	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
6071 	 */
6072 	connp->conn_recv = ip_conn_input;
6073 	connp->conn_recvicmp = ip_conn_input_icmp;
6074 
6075 	crhold(connp->conn_cred);
6076 
6077 	/*
6078 	 * If the caller has the process-wide flag set, then default to MAC
6079 	 * exempt mode.  This allows read-down to unlabeled hosts.
6080 	 */
6081 	if (getpflags(NET_MAC_AWARE, credp) != 0)
6082 		connp->conn_mac_mode = CONN_MAC_AWARE;
6083 
6084 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
6085 
6086 	connp->conn_rq = q;
6087 	connp->conn_wq = WR(q);
6088 
6089 	/* Non-zero default values */
6090 	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;
6091 
6092 	/*
6093 	 * Make the conn globally visible to walkers
6094 	 */
6095 	ASSERT(connp->conn_ref == 1);
6096 	mutex_enter(&connp->conn_lock);
6097 	connp->conn_state_flags &= ~CONN_INCIPIENT;
6098 	mutex_exit(&connp->conn_lock);
6099 
6100 	qprocson(q);
6101 
6102 	return (0);
6103 }
6104 
6105 /*
6106  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
6107  * all of them are copied to the conn_t. If the req is "zero", the policy is
6108  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
6109  * fields.
6110  * We keep only the latest setting of the policy and thus policy setting
6111  * is not incremental/cumulative.
6112  *
6113  * Requests to set policies with multiple alternative actions will
6114  * go through a different API.
6115  */
6116 int
6117 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
6118 {
6119 	uint_t ah_req = 0;
6120 	uint_t esp_req = 0;
6121 	uint_t se_req = 0;
6122 	ipsec_act_t *actp = NULL;
6123 	uint_t nact;
6124 	ipsec_policy_head_t *ph;
6125 	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
6126 	int error = 0;
6127 	netstack_t	*ns = connp->conn_netstack;
6128 	ip_stack_t	*ipst = ns->netstack_ip;
6129 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
6130 
6131 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
6132 
6133 	/*
6134 	 * The IP_SEC_OPT option does not allow variable length parameters,
6135 	 * hence a request cannot be NULL.
6136 	 */
6137 	if (req == NULL)
6138 		return (EINVAL);
6139 
6140 	ah_req = req->ipsr_ah_req;
6141 	esp_req = req->ipsr_esp_req;
6142 	se_req = req->ipsr_self_encap_req;
6143 
6144 	/* Don't allow setting self-encap without one or more of AH/ESP. */
6145 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
6146 		return (EINVAL);
6147 
6148 	/*
6149 	 * Are we dealing with a request to reset the policy (i.e.
6150 	 * zero requests).
6151 	 */
6152 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
6153 	    (esp_req & REQ_MASK) == 0 &&
6154 	    (se_req & REQ_MASK) == 0);
6155 
6156 	if (!is_pol_reset) {
6157 		/*
6158 		 * If we couldn't load IPsec, fail with "protocol
6159 		 * not supported".
6160 		 * IPsec may not have been loaded for a request with zero
6161 		 * policies, so we don't fail in this case.
6162 		 */
6163 		mutex_enter(&ipss->ipsec_loader_lock);
6164 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
6165 			mutex_exit(&ipss->ipsec_loader_lock);
6166 			return (EPROTONOSUPPORT);
6167 		}
6168 		mutex_exit(&ipss->ipsec_loader_lock);
6169 
6170 		/*
6171 		 * Test for valid requests. Invalid algorithms
6172 		 * need to be tested by IPsec code because new
6173 		 * algorithms can be added dynamically.
6174 		 */
6175 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6176 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
6177 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
6178 			return (EINVAL);
6179 		}
6180 
6181 		/*
6182 		 * Only privileged users can issue these
6183 		 * requests.
6184 		 */
6185 		if (((ah_req & IPSEC_PREF_NEVER) ||
6186 		    (esp_req & IPSEC_PREF_NEVER) ||
6187 		    (se_req & IPSEC_PREF_NEVER)) &&
6188 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
6189 			return (EPERM);
6190 		}
6191 
6192 		/*
6193 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
6194 		 * are mutually exclusive.
6195 		 */
6196 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
6197 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
6198 		    ((se_req & REQ_MASK) == REQ_MASK)) {
6199 			/* Both of them are set */
6200 			return (EINVAL);
6201 		}
6202 	}
6203 
6204 	ASSERT(MUTEX_HELD(&connp->conn_lock));
6205 
6206 	/*
6207 	 * If we have already cached policies in conn_connect(), don't
6208 	 * let them change now. We cache policies for connections
6209 	 * whose src,dst [addr, port] is known.
6210 	 */
6211 	if (connp->conn_policy_cached) {
6212 		return (EINVAL);
6213 	}
6214 
6215 	/*
6216 	 * We have a zero policies, reset the connection policy if already
6217 	 * set. This will cause the connection to inherit the
6218 	 * global policy, if any.
6219 	 */
6220 	if (is_pol_reset) {
6221 		if (connp->conn_policy != NULL) {
6222 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
6223 			connp->conn_policy = NULL;
6224 		}
6225 		connp->conn_in_enforce_policy = B_FALSE;
6226 		connp->conn_out_enforce_policy = B_FALSE;
6227 		return (0);
6228 	}
6229 
6230 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
6231 	    ipst->ips_netstack);
6232 	if (ph == NULL)
6233 		goto enomem;
6234 
6235 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
6236 	if (actp == NULL)
6237 		goto enomem;
6238 
6239 	/*
6240 	 * Always insert IPv4 policy entries, since they can also apply to
6241 	 * ipv6 sockets being used in ipv4-compat mode.
6242 	 */
6243 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6244 	    IPSEC_TYPE_INBOUND, ns))
6245 		goto enomem;
6246 	is_pol_inserted = B_TRUE;
6247 	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
6248 	    IPSEC_TYPE_OUTBOUND, ns))
6249 		goto enomem;
6250 
6251 	/*
6252 	 * We're looking at a v6 socket, also insert the v6-specific
6253 	 * entries.
6254 	 */
6255 	if (connp->conn_family == AF_INET6) {
6256 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6257 		    IPSEC_TYPE_INBOUND, ns))
6258 			goto enomem;
6259 		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
6260 		    IPSEC_TYPE_OUTBOUND, ns))
6261 			goto enomem;
6262 	}
6263 
6264 	ipsec_actvec_free(actp, nact);
6265 
6266 	/*
6267 	 * If the requests need security, set enforce_policy.
6268 	 * If the requests are IPSEC_PREF_NEVER, one should
6269 	 * still set conn_out_enforce_policy so that ip_set_destination
6270 	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
6271 	 * for connections that we don't cache policy in at connect time,
6272 	 * if global policy matches in ip_output_attach_policy, we
6273 	 * don't wrongly inherit global policy. Similarly, we need
6274 	 * to set conn_in_enforce_policy also so that we don't verify
6275 	 * policy wrongly.
6276 	 */
6277 	if ((ah_req & REQ_MASK) != 0 ||
6278 	    (esp_req & REQ_MASK) != 0 ||
6279 	    (se_req & REQ_MASK) != 0) {
6280 		connp->conn_in_enforce_policy = B_TRUE;
6281 		connp->conn_out_enforce_policy = B_TRUE;
6282 	}
6283 
6284 	return (error);
6285 #undef REQ_MASK
6286 
6287 	/*
6288 	 * Common memory-allocation-failure exit path.
6289 	 */
6290 enomem:
6291 	if (actp != NULL)
6292 		ipsec_actvec_free(actp, nact);
6293 	if (is_pol_inserted)
6294 		ipsec_polhead_flush(ph, ns);
6295 	return (ENOMEM);
6296 }
6297 
6298 /*
6299  * Set socket options for joining and leaving multicast groups.
6300  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6301  * The caller has already check that the option name is consistent with
6302  * the address family of the socket.
6303  */
6304 int
6305 ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
6306     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6307 {
6308 	int		*i1 = (int *)invalp;
6309 	int		error = 0;
6310 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6311 	struct ip_mreq	*v4_mreqp;
6312 	struct ipv6_mreq *v6_mreqp;
6313 	struct group_req *greqp;
6314 	ire_t *ire;
6315 	boolean_t done = B_FALSE;
6316 	ipaddr_t ifaddr;
6317 	in6_addr_t v6group;
6318 	uint_t ifindex;
6319 	boolean_t mcast_opt = B_TRUE;
6320 	mcast_record_t fmode;
6321 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6322 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6323 
6324 	switch (name) {
6325 	case IP_ADD_MEMBERSHIP:
6326 	case IPV6_JOIN_GROUP:
6327 		mcast_opt = B_FALSE;
6328 		/* FALLTHROUGH */
6329 	case MCAST_JOIN_GROUP:
6330 		fmode = MODE_IS_EXCLUDE;
6331 		optfn = ip_opt_add_group;
6332 		break;
6333 
6334 	case IP_DROP_MEMBERSHIP:
6335 	case IPV6_LEAVE_GROUP:
6336 		mcast_opt = B_FALSE;
6337 		/* FALLTHROUGH */
6338 	case MCAST_LEAVE_GROUP:
6339 		fmode = MODE_IS_INCLUDE;
6340 		optfn = ip_opt_delete_group;
6341 		break;
6342 	default:
6343 		ASSERT(0);
6344 	}
6345 
6346 	if (mcast_opt) {
6347 		struct sockaddr_in *sin;
6348 		struct sockaddr_in6 *sin6;
6349 
6350 		greqp = (struct group_req *)i1;
6351 		if (greqp->gr_group.ss_family == AF_INET) {
6352 			sin = (struct sockaddr_in *)&(greqp->gr_group);
6353 			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
6354 		} else {
6355 			if (!inet6)
6356 				return (EINVAL);	/* Not on INET socket */
6357 
6358 			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
6359 			v6group = sin6->sin6_addr;
6360 		}
6361 		ifaddr = INADDR_ANY;
6362 		ifindex = greqp->gr_interface;
6363 	} else if (inet6) {
6364 		v6_mreqp = (struct ipv6_mreq *)i1;
6365 		v6group = v6_mreqp->ipv6mr_multiaddr;
6366 		ifaddr = INADDR_ANY;
6367 		ifindex = v6_mreqp->ipv6mr_interface;
6368 	} else {
6369 		v4_mreqp = (struct ip_mreq *)i1;
6370 		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
6371 		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
6372 		ifindex = 0;
6373 	}
6374 
6375 	/*
6376 	 * In the multirouting case, we need to replicate
6377 	 * the request on all interfaces that will take part
6378 	 * in replication.  We do so because multirouting is
6379 	 * reflective, thus we will probably receive multi-
6380 	 * casts on those interfaces.
6381 	 * The ip_multirt_apply_membership() succeeds if
6382 	 * the operation succeeds on at least one interface.
6383 	 */
6384 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6385 		ipaddr_t group;
6386 
6387 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6388 
6389 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6390 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6391 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6392 	} else {
6393 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6394 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6395 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6396 	}
6397 	if (ire != NULL) {
6398 		if (ire->ire_flags & RTF_MULTIRT) {
6399 			error = ip_multirt_apply_membership(optfn, ire, connp,
6400 			    checkonly, &v6group, fmode, &ipv6_all_zeros);
6401 			done = B_TRUE;
6402 		}
6403 		ire_refrele(ire);
6404 	}
6405 
6406 	if (!done) {
6407 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6408 		    fmode, &ipv6_all_zeros);
6409 	}
6410 	return (error);
6411 }
6412 
6413 /*
6414  * Set socket options for joining and leaving multicast groups
6415  * for specific sources.
6416  * Common to IPv4 and IPv6; inet6 indicates the type of socket.
6417  * The caller has already check that the option name is consistent with
6418  * the address family of the socket.
6419  */
6420 int
6421 ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
6422     uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
6423 {
6424 	int		*i1 = (int *)invalp;
6425 	int		error = 0;
6426 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
6427 	struct ip_mreq_source *imreqp;
6428 	struct group_source_req *gsreqp;
6429 	in6_addr_t v6group, v6src;
6430 	uint32_t ifindex;
6431 	ipaddr_t ifaddr;
6432 	boolean_t mcast_opt = B_TRUE;
6433 	mcast_record_t fmode;
6434 	ire_t *ire;
6435 	boolean_t done = B_FALSE;
6436 	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
6437 	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);
6438 
6439 	switch (name) {
6440 	case IP_BLOCK_SOURCE:
6441 		mcast_opt = B_FALSE;
6442 		/* FALLTHROUGH */
6443 	case MCAST_BLOCK_SOURCE:
6444 		fmode = MODE_IS_EXCLUDE;
6445 		optfn = ip_opt_add_group;
6446 		break;
6447 
6448 	case IP_UNBLOCK_SOURCE:
6449 		mcast_opt = B_FALSE;
6450 		/* FALLTHROUGH */
6451 	case MCAST_UNBLOCK_SOURCE:
6452 		fmode = MODE_IS_EXCLUDE;
6453 		optfn = ip_opt_delete_group;
6454 		break;
6455 
6456 	case IP_ADD_SOURCE_MEMBERSHIP:
6457 		mcast_opt = B_FALSE;
6458 		/* FALLTHROUGH */
6459 	case MCAST_JOIN_SOURCE_GROUP:
6460 		fmode = MODE_IS_INCLUDE;
6461 		optfn = ip_opt_add_group;
6462 		break;
6463 
6464 	case IP_DROP_SOURCE_MEMBERSHIP:
6465 		mcast_opt = B_FALSE;
6466 		/* FALLTHROUGH */
6467 	case MCAST_LEAVE_SOURCE_GROUP:
6468 		fmode = MODE_IS_INCLUDE;
6469 		optfn = ip_opt_delete_group;
6470 		break;
6471 	default:
6472 		ASSERT(0);
6473 	}
6474 
6475 	if (mcast_opt) {
6476 		gsreqp = (struct group_source_req *)i1;
6477 		ifindex = gsreqp->gsr_interface;
6478 		if (gsreqp->gsr_group.ss_family == AF_INET) {
6479 			struct sockaddr_in *s;
6480 			s = (struct sockaddr_in *)&gsreqp->gsr_group;
6481 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
6482 			s = (struct sockaddr_in *)&gsreqp->gsr_source;
6483 			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
6484 		} else {
6485 			struct sockaddr_in6 *s6;
6486 
6487 			if (!inet6)
6488 				return (EINVAL);	/* Not on INET socket */
6489 
6490 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
6491 			v6group = s6->sin6_addr;
6492 			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
6493 			v6src = s6->sin6_addr;
6494 		}
6495 		ifaddr = INADDR_ANY;
6496 	} else {
6497 		imreqp = (struct ip_mreq_source *)i1;
6498 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
6499 		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
6500 		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
6501 		ifindex = 0;
6502 	}
6503 
6504 	/*
6505 	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
6506 	 */
6507 	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
6508 		v6src = ipv6_all_zeros;
6509 
6510 	/*
6511 	 * In the multirouting case, we need to replicate
6512 	 * the request as noted in the mcast cases above.
6513 	 */
6514 	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
6515 		ipaddr_t group;
6516 
6517 		IN6_V4MAPPED_TO_IPADDR(&v6group, group);
6518 
6519 		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
6520 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6521 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6522 	} else {
6523 		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
6524 		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
6525 		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
6526 	}
6527 	if (ire != NULL) {
6528 		if (ire->ire_flags & RTF_MULTIRT) {
6529 			error = ip_multirt_apply_membership(optfn, ire, connp,
6530 			    checkonly, &v6group, fmode, &v6src);
6531 			done = B_TRUE;
6532 		}
6533 		ire_refrele(ire);
6534 	}
6535 	if (!done) {
6536 		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
6537 		    fmode, &v6src);
6538 	}
6539 	return (error);
6540 }
6541 
6542 /*
6543  * Given a destination address and a pointer to where to put the information
6544  * this routine fills in the mtuinfo.
6545  * The socket must be connected.
6546  * For sctp conn_faddr is the primary address.
6547  */
6548 int
6549 ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
6550 {
6551 	uint32_t	pmtu = IP_MAXPACKET;
6552 	uint_t		scopeid;
6553 
6554 	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
6555 		return (-1);
6556 
6557 	/* In case we never sent or called ip_set_destination_v4/v6 */
6558 	if (ixa->ixa_ire != NULL)
6559 		pmtu = ip_get_pmtu(ixa);
6560 
6561 	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
6562 		scopeid = ixa->ixa_scopeid;
6563 	else
6564 		scopeid = 0;
6565 
6566 	bzero(mtuinfo, sizeof (*mtuinfo));
6567 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
6568 	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
6569 	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
6570 	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
6571 	mtuinfo->ip6m_mtu = pmtu;
6572 
6573 	return (sizeof (struct ip6_mtuinfo));
6574 }
6575 
6576 /*
6577  * When the src multihoming is changed from weak to [strong, preferred]
6578  * ip_ire_rebind_walker is called to walk the list of all ire_t entries
6579  * and identify routes that were created by user-applications in the
6580  * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
6581  * currently defined. These routes are then 'rebound', i.e., their ire_ill
6582  * is selected by finding an interface route for the gateway.
6583  */
6584 /* ARGSUSED */
6585 void
6586 ip_ire_rebind_walker(ire_t *ire, void *notused)
6587 {
6588 	if (!ire->ire_unbound || ire->ire_ill != NULL)
6589 		return;
6590 	ire_rebind(ire);
6591 	ire_delete(ire);
6592 }
6593 
6594 /*
6595  * When the src multihoming is changed from  [strong, preferred] to weak,
6596  * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
6597  * set any entries that were created by user-applications in the unbound state
6598  * (i.e., without RTA_IFP) back to having a NULL ire_ill.
6599  */
6600 /* ARGSUSED */
6601 void
6602 ip_ire_unbind_walker(ire_t *ire, void *notused)
6603 {
6604 	ire_t *new_ire;
6605 
6606 	if (!ire->ire_unbound || ire->ire_ill == NULL)
6607 		return;
6608 	if (ire->ire_ipversion == IPV6_VERSION) {
6609 		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
6610 		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
6611 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6612 	} else {
6613 		new_ire = ire_create((uchar_t *)&ire->ire_addr,
6614 		    (uchar_t *)&ire->ire_mask,
6615 		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
6616 		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
6617 	}
6618 	if (new_ire == NULL)
6619 		return;
6620 	new_ire->ire_unbound = B_TRUE;
6621 	/*
6622 	 * The bound ire must first be deleted so that we don't return
6623 	 * the existing one on the attempt to add the unbound new_ire.
6624 	 */
6625 	ire_delete(ire);
6626 	new_ire = ire_add(new_ire);
6627 	if (new_ire != NULL)
6628 		ire_refrele(new_ire);
6629 }
6630 
6631 /*
6632  * When the settings of ip*_strict_src_multihoming tunables are changed,
6633  * all cached routes need to be recomputed. This recomputation needs to be
6634  * done when going from weaker to stronger modes so that the cached ire
6635  * for the connection does not violate the current ip*_strict_src_multihoming
6636  * setting. It also needs to be done when going from stronger to weaker modes,
6637  * so that we fall back to matching on the longest-matching-route (as opposed
6638  * to a shorter match that may have been selected in the strong mode
6639  * to satisfy src_multihoming settings).
6640  *
6641  * The cached ixa_ire entires for all conn_t entries are marked as
6642  * "verify" so that they will be recomputed for the next packet.
6643  */
6644 void
6645 conn_ire_revalidate(conn_t *connp, void *arg)
6646 {
6647 	boolean_t isv6 = (boolean_t)arg;
6648 
6649 	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
6650 	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
6651 		return;
6652 	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
6653 }
6654 
6655 /*
6656  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
6657  * When an ipf is passed here for the first time, if
6658  * we already have in-order fragments on the queue, we convert from the fast-
6659  * path reassembly scheme to the hard-case scheme.  From then on, additional
6660  * fragments are reassembled here.  We keep track of the start and end offsets
6661  * of each piece, and the number of holes in the chain.  When the hole count
6662  * goes to zero, we are done!
6663  *
6664  * The ipf_count will be updated to account for any mblk(s) added (pointed to
6665  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
6666  * ipfb_count and ill_frag_count by the difference of ipf_count before and
6667  * after the call to ip_reassemble().
6668  */
6669 int
6670 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
6671     size_t msg_len)
6672 {
6673 	uint_t	end;
6674 	mblk_t	*next_mp;
6675 	mblk_t	*mp1;
6676 	uint_t	offset;
6677 	boolean_t incr_dups = B_TRUE;
6678 	boolean_t offset_zero_seen = B_FALSE;
6679 	boolean_t pkt_boundary_checked = B_FALSE;
6680 
6681 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
6682 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
6683 
6684 	/* Add in byte count */
6685 	ipf->ipf_count += msg_len;
6686 	if (ipf->ipf_end) {
6687 		/*
6688 		 * We were part way through in-order reassembly, but now there
6689 		 * is a hole.  We walk through messages already queued, and
6690 		 * mark them for hard case reassembly.  We know that up till
6691 		 * now they were in order starting from offset zero.
6692 		 */
6693 		offset = 0;
6694 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6695 			IP_REASS_SET_START(mp1, offset);
6696 			if (offset == 0) {
6697 				ASSERT(ipf->ipf_nf_hdr_len != 0);
6698 				offset = -ipf->ipf_nf_hdr_len;
6699 			}
6700 			offset += mp1->b_wptr - mp1->b_rptr;
6701 			IP_REASS_SET_END(mp1, offset);
6702 		}
6703 		/* One hole at the end. */
6704 		ipf->ipf_hole_cnt = 1;
6705 		/* Brand it as a hard case, forever. */
6706 		ipf->ipf_end = 0;
6707 	}
6708 	/* Walk through all the new pieces. */
6709 	do {
6710 		end = start + (mp->b_wptr - mp->b_rptr);
6711 		/*
6712 		 * If start is 0, decrease 'end' only for the first mblk of
6713 		 * the fragment. Otherwise 'end' can get wrong value in the
6714 		 * second pass of the loop if first mblk is exactly the
6715 		 * size of ipf_nf_hdr_len.
6716 		 */
6717 		if (start == 0 && !offset_zero_seen) {
6718 			/* First segment */
6719 			ASSERT(ipf->ipf_nf_hdr_len != 0);
6720 			end -= ipf->ipf_nf_hdr_len;
6721 			offset_zero_seen = B_TRUE;
6722 		}
6723 		next_mp = mp->b_cont;
6724 		/*
6725 		 * We are checking to see if there is any interesing data
6726 		 * to process.  If there isn't and the mblk isn't the
6727 		 * one which carries the unfragmentable header then we
6728 		 * drop it.  It's possible to have just the unfragmentable
6729 		 * header come through without any data.  That needs to be
6730 		 * saved.
6731 		 *
6732 		 * If the assert at the top of this function holds then the
6733 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
6734 		 * is infrequently traveled enough that the test is left in
6735 		 * to protect against future code changes which break that
6736 		 * invariant.
6737 		 */
6738 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
6739 			/* Empty.  Blast it. */
6740 			IP_REASS_SET_START(mp, 0);
6741 			IP_REASS_SET_END(mp, 0);
6742 			/*
6743 			 * If the ipf points to the mblk we are about to free,
6744 			 * update ipf to point to the next mblk (or NULL
6745 			 * if none).
6746 			 */
6747 			if (ipf->ipf_mp->b_cont == mp)
6748 				ipf->ipf_mp->b_cont = next_mp;
6749 			freeb(mp);
6750 			continue;
6751 		}
6752 		mp->b_cont = NULL;
6753 		IP_REASS_SET_START(mp, start);
6754 		IP_REASS_SET_END(mp, end);
6755 		if (!ipf->ipf_tail_mp) {
6756 			ipf->ipf_tail_mp = mp;
6757 			ipf->ipf_mp->b_cont = mp;
6758 			if (start == 0 || !more) {
6759 				ipf->ipf_hole_cnt = 1;
6760 				/*
6761 				 * if the first fragment comes in more than one
6762 				 * mblk, this loop will be executed for each
6763 				 * mblk. Need to adjust hole count so exiting
6764 				 * this routine will leave hole count at 1.
6765 				 */
6766 				if (next_mp)
6767 					ipf->ipf_hole_cnt++;
6768 			} else
6769 				ipf->ipf_hole_cnt = 2;
6770 			continue;
6771 		} else if (ipf->ipf_last_frag_seen && !more &&
6772 		    !pkt_boundary_checked) {
6773 			/*
6774 			 * We check datagram boundary only if this fragment
6775 			 * claims to be the last fragment and we have seen a
6776 			 * last fragment in the past too. We do this only
6777 			 * once for a given fragment.
6778 			 *
6779 			 * start cannot be 0 here as fragments with start=0
6780 			 * and MF=0 gets handled as a complete packet. These
6781 			 * fragments should not reach here.
6782 			 */
6783 
6784 			if (start + msgdsize(mp) !=
6785 			    IP_REASS_END(ipf->ipf_tail_mp)) {
6786 				/*
6787 				 * We have two fragments both of which claim
6788 				 * to be the last fragment but gives conflicting
6789 				 * information about the whole datagram size.
6790 				 * Something fishy is going on. Drop the
6791 				 * fragment and free up the reassembly list.
6792 				 */
6793 				return (IP_REASS_FAILED);
6794 			}
6795 
6796 			/*
6797 			 * We shouldn't come to this code block again for this
6798 			 * particular fragment.
6799 			 */
6800 			pkt_boundary_checked = B_TRUE;
6801 		}
6802 
6803 		/* New stuff at or beyond tail? */
6804 		offset = IP_REASS_END(ipf->ipf_tail_mp);
6805 		if (start >= offset) {
6806 			if (ipf->ipf_last_frag_seen) {
6807 				/* current fragment is beyond last fragment */
6808 				return (IP_REASS_FAILED);
6809 			}
6810 			/* Link it on end. */
6811 			ipf->ipf_tail_mp->b_cont = mp;
6812 			ipf->ipf_tail_mp = mp;
6813 			if (more) {
6814 				if (start != offset)
6815 					ipf->ipf_hole_cnt++;
6816 			} else if (start == offset && next_mp == NULL)
6817 					ipf->ipf_hole_cnt--;
6818 			continue;
6819 		}
6820 		mp1 = ipf->ipf_mp->b_cont;
6821 		offset = IP_REASS_START(mp1);
6822 		/* New stuff at the front? */
6823 		if (start < offset) {
6824 			if (start == 0) {
6825 				if (end >= offset) {
6826 					/* Nailed the hole at the begining. */
6827 					ipf->ipf_hole_cnt--;
6828 				}
6829 			} else if (end < offset) {
6830 				/*
6831 				 * A hole, stuff, and a hole where there used
6832 				 * to be just a hole.
6833 				 */
6834 				ipf->ipf_hole_cnt++;
6835 			}
6836 			mp->b_cont = mp1;
6837 			/* Check for overlap. */
6838 			while (end > offset) {
6839 				if (end < IP_REASS_END(mp1)) {
6840 					mp->b_wptr -= end - offset;
6841 					IP_REASS_SET_END(mp, offset);
6842 					BUMP_MIB(ill->ill_ip_mib,
6843 					    ipIfStatsReasmPartDups);
6844 					break;
6845 				}
6846 				/* Did we cover another hole? */
6847 				if ((mp1->b_cont &&
6848 				    IP_REASS_END(mp1) !=
6849 				    IP_REASS_START(mp1->b_cont) &&
6850 				    end >= IP_REASS_START(mp1->b_cont)) ||
6851 				    (!ipf->ipf_last_frag_seen && !more)) {
6852 					ipf->ipf_hole_cnt--;
6853 				}
6854 				/* Clip out mp1. */
6855 				if ((mp->b_cont = mp1->b_cont) == NULL) {
6856 					/*
6857 					 * After clipping out mp1, this guy
6858 					 * is now hanging off the end.
6859 					 */
6860 					ipf->ipf_tail_mp = mp;
6861 				}
6862 				IP_REASS_SET_START(mp1, 0);
6863 				IP_REASS_SET_END(mp1, 0);
6864 				/* Subtract byte count */
6865 				ipf->ipf_count -= mp1->b_datap->db_lim -
6866 				    mp1->b_datap->db_base;
6867 				freeb(mp1);
6868 				BUMP_MIB(ill->ill_ip_mib,
6869 				    ipIfStatsReasmPartDups);
6870 				mp1 = mp->b_cont;
6871 				if (!mp1)
6872 					break;
6873 				offset = IP_REASS_START(mp1);
6874 			}
6875 			ipf->ipf_mp->b_cont = mp;
6876 			continue;
6877 		}
6878 		/*
6879 		 * The new piece starts somewhere between the start of the head
6880 		 * and before the end of the tail.
6881 		 */
6882 		for (; mp1; mp1 = mp1->b_cont) {
6883 			offset = IP_REASS_END(mp1);
6884 			if (start < offset) {
6885 				if (end <= offset) {
6886 					/* Nothing new. */
6887 					IP_REASS_SET_START(mp, 0);
6888 					IP_REASS_SET_END(mp, 0);
6889 					/* Subtract byte count */
6890 					ipf->ipf_count -= mp->b_datap->db_lim -
6891 					    mp->b_datap->db_base;
6892 					if (incr_dups) {
6893 						ipf->ipf_num_dups++;
6894 						incr_dups = B_FALSE;
6895 					}
6896 					freeb(mp);
6897 					BUMP_MIB(ill->ill_ip_mib,
6898 					    ipIfStatsReasmDuplicates);
6899 					break;
6900 				}
6901 				/*
6902 				 * Trim redundant stuff off beginning of new
6903 				 * piece.
6904 				 */
6905 				IP_REASS_SET_START(mp, offset);
6906 				mp->b_rptr += offset - start;
6907 				BUMP_MIB(ill->ill_ip_mib,
6908 				    ipIfStatsReasmPartDups);
6909 				start = offset;
6910 				if (!mp1->b_cont) {
6911 					/*
6912 					 * After trimming, this guy is now
6913 					 * hanging off the end.
6914 					 */
6915 					mp1->b_cont = mp;
6916 					ipf->ipf_tail_mp = mp;
6917 					if (!more) {
6918 						ipf->ipf_hole_cnt--;
6919 					}
6920 					break;
6921 				}
6922 			}
6923 			if (start >= IP_REASS_START(mp1->b_cont))
6924 				continue;
6925 			/* Fill a hole */
6926 			if (start > offset)
6927 				ipf->ipf_hole_cnt++;
6928 			mp->b_cont = mp1->b_cont;
6929 			mp1->b_cont = mp;
6930 			mp1 = mp->b_cont;
6931 			offset = IP_REASS_START(mp1);
6932 			if (end >= offset) {
6933 				ipf->ipf_hole_cnt--;
6934 				/* Check for overlap. */
6935 				while (end > offset) {
6936 					if (end < IP_REASS_END(mp1)) {
6937 						mp->b_wptr -= end - offset;
6938 						IP_REASS_SET_END(mp, offset);
6939 						/*
6940 						 * TODO we might bump
6941 						 * this up twice if there is
6942 						 * overlap at both ends.
6943 						 */
6944 						BUMP_MIB(ill->ill_ip_mib,
6945 						    ipIfStatsReasmPartDups);
6946 						break;
6947 					}
6948 					/* Did we cover another hole? */
6949 					if ((mp1->b_cont &&
6950 					    IP_REASS_END(mp1)
6951 					    != IP_REASS_START(mp1->b_cont) &&
6952 					    end >=
6953 					    IP_REASS_START(mp1->b_cont)) ||
6954 					    (!ipf->ipf_last_frag_seen &&
6955 					    !more)) {
6956 						ipf->ipf_hole_cnt--;
6957 					}
6958 					/* Clip out mp1. */
6959 					if ((mp->b_cont = mp1->b_cont) ==
6960 					    NULL) {
6961 						/*
6962 						 * After clipping out mp1,
6963 						 * this guy is now hanging
6964 						 * off the end.
6965 						 */
6966 						ipf->ipf_tail_mp = mp;
6967 					}
6968 					IP_REASS_SET_START(mp1, 0);
6969 					IP_REASS_SET_END(mp1, 0);
6970 					/* Subtract byte count */
6971 					ipf->ipf_count -=
6972 					    mp1->b_datap->db_lim -
6973 					    mp1->b_datap->db_base;
6974 					freeb(mp1);
6975 					BUMP_MIB(ill->ill_ip_mib,
6976 					    ipIfStatsReasmPartDups);
6977 					mp1 = mp->b_cont;
6978 					if (!mp1)
6979 						break;
6980 					offset = IP_REASS_START(mp1);
6981 				}
6982 			}
6983 			break;
6984 		}
6985 	} while (start = end, mp = next_mp);
6986 
6987 	/* Fragment just processed could be the last one. Remember this fact */
6988 	if (!more)
6989 		ipf->ipf_last_frag_seen = B_TRUE;
6990 
6991 	/* Still got holes? */
6992 	if (ipf->ipf_hole_cnt)
6993 		return (IP_REASS_PARTIAL);
6994 	/* Clean up overloaded fields to avoid upstream disasters. */
6995 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
6996 		IP_REASS_SET_START(mp1, 0);
6997 		IP_REASS_SET_END(mp1, 0);
6998 	}
6999 	return (IP_REASS_COMPLETE);
7000 }
7001 
7002 /*
7003  * Fragmentation reassembly.  Each ILL has a hash table for
7004  * queuing packets undergoing reassembly for all IPIFs
7005  * associated with the ILL.  The hash is based on the packet
7006  * IP ident field.  The ILL frag hash table was allocated
7007  * as a timer block at the time the ILL was created.  Whenever
7008  * there is anything on the reassembly queue, the timer will
7009  * be running.  Returns the reassembled packet if reassembly completes.
7010  */
7011 mblk_t *
7012 ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
7013 {
7014 	uint32_t	frag_offset_flags;
7015 	mblk_t		*t_mp;
7016 	ipaddr_t	dst;
7017 	uint8_t		proto = ipha->ipha_protocol;
7018 	uint32_t	sum_val;
7019 	uint16_t	sum_flags;
7020 	ipf_t		*ipf;
7021 	ipf_t		**ipfp;
7022 	ipfb_t		*ipfb;
7023 	uint16_t	ident;
7024 	uint32_t	offset;
7025 	ipaddr_t	src;
7026 	uint_t		hdr_length;
7027 	uint32_t	end;
7028 	mblk_t		*mp1;
7029 	mblk_t		*tail_mp;
7030 	size_t		count;
7031 	size_t		msg_len;
7032 	uint8_t		ecn_info = 0;
7033 	uint32_t	packet_size;
7034 	boolean_t	pruned = B_FALSE;
7035 	ill_t		*ill = ira->ira_ill;
7036 	ip_stack_t	*ipst = ill->ill_ipst;
7037 
7038 	/*
7039 	 * Drop the fragmented as early as possible, if
7040 	 * we don't have resource(s) to re-assemble.
7041 	 */
7042 	if (ipst->ips_ip_reass_queue_bytes == 0) {
7043 		freemsg(mp);
7044 		return (NULL);
7045 	}
7046 
7047 	/* Check for fragmentation offset; return if there's none */
7048 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
7049 	    (IPH_MF | IPH_OFFSET)) == 0)
7050 		return (mp);
7051 
7052 	/*
7053 	 * We utilize hardware computed checksum info only for UDP since
7054 	 * IP fragmentation is a normal occurrence for the protocol.  In
7055 	 * addition, checksum offload support for IP fragments carrying
7056 	 * UDP payload is commonly implemented across network adapters.
7057 	 */
7058 	ASSERT(ira->ira_rill != NULL);
7059 	if (proto == IPPROTO_UDP && dohwcksum &&
7060 	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
7061 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
7062 		mblk_t *mp1 = mp->b_cont;
7063 		int32_t len;
7064 
7065 		/* Record checksum information from the packet */
7066 		sum_val = (uint32_t)DB_CKSUM16(mp);
7067 		sum_flags = DB_CKSUMFLAGS(mp);
7068 
7069 		/* IP payload offset from beginning of mblk */
7070 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
7071 
7072 		if ((sum_flags & HCK_PARTIALCKSUM) &&
7073 		    (mp1 == NULL || mp1->b_cont == NULL) &&
7074 		    offset >= DB_CKSUMSTART(mp) &&
7075 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
7076 			uint32_t adj;
7077 			/*
7078 			 * Partial checksum has been calculated by hardware
7079 			 * and attached to the packet; in addition, any
7080 			 * prepended extraneous data is even byte aligned.
7081 			 * If any such data exists, we adjust the checksum;
7082 			 * this would also handle any postpended data.
7083 			 */
7084 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
7085 			    mp, mp1, len, adj);
7086 
7087 			/* One's complement subtract extraneous checksum */
7088 			if (adj >= sum_val)
7089 				sum_val = ~(adj - sum_val) & 0xFFFF;
7090 			else
7091 				sum_val -= adj;
7092 		}
7093 	} else {
7094 		sum_val = 0;
7095 		sum_flags = 0;
7096 	}
7097 
7098 	/* Clear hardware checksumming flag */
7099 	DB_CKSUMFLAGS(mp) = 0;
7100 
7101 	ident = ipha->ipha_ident;
7102 	offset = (frag_offset_flags << 3) & 0xFFFF;
7103 	src = ipha->ipha_src;
7104 	dst = ipha->ipha_dst;
7105 	hdr_length = IPH_HDR_LENGTH(ipha);
7106 	end = ntohs(ipha->ipha_length) - hdr_length;
7107 
7108 	/* If end == 0 then we have a packet with no data, so just free it */
7109 	if (end == 0) {
7110 		freemsg(mp);
7111 		return (NULL);
7112 	}
7113 
7114 	/* Record the ECN field info. */
7115 	ecn_info = (ipha->ipha_type_of_service & 0x3);
7116 	if (offset != 0) {
7117 		/*
7118 		 * If this isn't the first piece, strip the header, and
7119 		 * add the offset to the end value.
7120 		 */
7121 		mp->b_rptr += hdr_length;
7122 		end += offset;
7123 	}
7124 
7125 	/* Handle vnic loopback of fragments */
7126 	if (mp->b_datap->db_ref > 2)
7127 		msg_len = 0;
7128 	else
7129 		msg_len = MBLKSIZE(mp);
7130 
7131 	tail_mp = mp;
7132 	while (tail_mp->b_cont != NULL) {
7133 		tail_mp = tail_mp->b_cont;
7134 		if (tail_mp->b_datap->db_ref <= 2)
7135 			msg_len += MBLKSIZE(tail_mp);
7136 	}
7137 
7138 	/* If the reassembly list for this ILL will get too big, prune it */
7139 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
7140 	    ipst->ips_ip_reass_queue_bytes) {
7141 		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
7142 		    uint_t, ill->ill_frag_count,
7143 		    uint_t, ipst->ips_ip_reass_queue_bytes);
7144 		ill_frag_prune(ill,
7145 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
7146 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
7147 		pruned = B_TRUE;
7148 	}
7149 
7150 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
7151 	mutex_enter(&ipfb->ipfb_lock);
7152 
7153 	ipfp = &ipfb->ipfb_ipf;
7154 	/* Try to find an existing fragment queue for this packet. */
7155 	for (;;) {
7156 		ipf = ipfp[0];
7157 		if (ipf != NULL) {
7158 			/*
7159 			 * It has to match on ident and src/dst address.
7160 			 */
7161 			if (ipf->ipf_ident == ident &&
7162 			    ipf->ipf_src == src &&
7163 			    ipf->ipf_dst == dst &&
7164 			    ipf->ipf_protocol == proto) {
7165 				/*
7166 				 * If we have received too many
7167 				 * duplicate fragments for this packet
7168 				 * free it.
7169 				 */
7170 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
7171 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
7172 					freemsg(mp);
7173 					mutex_exit(&ipfb->ipfb_lock);
7174 					return (NULL);
7175 				}
7176 				/* Found it. */
7177 				break;
7178 			}
7179 			ipfp = &ipf->ipf_hash_next;
7180 			continue;
7181 		}
7182 
7183 		/*
7184 		 * If we pruned the list, do we want to store this new
7185 		 * fragment?. We apply an optimization here based on the
7186 		 * fact that most fragments will be received in order.
7187 		 * So if the offset of this incoming fragment is zero,
7188 		 * it is the first fragment of a new packet. We will
7189 		 * keep it.  Otherwise drop the fragment, as we have
7190 		 * probably pruned the packet already (since the
7191 		 * packet cannot be found).
7192 		 */
7193 		if (pruned && offset != 0) {
7194 			mutex_exit(&ipfb->ipfb_lock);
7195 			freemsg(mp);
7196 			return (NULL);
7197 		}
7198 
7199 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
7200 			/*
7201 			 * Too many fragmented packets in this hash
7202 			 * bucket. Free the oldest.
7203 			 */
7204 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
7205 		}
7206 
7207 		/* New guy.  Allocate a frag message. */
7208 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
7209 		if (mp1 == NULL) {
7210 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7211 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7212 			freemsg(mp);
7213 reass_done:
7214 			mutex_exit(&ipfb->ipfb_lock);
7215 			return (NULL);
7216 		}
7217 
7218 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
7219 		mp1->b_cont = mp;
7220 
7221 		/* Initialize the fragment header. */
7222 		ipf = (ipf_t *)mp1->b_rptr;
7223 		ipf->ipf_mp = mp1;
7224 		ipf->ipf_ptphn = ipfp;
7225 		ipfp[0] = ipf;
7226 		ipf->ipf_hash_next = NULL;
7227 		ipf->ipf_ident = ident;
7228 		ipf->ipf_protocol = proto;
7229 		ipf->ipf_src = src;
7230 		ipf->ipf_dst = dst;
7231 		ipf->ipf_nf_hdr_len = 0;
7232 		/* Record reassembly start time. */
7233 		ipf->ipf_timestamp = gethrestime_sec();
7234 		/* Record ipf generation and account for frag header */
7235 		ipf->ipf_gen = ill->ill_ipf_gen++;
7236 		ipf->ipf_count = MBLKSIZE(mp1);
7237 		ipf->ipf_last_frag_seen = B_FALSE;
7238 		ipf->ipf_ecn = ecn_info;
7239 		ipf->ipf_num_dups = 0;
7240 		ipfb->ipfb_frag_pkts++;
7241 		ipf->ipf_checksum = 0;
7242 		ipf->ipf_checksum_flags = 0;
7243 
7244 		/* Store checksum value in fragment header */
7245 		if (sum_flags != 0) {
7246 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7247 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7248 			ipf->ipf_checksum = sum_val;
7249 			ipf->ipf_checksum_flags = sum_flags;
7250 		}
7251 
7252 		/*
7253 		 * We handle reassembly two ways.  In the easy case,
7254 		 * where all the fragments show up in order, we do
7255 		 * minimal bookkeeping, and just clip new pieces on
7256 		 * the end.  If we ever see a hole, then we go off
7257 		 * to ip_reassemble which has to mark the pieces and
7258 		 * keep track of the number of holes, etc.  Obviously,
7259 		 * the point of having both mechanisms is so we can
7260 		 * handle the easy case as efficiently as possible.
7261 		 */
7262 		if (offset == 0) {
7263 			/* Easy case, in-order reassembly so far. */
7264 			ipf->ipf_count += msg_len;
7265 			ipf->ipf_tail_mp = tail_mp;
7266 			/*
7267 			 * Keep track of next expected offset in
7268 			 * ipf_end.
7269 			 */
7270 			ipf->ipf_end = end;
7271 			ipf->ipf_nf_hdr_len = hdr_length;
7272 		} else {
7273 			/* Hard case, hole at the beginning. */
7274 			ipf->ipf_tail_mp = NULL;
7275 			/*
7276 			 * ipf_end == 0 means that we have given up
7277 			 * on easy reassembly.
7278 			 */
7279 			ipf->ipf_end = 0;
7280 
7281 			/* Forget checksum offload from now on */
7282 			ipf->ipf_checksum_flags = 0;
7283 
7284 			/*
7285 			 * ipf_hole_cnt is set by ip_reassemble.
7286 			 * ipf_count is updated by ip_reassemble.
7287 			 * No need to check for return value here
7288 			 * as we don't expect reassembly to complete
7289 			 * or fail for the first fragment itself.
7290 			 */
7291 			(void) ip_reassemble(mp, ipf,
7292 			    (frag_offset_flags & IPH_OFFSET) << 3,
7293 			    (frag_offset_flags & IPH_MF), ill, msg_len);
7294 		}
7295 		/* Update per ipfb and ill byte counts */
7296 		ipfb->ipfb_count += ipf->ipf_count;
7297 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7298 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
7299 		/* If the frag timer wasn't already going, start it. */
7300 		mutex_enter(&ill->ill_lock);
7301 		ill_frag_timer_start(ill);
7302 		mutex_exit(&ill->ill_lock);
7303 		goto reass_done;
7304 	}
7305 
7306 	/*
7307 	 * If the packet's flag has changed (it could be coming up
7308 	 * from an interface different than the previous, therefore
7309 	 * possibly different checksum capability), then forget about
7310 	 * any stored checksum states.  Otherwise add the value to
7311 	 * the existing one stored in the fragment header.
7312 	 */
7313 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
7314 		sum_val += ipf->ipf_checksum;
7315 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7316 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
7317 		ipf->ipf_checksum = sum_val;
7318 	} else if (ipf->ipf_checksum_flags != 0) {
7319 		/* Forget checksum offload from now on */
7320 		ipf->ipf_checksum_flags = 0;
7321 	}
7322 
7323 	/*
7324 	 * We have a new piece of a datagram which is already being
7325 	 * reassembled.  Update the ECN info if all IP fragments
7326 	 * are ECN capable.  If there is one which is not, clear
7327 	 * all the info.  If there is at least one which has CE
7328 	 * code point, IP needs to report that up to transport.
7329 	 */
7330 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
7331 		if (ecn_info == IPH_ECN_CE)
7332 			ipf->ipf_ecn = IPH_ECN_CE;
7333 	} else {
7334 		ipf->ipf_ecn = IPH_ECN_NECT;
7335 	}
7336 	if (offset && ipf->ipf_end == offset) {
7337 		/* The new fragment fits at the end */
7338 		ipf->ipf_tail_mp->b_cont = mp;
7339 		/* Update the byte count */
7340 		ipf->ipf_count += msg_len;
7341 		/* Update per ipfb and ill byte counts */
7342 		ipfb->ipfb_count += msg_len;
7343 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
7344 		atomic_add_32(&ill->ill_frag_count, msg_len);
7345 		if (frag_offset_flags & IPH_MF) {
7346 			/* More to come. */
7347 			ipf->ipf_end = end;
7348 			ipf->ipf_tail_mp = tail_mp;
7349 			goto reass_done;
7350 		}
7351 	} else {
7352 		/* Go do the hard cases. */
7353 		int ret;
7354 
7355 		if (offset == 0)
7356 			ipf->ipf_nf_hdr_len = hdr_length;
7357 
7358 		/* Save current byte count */
7359 		count = ipf->ipf_count;
7360 		ret = ip_reassemble(mp, ipf,
7361 		    (frag_offset_flags & IPH_OFFSET) << 3,
7362 		    (frag_offset_flags & IPH_MF), ill, msg_len);
7363 		/* Count of bytes added and subtracted (freeb()ed) */
7364 		count = ipf->ipf_count - count;
7365 		if (count) {
7366 			/* Update per ipfb and ill byte counts */
7367 			ipfb->ipfb_count += count;
7368 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
7369 			atomic_add_32(&ill->ill_frag_count, count);
7370 		}
7371 		if (ret == IP_REASS_PARTIAL) {
7372 			goto reass_done;
7373 		} else if (ret == IP_REASS_FAILED) {
7374 			/* Reassembly failed. Free up all resources */
7375 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
7376 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
7377 				IP_REASS_SET_START(t_mp, 0);
7378 				IP_REASS_SET_END(t_mp, 0);
7379 			}
7380 			freemsg(mp);
7381 			goto reass_done;
7382 		}
7383 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
7384 	}
7385 	/*
7386 	 * We have completed reassembly.  Unhook the frag header from
7387 	 * the reassembly list.
7388 	 *
7389 	 * Before we free the frag header, record the ECN info
7390 	 * to report back to the transport.
7391 	 */
7392 	ecn_info = ipf->ipf_ecn;
7393 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
7394 	ipfp = ipf->ipf_ptphn;
7395 
7396 	/* We need to supply these to caller */
7397 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
7398 		sum_val = ipf->ipf_checksum;
7399 	else
7400 		sum_val = 0;
7401 
7402 	mp1 = ipf->ipf_mp;
7403 	count = ipf->ipf_count;
7404 	ipf = ipf->ipf_hash_next;
7405 	if (ipf != NULL)
7406 		ipf->ipf_ptphn = ipfp;
7407 	ipfp[0] = ipf;
7408 	atomic_add_32(&ill->ill_frag_count, -count);
7409 	ASSERT(ipfb->ipfb_count >= count);
7410 	ipfb->ipfb_count -= count;
7411 	ipfb->ipfb_frag_pkts--;
7412 	mutex_exit(&ipfb->ipfb_lock);
7413 	/* Ditch the frag header. */
7414 	mp = mp1->b_cont;
7415 
7416 	freeb(mp1);
7417 
7418 	/* Restore original IP length in header. */
7419 	packet_size = (uint32_t)msgdsize(mp);
7420 	if (packet_size > IP_MAXPACKET) {
7421 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7422 		ip_drop_input("Reassembled packet too large", mp, ill);
7423 		freemsg(mp);
7424 		return (NULL);
7425 	}
7426 
7427 	if (DB_REF(mp) > 1) {
7428 		mblk_t *mp2 = copymsg(mp);
7429 
7430 		if (mp2 == NULL) {
7431 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7432 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7433 			freemsg(mp);
7434 			return (NULL);
7435 		}
7436 		freemsg(mp);
7437 		mp = mp2;
7438 	}
7439 	ipha = (ipha_t *)mp->b_rptr;
7440 
7441 	ipha->ipha_length = htons((uint16_t)packet_size);
7442 	/* We're now complete, zip the frag state */
7443 	ipha->ipha_fragment_offset_and_flags = 0;
7444 	/* Record the ECN info. */
7445 	ipha->ipha_type_of_service &= 0xFC;
7446 	ipha->ipha_type_of_service |= ecn_info;
7447 
7448 	/* Update the receive attributes */
7449 	ira->ira_pktlen = packet_size;
7450 	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
7451 
7452 	/* Reassembly is successful; set checksum information in packet */
7453 	DB_CKSUM16(mp) = (uint16_t)sum_val;
7454 	DB_CKSUMFLAGS(mp) = sum_flags;
7455 	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;
7456 
7457 	return (mp);
7458 }
7459 
7460 /*
7461  * Pullup function that should be used for IP input in order to
7462  * ensure we do not loose the L2 source address; we need the l2 source
7463  * address for IP_RECVSLLA and for ndp_input.
7464  *
7465  * We return either NULL or b_rptr.
7466  */
7467 void *
7468 ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
7469 {
7470 	ill_t		*ill = ira->ira_ill;
7471 
7472 	if (ip_rput_pullups++ == 0) {
7473 		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
7474 		    "ip_pullup: %s forced us to "
7475 		    " pullup pkt, hdr len %ld, hdr addr %p",
7476 		    ill->ill_name, len, (void *)mp->b_rptr);
7477 	}
7478 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
7479 		ip_setl2src(mp, ira, ira->ira_rill);
7480 	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7481 	if (!pullupmsg(mp, len))
7482 		return (NULL);
7483 	else
7484 		return (mp->b_rptr);
7485 }
7486 
7487 /*
7488  * Make sure ira_l2src has an address. If we don't have one fill with zeros.
7489  * When called from the ULP ira_rill will be NULL hence the caller has to
7490  * pass in the ill.
7491  */
7492 /* ARGSUSED */
7493 void
7494 ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
7495 {
7496 	const uchar_t *addr;
7497 	int alen;
7498 
7499 	if (ira->ira_flags & IRAF_L2SRC_SET)
7500 		return;
7501 
7502 	ASSERT(ill != NULL);
7503 	alen = ill->ill_phys_addr_length;
7504 	ASSERT(alen <= sizeof (ira->ira_l2src));
7505 	if (ira->ira_mhip != NULL &&
7506 	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
7507 		bcopy(addr, ira->ira_l2src, alen);
7508 	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
7509 	    (addr = ill->ill_phys_addr) != NULL) {
7510 		bcopy(addr, ira->ira_l2src, alen);
7511 	} else {
7512 		bzero(ira->ira_l2src, alen);
7513 	}
7514 	ira->ira_flags |= IRAF_L2SRC_SET;
7515 }
7516 
7517 /*
7518  * check ip header length and align it.
7519  */
7520 mblk_t *
7521 ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
7522 {
7523 	ill_t	*ill = ira->ira_ill;
7524 	ssize_t len;
7525 
7526 	len = MBLKL(mp);
7527 
7528 	if (!OK_32PTR(mp->b_rptr))
7529 		IP_STAT(ill->ill_ipst, ip_notaligned);
7530 	else
7531 		IP_STAT(ill->ill_ipst, ip_recv_pullup);
7532 
7533 	/* Guard against bogus device drivers */
7534 	if (len < 0) {
7535 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7536 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7537 		freemsg(mp);
7538 		return (NULL);
7539 	}
7540 
7541 	if (len == 0) {
7542 		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
7543 		mblk_t *mp1 = mp->b_cont;
7544 
7545 		if (!(ira->ira_flags & IRAF_L2SRC_SET))
7546 			ip_setl2src(mp, ira, ira->ira_rill);
7547 		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
7548 
7549 		freeb(mp);
7550 		mp = mp1;
7551 		if (mp == NULL)
7552 			return (NULL);
7553 
7554 		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
7555 			return (mp);
7556 	}
7557 	if (ip_pullup(mp, min_size, ira) == NULL) {
7558 		if (msgdsize(mp) < min_size) {
7559 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7560 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7561 		} else {
7562 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7563 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7564 		}
7565 		freemsg(mp);
7566 		return (NULL);
7567 	}
7568 	return (mp);
7569 }
7570 
7571 /*
7572  * Common code for IPv4 and IPv6 to check and pullup multi-mblks
7573  */
7574 mblk_t *
7575 ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
7576     uint_t min_size, ip_recv_attr_t *ira)
7577 {
7578 	ill_t	*ill = ira->ira_ill;
7579 
7580 	/*
7581 	 * Make sure we have data length consistent
7582 	 * with the IP header.
7583 	 */
7584 	if (mp->b_cont == NULL) {
7585 		/* pkt_len is based on ipha_len, not the mblk length */
7586 		if (pkt_len < min_size) {
7587 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7588 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7589 			freemsg(mp);
7590 			return (NULL);
7591 		}
7592 		if (len < 0) {
7593 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7594 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7595 			freemsg(mp);
7596 			return (NULL);
7597 		}
7598 		/* Drop any pad */
7599 		mp->b_wptr = rptr + pkt_len;
7600 	} else if ((len += msgdsize(mp->b_cont)) != 0) {
7601 		ASSERT(pkt_len >= min_size);
7602 		if (pkt_len < min_size) {
7603 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7604 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7605 			freemsg(mp);
7606 			return (NULL);
7607 		}
7608 		if (len < 0) {
7609 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
7610 			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
7611 			freemsg(mp);
7612 			return (NULL);
7613 		}
7614 		/* Drop any pad */
7615 		(void) adjmsg(mp, -len);
7616 		/*
7617 		 * adjmsg may have freed an mblk from the chain, hence
7618 		 * invalidate any hw checksum here. This will force IP to
7619 		 * calculate the checksum in sw, but only for this packet.
7620 		 */
7621 		DB_CKSUMFLAGS(mp) = 0;
7622 		IP_STAT(ill->ill_ipst, ip_multimblk);
7623 	}
7624 	return (mp);
7625 }
7626 
7627 /*
7628  * Check that the IPv4 opt_len is consistent with the packet and pullup
7629  * the options.
7630  */
7631 mblk_t *
7632 ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
7633     ip_recv_attr_t *ira)
7634 {
7635 	ill_t	*ill = ira->ira_ill;
7636 	ssize_t len;
7637 
7638 	/* Assume no IPv6 packets arrive over the IPv4 queue */
7639 	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
7640 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7641 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
7642 		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
7643 		freemsg(mp);
7644 		return (NULL);
7645 	}
7646 
7647 	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
7648 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7649 		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7650 		freemsg(mp);
7651 		return (NULL);
7652 	}
7653 	/*
7654 	 * Recompute complete header length and make sure we
7655 	 * have access to all of it.
7656 	 */
7657 	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
7658 	if (len > (mp->b_wptr - mp->b_rptr)) {
7659 		if (len > pkt_len) {
7660 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
7661 			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
7662 			freemsg(mp);
7663 			return (NULL);
7664 		}
7665 		if (ip_pullup(mp, len, ira) == NULL) {
7666 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7667 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
7668 			freemsg(mp);
7669 			return (NULL);
7670 		}
7671 	}
7672 	return (mp);
7673 }
7674 
7675 /*
7676  * Returns a new ire, or the same ire, or NULL.
7677  * If a different IRE is returned, then it is held; the caller
7678  * needs to release it.
7679  * In no case is there any hold/release on the ire argument.
7680  */
7681 ire_t *
7682 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
7683 {
7684 	ire_t		*new_ire;
7685 	ill_t		*ire_ill;
7686 	uint_t		ifindex;
7687 	ip_stack_t	*ipst = ill->ill_ipst;
7688 	boolean_t	strict_check = B_FALSE;
7689 
7690 	/*
7691 	 * IPMP common case: if IRE and ILL are in the same group, there's no
7692 	 * issue (e.g. packet received on an underlying interface matched an
7693 	 * IRE_LOCAL on its associated group interface).
7694 	 */
7695 	ASSERT(ire->ire_ill != NULL);
7696 	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
7697 		return (ire);
7698 
7699 	/*
7700 	 * Do another ire lookup here, using the ingress ill, to see if the
7701 	 * interface is in a usesrc group.
7702 	 * As long as the ills belong to the same group, we don't consider
7703 	 * them to be arriving on the wrong interface. Thus, if the switch
7704 	 * is doing inbound load spreading, we won't drop packets when the
7705 	 * ip*_strict_dst_multihoming switch is on.
7706 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
7707 	 * where the local address may not be unique. In this case we were
7708 	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
7709 	 * actually returned. The new lookup, which is more specific, should
7710 	 * only find the IRE_LOCAL associated with the ingress ill if one
7711 	 * exists.
7712 	 */
7713 	if (ire->ire_ipversion == IPV4_VERSION) {
7714 		if (ipst->ips_ip_strict_dst_multihoming)
7715 			strict_check = B_TRUE;
7716 		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
7717 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7718 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7719 	} else {
7720 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
7721 		if (ipst->ips_ipv6_strict_dst_multihoming)
7722 			strict_check = B_TRUE;
7723 		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
7724 		    IRE_LOCAL, ill, ALL_ZONES, NULL,
7725 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
7726 	}
7727 	/*
7728 	 * If the same ire that was returned in ip_input() is found then this
7729 	 * is an indication that usesrc groups are in use. The packet
7730 	 * arrived on a different ill in the group than the one associated with
7731 	 * the destination address.  If a different ire was found then the same
7732 	 * IP address must be hosted on multiple ills. This is possible with
7733 	 * unnumbered point2point interfaces. We switch to use this new ire in
7734 	 * order to have accurate interface statistics.
7735 	 */
7736 	if (new_ire != NULL) {
7737 		/* Note: held in one case but not the other? Caller handles */
7738 		if (new_ire != ire)
7739 			return (new_ire);
7740 		/* Unchanged */
7741 		ire_refrele(new_ire);
7742 		return (ire);
7743 	}
7744 
7745 	/*
7746 	 * Chase pointers once and store locally.
7747 	 */
7748 	ASSERT(ire->ire_ill != NULL);
7749 	ire_ill = ire->ire_ill;
7750 	ifindex = ill->ill_usesrc_ifindex;
7751 
7752 	/*
7753 	 * Check if it's a legal address on the 'usesrc' interface.
7754 	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
7755 	 * can just check phyint_ifindex.
7756 	 */
7757 	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
7758 		return (ire);
7759 	}
7760 
7761 	/*
7762 	 * If the ip*_strict_dst_multihoming switch is on then we can
7763 	 * only accept this packet if the interface is marked as routing.
7764 	 */
7765 	if (!(strict_check))
7766 		return (ire);
7767 
7768 	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
7769 		return (ire);
7770 	}
7771 	return (NULL);
7772 }
7773 
7774 /*
7775  * This function is used to construct a mac_header_info_s from a
7776  * DL_UNITDATA_IND message.
7777  * The address fields in the mhi structure points into the message,
7778  * thus the caller can't use those fields after freeing the message.
7779  *
7780  * We determine whether the packet received is a non-unicast packet
7781  * and in doing so, determine whether or not it is broadcast vs multicast.
7782  * For it to be a broadcast packet, we must have the appropriate mblk_t
7783  * hanging off the ill_t.  If this is either not present or doesn't match
7784  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7785  * to be multicast.  Thus NICs that have no broadcast address (or no
7786  * capability for one, such as point to point links) cannot return as
7787  * the packet being broadcast.
7788  */
7789 void
7790 ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
7791 {
7792 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
7793 	mblk_t *bmp;
7794 	uint_t extra_offset;
7795 
7796 	bzero(mhip, sizeof (struct mac_header_info_s));
7797 
7798 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7799 
7800 	if (ill->ill_sap_length < 0)
7801 		extra_offset = 0;
7802 	else
7803 		extra_offset = ill->ill_sap_length;
7804 
7805 	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
7806 	    extra_offset;
7807 	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
7808 	    extra_offset;
7809 
7810 	if (!ind->dl_group_address)
7811 		return;
7812 
7813 	/* Multicast or broadcast */
7814 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7815 
7816 	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
7817 	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
7818 	    (bmp = ill->ill_bcast_mp) != NULL) {
7819 		dl_unitdata_req_t *dlur;
7820 		uint8_t *bphys_addr;
7821 
7822 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7823 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
7824 		    extra_offset;
7825 
7826 		if (bcmp(mhip->mhi_daddr, bphys_addr,
7827 		    ind->dl_dest_addr_length) == 0)
7828 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7829 	}
7830 }
7831 
7832 /*
7833  * This function is used to construct a mac_header_info_s from a
7834  * M_DATA fastpath message from a DLPI driver.
7835  * The address fields in the mhi structure points into the message,
7836  * thus the caller can't use those fields after freeing the message.
7837  *
7838  * We determine whether the packet received is a non-unicast packet
7839  * and in doing so, determine whether or not it is broadcast vs multicast.
7840  * For it to be a broadcast packet, we must have the appropriate mblk_t
7841  * hanging off the ill_t.  If this is either not present or doesn't match
7842  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
7843  * to be multicast.  Thus NICs that have no broadcast address (or no
7844  * capability for one, such as point to point links) cannot return as
7845  * the packet being broadcast.
7846  */
7847 void
7848 ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
7849 {
7850 	mblk_t *bmp;
7851 	struct ether_header *pether;
7852 
7853 	bzero(mhip, sizeof (struct mac_header_info_s));
7854 
7855 	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;
7856 
7857 	pether = (struct ether_header *)((char *)mp->b_rptr
7858 	    - sizeof (struct ether_header));
7859 
7860 	/*
7861 	 * Make sure the interface is an ethernet type, since we don't
7862 	 * know the header format for anything but Ethernet. Also make
7863 	 * sure we are pointing correctly above db_base.
7864 	 */
7865 	if (ill->ill_type != IFT_ETHER)
7866 		return;
7867 
7868 retry:
7869 	if ((uchar_t *)pether < mp->b_datap->db_base)
7870 		return;
7871 
7872 	/* Is there a VLAN tag? */
7873 	if (ill->ill_isv6) {
7874 		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
7875 			pether = (struct ether_header *)((char *)pether - 4);
7876 			goto retry;
7877 		}
7878 	} else {
7879 		if (pether->ether_type != htons(ETHERTYPE_IP)) {
7880 			pether = (struct ether_header *)((char *)pether - 4);
7881 			goto retry;
7882 		}
7883 	}
7884 	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
7885 	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;
7886 
7887 	if (!(mhip->mhi_daddr[0] & 0x01))
7888 		return;
7889 
7890 	/* Multicast or broadcast */
7891 	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;
7892 
7893 	if ((bmp = ill->ill_bcast_mp) != NULL) {
7894 		dl_unitdata_req_t *dlur;
7895 		uint8_t *bphys_addr;
7896 		uint_t	addrlen;
7897 
7898 		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
7899 		addrlen = dlur->dl_dest_addr_length;
7900 		if (ill->ill_sap_length < 0) {
7901 			bphys_addr = (uchar_t *)dlur +
7902 			    dlur->dl_dest_addr_offset;
7903 			addrlen += ill->ill_sap_length;
7904 		} else {
7905 			bphys_addr = (uchar_t *)dlur +
7906 			    dlur->dl_dest_addr_offset +
7907 			    ill->ill_sap_length;
7908 			addrlen -= ill->ill_sap_length;
7909 		}
7910 		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
7911 			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
7912 	}
7913 }
7914 
7915 /*
7916  * Handle anything but M_DATA messages
7917  * We see the DL_UNITDATA_IND which are part
7918  * of the data path, and also the other messages from the driver.
7919  */
7920 void
7921 ip_rput_notdata(ill_t *ill, mblk_t *mp)
7922 {
7923 	mblk_t		*first_mp;
7924 	struct iocblk   *iocp;
7925 	struct mac_header_info_s mhi;
7926 
7927 	switch (DB_TYPE(mp)) {
7928 	case M_PROTO:
7929 	case M_PCPROTO: {
7930 		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
7931 		    DL_UNITDATA_IND) {
7932 			/* Go handle anything other than data elsewhere. */
7933 			ip_rput_dlpi(ill, mp);
7934 			return;
7935 		}
7936 
7937 		first_mp = mp;
7938 		mp = first_mp->b_cont;
7939 		first_mp->b_cont = NULL;
7940 
7941 		if (mp == NULL) {
7942 			freeb(first_mp);
7943 			return;
7944 		}
7945 		ip_dlur_to_mhi(ill, first_mp, &mhi);
7946 		if (ill->ill_isv6)
7947 			ip_input_v6(ill, NULL, mp, &mhi);
7948 		else
7949 			ip_input(ill, NULL, mp, &mhi);
7950 
7951 		/* Ditch the DLPI header. */
7952 		freeb(first_mp);
7953 		return;
7954 	}
7955 	case M_IOCACK:
7956 		iocp = (struct iocblk *)mp->b_rptr;
7957 		switch (iocp->ioc_cmd) {
7958 		case DL_IOC_HDR_INFO:
7959 			ill_fastpath_ack(ill, mp);
7960 			return;
7961 		default:
7962 			putnext(ill->ill_rq, mp);
7963 			return;
7964 		}
7965 		/* FALLTHROUGH */
7966 	case M_ERROR:
7967 	case M_HANGUP:
7968 		mutex_enter(&ill->ill_lock);
7969 		if (ill->ill_state_flags & ILL_CONDEMNED) {
7970 			mutex_exit(&ill->ill_lock);
7971 			freemsg(mp);
7972 			return;
7973 		}
7974 		ill_refhold_locked(ill);
7975 		mutex_exit(&ill->ill_lock);
7976 		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
7977 		    B_FALSE);
7978 		return;
7979 	case M_CTL:
7980 		putnext(ill->ill_rq, mp);
7981 		return;
7982 	case M_IOCNAK:
7983 		ip1dbg(("got iocnak "));
7984 		iocp = (struct iocblk *)mp->b_rptr;
7985 		switch (iocp->ioc_cmd) {
7986 		case DL_IOC_HDR_INFO:
7987 			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
7988 			return;
7989 		default:
7990 			break;
7991 		}
7992 		/* FALLTHROUGH */
7993 	default:
7994 		putnext(ill->ill_rq, mp);
7995 		return;
7996 	}
7997 }
7998 
7999 /* Read side put procedure.  Packets coming from the wire arrive here. */
8000 void
8001 ip_rput(queue_t *q, mblk_t *mp)
8002 {
8003 	ill_t	*ill;
8004 	union DL_primitives *dl;
8005 
8006 	ill = (ill_t *)q->q_ptr;
8007 
8008 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
8009 		/*
8010 		 * If things are opening or closing, only accept high-priority
8011 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
8012 		 * created; on close, things hanging off the ill may have been
8013 		 * freed already.)
8014 		 */
8015 		dl = (union DL_primitives *)mp->b_rptr;
8016 		if (DB_TYPE(mp) != M_PCPROTO ||
8017 		    dl->dl_primitive == DL_UNITDATA_IND) {
8018 			inet_freemsg(mp);
8019 			return;
8020 		}
8021 	}
8022 	if (DB_TYPE(mp) == M_DATA) {
8023 		struct mac_header_info_s mhi;
8024 
8025 		ip_mdata_to_mhi(ill, mp, &mhi);
8026 		ip_input(ill, NULL, mp, &mhi);
8027 	} else {
8028 		ip_rput_notdata(ill, mp);
8029 	}
8030 }
8031 
8032 /*
8033  * Move the information to a copy.
8034  */
8035 mblk_t *
8036 ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
8037 {
8038 	mblk_t		*mp1;
8039 	ill_t		*ill = ira->ira_ill;
8040 	ip_stack_t	*ipst = ill->ill_ipst;
8041 
8042 	IP_STAT(ipst, ip_db_ref);
8043 
8044 	/* Make sure we have ira_l2src before we loose the original mblk */
8045 	if (!(ira->ira_flags & IRAF_L2SRC_SET))
8046 		ip_setl2src(mp, ira, ira->ira_rill);
8047 
8048 	mp1 = copymsg(mp);
8049 	if (mp1 == NULL) {
8050 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
8051 		ip_drop_input("ipIfStatsInDiscards", mp, ill);
8052 		freemsg(mp);
8053 		return (NULL);
8054 	}
8055 	/* preserve the hardware checksum flags and data, if present */
8056 	if (DB_CKSUMFLAGS(mp) != 0) {
8057 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
8058 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
8059 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
8060 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
8061 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
8062 	}
8063 	freemsg(mp);
8064 	return (mp1);
8065 }
8066 
8067 static void
8068 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
8069     t_uscalar_t err)
8070 {
8071 	if (dl_err == DL_SYSERR) {
8072 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8073 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
8074 		    ill->ill_name, dl_primstr(prim), err);
8075 		return;
8076 	}
8077 
8078 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
8079 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
8080 	    dl_errstr(dl_err));
8081 }
8082 
8083 /*
8084  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
8085  * than DL_UNITDATA_IND messages. If we need to process this message
8086  * exclusively, we call qwriter_ip, in which case we also need to call
8087  * ill_refhold before that, since qwriter_ip does an ill_refrele.
8088  */
8089 void
8090 ip_rput_dlpi(ill_t *ill, mblk_t *mp)
8091 {
8092 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8093 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8094 	queue_t		*q = ill->ill_rq;
8095 	t_uscalar_t	prim = dloa->dl_primitive;
8096 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
8097 
8098 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
8099 	    char *, dl_primstr(prim), ill_t *, ill);
8100 	ip1dbg(("ip_rput_dlpi"));
8101 
8102 	/*
8103 	 * If we received an ACK but didn't send a request for it, then it
8104 	 * can't be part of any pending operation; discard up-front.
8105 	 */
8106 	switch (prim) {
8107 	case DL_ERROR_ACK:
8108 		reqprim = dlea->dl_error_primitive;
8109 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
8110 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
8111 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
8112 		    dlea->dl_unix_errno));
8113 		break;
8114 	case DL_OK_ACK:
8115 		reqprim = dloa->dl_correct_primitive;
8116 		break;
8117 	case DL_INFO_ACK:
8118 		reqprim = DL_INFO_REQ;
8119 		break;
8120 	case DL_BIND_ACK:
8121 		reqprim = DL_BIND_REQ;
8122 		break;
8123 	case DL_PHYS_ADDR_ACK:
8124 		reqprim = DL_PHYS_ADDR_REQ;
8125 		break;
8126 	case DL_NOTIFY_ACK:
8127 		reqprim = DL_NOTIFY_REQ;
8128 		break;
8129 	case DL_CAPABILITY_ACK:
8130 		reqprim = DL_CAPABILITY_REQ;
8131 		break;
8132 	}
8133 
8134 	if (prim != DL_NOTIFY_IND) {
8135 		if (reqprim == DL_PRIM_INVAL ||
8136 		    !ill_dlpi_pending(ill, reqprim)) {
8137 			/* Not a DLPI message we support or expected */
8138 			freemsg(mp);
8139 			return;
8140 		}
8141 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
8142 		    dl_primstr(reqprim)));
8143 	}
8144 
8145 	switch (reqprim) {
8146 	case DL_UNBIND_REQ:
8147 		/*
8148 		 * NOTE: we mark the unbind as complete even if we got a
8149 		 * DL_ERROR_ACK, since there's not much else we can do.
8150 		 */
8151 		mutex_enter(&ill->ill_lock);
8152 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
8153 		cv_signal(&ill->ill_cv);
8154 		mutex_exit(&ill->ill_lock);
8155 		break;
8156 
8157 	case DL_ENABMULTI_REQ:
8158 		if (prim == DL_OK_ACK) {
8159 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8160 				ill->ill_dlpi_multicast_state = IDS_OK;
8161 		}
8162 		break;
8163 	}
8164 
8165 	/*
8166 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
8167 	 * need to become writer to continue to process it.  Because an
8168 	 * exclusive operation doesn't complete until replies to all queued
8169 	 * DLPI messages have been received, we know we're in the middle of an
8170 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
8171 	 *
8172 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
8173 	 * Since this is on the ill stream we unconditionally bump up the
8174 	 * refcount without doing ILL_CAN_LOOKUP().
8175 	 */
8176 	ill_refhold(ill);
8177 	if (prim == DL_NOTIFY_IND)
8178 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
8179 	else
8180 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
8181 }
8182 
8183 /*
8184  * Handling of DLPI messages that require exclusive access to the ipsq.
8185  *
8186  * Need to do ipsq_pending_mp_get on ioctl completion, which could
8187  * happen here. (along with mi_copy_done)
8188  */
8189 /* ARGSUSED */
8190 static void
8191 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8192 {
8193 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
8194 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
8195 	int		err = 0;
8196 	ill_t		*ill = (ill_t *)q->q_ptr;
8197 	ipif_t		*ipif = NULL;
8198 	mblk_t		*mp1 = NULL;
8199 	conn_t		*connp = NULL;
8200 	t_uscalar_t	paddrreq;
8201 	mblk_t		*mp_hw;
8202 	boolean_t	success;
8203 	boolean_t	ioctl_aborted = B_FALSE;
8204 	boolean_t	log = B_TRUE;
8205 
8206 	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
8207 	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);
8208 
8209 	ip1dbg(("ip_rput_dlpi_writer .."));
8210 	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
8211 	ASSERT(IAM_WRITER_ILL(ill));
8212 
8213 	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
8214 	/*
8215 	 * The current ioctl could have been aborted by the user and a new
8216 	 * ioctl to bring up another ill could have started. We could still
8217 	 * get a response from the driver later.
8218 	 */
8219 	if (ipif != NULL && ipif->ipif_ill != ill)
8220 		ioctl_aborted = B_TRUE;
8221 
8222 	switch (dloa->dl_primitive) {
8223 	case DL_ERROR_ACK:
8224 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
8225 		    dl_primstr(dlea->dl_error_primitive)));
8226 
8227 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
8228 		    char *, dl_primstr(dlea->dl_error_primitive),
8229 		    ill_t *, ill);
8230 
8231 		switch (dlea->dl_error_primitive) {
8232 		case DL_DISABMULTI_REQ:
8233 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8234 			break;
8235 		case DL_PROMISCON_REQ:
8236 		case DL_PROMISCOFF_REQ:
8237 		case DL_UNBIND_REQ:
8238 		case DL_ATTACH_REQ:
8239 		case DL_INFO_REQ:
8240 			ill_dlpi_done(ill, dlea->dl_error_primitive);
8241 			break;
8242 		case DL_NOTIFY_REQ:
8243 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
8244 			log = B_FALSE;
8245 			break;
8246 		case DL_PHYS_ADDR_REQ:
8247 			/*
8248 			 * For IPv6 only, there are two additional
8249 			 * phys_addr_req's sent to the driver to get the
8250 			 * IPv6 token and lla. This allows IP to acquire
8251 			 * the hardware address format for a given interface
8252 			 * without having built in knowledge of the hardware
8253 			 * address. ill_phys_addr_pend keeps track of the last
8254 			 * DL_PAR sent so we know which response we are
8255 			 * dealing with. ill_dlpi_done will update
8256 			 * ill_phys_addr_pend when it sends the next req.
8257 			 * We don't complete the IOCTL until all three DL_PARs
8258 			 * have been attempted, so set *_len to 0 and break.
8259 			 */
8260 			paddrreq = ill->ill_phys_addr_pend;
8261 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8262 			if (paddrreq == DL_IPV6_TOKEN) {
8263 				ill->ill_token_length = 0;
8264 				log = B_FALSE;
8265 				break;
8266 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8267 				ill->ill_nd_lla_len = 0;
8268 				log = B_FALSE;
8269 				break;
8270 			}
8271 			/*
8272 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
8273 			 * We presumably have an IOCTL hanging out waiting
8274 			 * for completion. Find it and complete the IOCTL
8275 			 * with the error noted.
8276 			 * However, ill_dl_phys was called on an ill queue
8277 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
8278 			 * set. But the ioctl is known to be pending on ill_wq.
8279 			 */
8280 			if (!ill->ill_ifname_pending)
8281 				break;
8282 			ill->ill_ifname_pending = 0;
8283 			if (!ioctl_aborted)
8284 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8285 			if (mp1 != NULL) {
8286 				/*
8287 				 * This operation (SIOCSLIFNAME) must have
8288 				 * happened on the ill. Assert there is no conn
8289 				 */
8290 				ASSERT(connp == NULL);
8291 				q = ill->ill_wq;
8292 			}
8293 			break;
8294 		case DL_BIND_REQ:
8295 			ill_dlpi_done(ill, DL_BIND_REQ);
8296 			if (ill->ill_ifname_pending)
8297 				break;
8298 			mutex_enter(&ill->ill_lock);
8299 			ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8300 			mutex_exit(&ill->ill_lock);
8301 			/*
8302 			 * Something went wrong with the bind.  We presumably
8303 			 * have an IOCTL hanging out waiting for completion.
8304 			 * Find it, take down the interface that was coming
8305 			 * up, and complete the IOCTL with the error noted.
8306 			 */
8307 			if (!ioctl_aborted)
8308 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8309 			if (mp1 != NULL) {
8310 				/*
8311 				 * This might be a result of a DL_NOTE_REPLUMB
8312 				 * notification. In that case, connp is NULL.
8313 				 */
8314 				if (connp != NULL)
8315 					q = CONNP_TO_WQ(connp);
8316 
8317 				(void) ipif_down(ipif, NULL, NULL);
8318 				/* error is set below the switch */
8319 			}
8320 			break;
8321 		case DL_ENABMULTI_REQ:
8322 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
8323 
8324 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
8325 				ill->ill_dlpi_multicast_state = IDS_FAILED;
8326 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
8327 
8328 				printf("ip: joining multicasts failed (%d)"
8329 				    " on %s - will use link layer "
8330 				    "broadcasts for multicast\n",
8331 				    dlea->dl_errno, ill->ill_name);
8332 
8333 				/*
8334 				 * Set up for multi_bcast; We are the
8335 				 * writer, so ok to access ill->ill_ipif
8336 				 * without any lock.
8337 				 */
8338 				mutex_enter(&ill->ill_phyint->phyint_lock);
8339 				ill->ill_phyint->phyint_flags |=
8340 				    PHYI_MULTI_BCAST;
8341 				mutex_exit(&ill->ill_phyint->phyint_lock);
8342 
8343 			}
8344 			freemsg(mp);	/* Don't want to pass this up */
8345 			return;
8346 		case DL_CAPABILITY_REQ:
8347 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
8348 			    "DL_CAPABILITY REQ\n"));
8349 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
8350 				ill->ill_dlpi_capab_state = IDCS_FAILED;
8351 			ill_capability_done(ill);
8352 			freemsg(mp);
8353 			return;
8354 		}
8355 		/*
8356 		 * Note the error for IOCTL completion (mp1 is set when
8357 		 * ready to complete ioctl). If ill_ifname_pending_err is
8358 		 * set, an error occured during plumbing (ill_ifname_pending),
8359 		 * so we want to report that error.
8360 		 *
8361 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
8362 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
8363 		 * expected to get errack'd if the driver doesn't support
8364 		 * these flags (e.g. ethernet). log will be set to B_FALSE
8365 		 * if these error conditions are encountered.
8366 		 */
8367 		if (mp1 != NULL) {
8368 			if (ill->ill_ifname_pending_err != 0)  {
8369 				err = ill->ill_ifname_pending_err;
8370 				ill->ill_ifname_pending_err = 0;
8371 			} else {
8372 				err = dlea->dl_unix_errno ?
8373 				    dlea->dl_unix_errno : ENXIO;
8374 			}
8375 		/*
8376 		 * If we're plumbing an interface and an error hasn't already
8377 		 * been saved, set ill_ifname_pending_err to the error passed
8378 		 * up. Ignore the error if log is B_FALSE (see comment above).
8379 		 */
8380 		} else if (log && ill->ill_ifname_pending &&
8381 		    ill->ill_ifname_pending_err == 0) {
8382 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
8383 			    dlea->dl_unix_errno : ENXIO;
8384 		}
8385 
8386 		if (log)
8387 			ip_dlpi_error(ill, dlea->dl_error_primitive,
8388 			    dlea->dl_errno, dlea->dl_unix_errno);
8389 		break;
8390 	case DL_CAPABILITY_ACK:
8391 		ill_capability_ack(ill, mp);
8392 		/*
8393 		 * The message has been handed off to ill_capability_ack
8394 		 * and must not be freed below
8395 		 */
8396 		mp = NULL;
8397 		break;
8398 
8399 	case DL_INFO_ACK:
8400 		/* Call a routine to handle this one. */
8401 		ill_dlpi_done(ill, DL_INFO_REQ);
8402 		ip_ll_subnet_defaults(ill, mp);
8403 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
8404 		return;
8405 	case DL_BIND_ACK:
8406 		/*
8407 		 * We should have an IOCTL waiting on this unless
8408 		 * sent by ill_dl_phys, in which case just return
8409 		 */
8410 		ill_dlpi_done(ill, DL_BIND_REQ);
8411 
8412 		if (ill->ill_ifname_pending) {
8413 			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
8414 			    ill_t *, ill, mblk_t *, mp);
8415 			break;
8416 		}
8417 		mutex_enter(&ill->ill_lock);
8418 		ill->ill_dl_up = 1;
8419 		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
8420 		mutex_exit(&ill->ill_lock);
8421 
8422 		if (!ioctl_aborted)
8423 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8424 		if (mp1 == NULL) {
8425 			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
8426 			break;
8427 		}
8428 		/*
8429 		 * mp1 was added by ill_dl_up(). if that is a result of
8430 		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
8431 		 */
8432 		if (connp != NULL)
8433 			q = CONNP_TO_WQ(connp);
8434 		/*
8435 		 * We are exclusive. So nothing can change even after
8436 		 * we get the pending mp.
8437 		 */
8438 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
8439 		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
8440 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
8441 
8442 		/*
8443 		 * Now bring up the resolver; when that is complete, we'll
8444 		 * create IREs.  Note that we intentionally mirror what
8445 		 * ipif_up() would have done, because we got here by way of
8446 		 * ill_dl_up(), which stopped ipif_up()'s processing.
8447 		 */
8448 		if (ill->ill_isv6) {
8449 			/*
8450 			 * v6 interfaces.
8451 			 * Unlike ARP which has to do another bind
8452 			 * and attach, once we get here we are
8453 			 * done with NDP
8454 			 */
8455 			(void) ipif_resolver_up(ipif, Res_act_initial);
8456 			if ((err = ipif_ndp_up(ipif, B_TRUE)) == 0)
8457 				err = ipif_up_done_v6(ipif);
8458 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
8459 			/*
8460 			 * ARP and other v4 external resolvers.
8461 			 * Leave the pending mblk intact so that
8462 			 * the ioctl completes in ip_rput().
8463 			 */
8464 			if (connp != NULL)
8465 				mutex_enter(&connp->conn_lock);
8466 			mutex_enter(&ill->ill_lock);
8467 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
8468 			mutex_exit(&ill->ill_lock);
8469 			if (connp != NULL)
8470 				mutex_exit(&connp->conn_lock);
8471 			if (success) {
8472 				err = ipif_resolver_up(ipif, Res_act_initial);
8473 				if (err == EINPROGRESS) {
8474 					freemsg(mp);
8475 					return;
8476 				}
8477 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
8478 			} else {
8479 				/* The conn has started closing */
8480 				err = EINTR;
8481 			}
8482 		} else {
8483 			/*
8484 			 * This one is complete. Reply to pending ioctl.
8485 			 */
8486 			(void) ipif_resolver_up(ipif, Res_act_initial);
8487 			err = ipif_up_done(ipif);
8488 		}
8489 
8490 		if ((err == 0) && (ill->ill_up_ipifs)) {
8491 			err = ill_up_ipifs(ill, q, mp1);
8492 			if (err == EINPROGRESS) {
8493 				freemsg(mp);
8494 				return;
8495 			}
8496 		}
8497 
8498 		/*
8499 		 * If we have a moved ipif to bring up, and everything has
8500 		 * succeeded to this point, bring it up on the IPMP ill.
8501 		 * Otherwise, leave it down -- the admin can try to bring it
8502 		 * up by hand if need be.
8503 		 */
8504 		if (ill->ill_move_ipif != NULL) {
8505 			if (err != 0) {
8506 				ill->ill_move_ipif = NULL;
8507 			} else {
8508 				ipif = ill->ill_move_ipif;
8509 				ill->ill_move_ipif = NULL;
8510 				err = ipif_up(ipif, q, mp1);
8511 				if (err == EINPROGRESS) {
8512 					freemsg(mp);
8513 					return;
8514 				}
8515 			}
8516 		}
8517 		break;
8518 
8519 	case DL_NOTIFY_IND: {
8520 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
8521 		uint_t orig_mtu, orig_mc_mtu;
8522 
8523 		switch (notify->dl_notification) {
8524 		case DL_NOTE_PHYS_ADDR:
8525 			err = ill_set_phys_addr(ill, mp);
8526 			break;
8527 
8528 		case DL_NOTE_REPLUMB:
8529 			/*
8530 			 * Directly return after calling ill_replumb().
8531 			 * Note that we should not free mp as it is reused
8532 			 * in the ill_replumb() function.
8533 			 */
8534 			err = ill_replumb(ill, mp);
8535 			return;
8536 
8537 		case DL_NOTE_FASTPATH_FLUSH:
8538 			nce_flush(ill, B_FALSE);
8539 			break;
8540 
8541 		case DL_NOTE_SDU_SIZE:
8542 		case DL_NOTE_SDU_SIZE2:
8543 			/*
8544 			 * The dce and fragmentation code can cope with
8545 			 * this changing while packets are being sent.
8546 			 * When packets are sent ip_output will discover
8547 			 * a change.
8548 			 *
8549 			 * Change the MTU size of the interface.
8550 			 */
8551 			mutex_enter(&ill->ill_lock);
8552 			orig_mtu = ill->ill_mtu;
8553 			orig_mc_mtu = ill->ill_mc_mtu;
8554 			switch (notify->dl_notification) {
8555 			case DL_NOTE_SDU_SIZE:
8556 				ill->ill_current_frag =
8557 				    (uint_t)notify->dl_data;
8558 				ill->ill_mc_mtu = (uint_t)notify->dl_data;
8559 				break;
8560 			case DL_NOTE_SDU_SIZE2:
8561 				ill->ill_current_frag =
8562 				    (uint_t)notify->dl_data1;
8563 				ill->ill_mc_mtu = (uint_t)notify->dl_data2;
8564 				break;
8565 			}
8566 			if (ill->ill_current_frag > ill->ill_max_frag)
8567 				ill->ill_max_frag = ill->ill_current_frag;
8568 
8569 			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
8570 				ill->ill_mtu = ill->ill_current_frag;
8571 
8572 				/*
8573 				 * If ill_user_mtu was set (via
8574 				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
8575 				 */
8576 				if (ill->ill_user_mtu != 0 &&
8577 				    ill->ill_user_mtu < ill->ill_mtu)
8578 					ill->ill_mtu = ill->ill_user_mtu;
8579 
8580 				if (ill->ill_user_mtu != 0 &&
8581 				    ill->ill_user_mtu < ill->ill_mc_mtu)
8582 					ill->ill_mc_mtu = ill->ill_user_mtu;
8583 
8584 				if (ill->ill_isv6) {
8585 					if (ill->ill_mtu < IPV6_MIN_MTU)
8586 						ill->ill_mtu = IPV6_MIN_MTU;
8587 					if (ill->ill_mc_mtu < IPV6_MIN_MTU)
8588 						ill->ill_mc_mtu = IPV6_MIN_MTU;
8589 				} else {
8590 					if (ill->ill_mtu < IP_MIN_MTU)
8591 						ill->ill_mtu = IP_MIN_MTU;
8592 					if (ill->ill_mc_mtu < IP_MIN_MTU)
8593 						ill->ill_mc_mtu = IP_MIN_MTU;
8594 				}
8595 			} else if (ill->ill_mc_mtu > ill->ill_mtu) {
8596 				ill->ill_mc_mtu = ill->ill_mtu;
8597 			}
8598 
8599 			mutex_exit(&ill->ill_lock);
8600 			/*
8601 			 * Make sure all dce_generation checks find out
8602 			 * that ill_mtu/ill_mc_mtu has changed.
8603 			 */
8604 			if (orig_mtu != ill->ill_mtu ||
8605 			    orig_mc_mtu != ill->ill_mc_mtu) {
8606 				dce_increment_all_generations(ill->ill_isv6,
8607 				    ill->ill_ipst);
8608 			}
8609 
8610 			/*
8611 			 * Refresh IPMP meta-interface MTU if necessary.
8612 			 */
8613 			if (IS_UNDER_IPMP(ill))
8614 				ipmp_illgrp_refresh_mtu(ill->ill_grp);
8615 			break;
8616 
8617 		case DL_NOTE_LINK_UP:
8618 		case DL_NOTE_LINK_DOWN: {
8619 			/*
8620 			 * We are writer. ill / phyint / ipsq assocs stable.
8621 			 * The RUNNING flag reflects the state of the link.
8622 			 */
8623 			phyint_t *phyint = ill->ill_phyint;
8624 			uint64_t new_phyint_flags;
8625 			boolean_t changed = B_FALSE;
8626 			boolean_t went_up;
8627 
8628 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
8629 			mutex_enter(&phyint->phyint_lock);
8630 
8631 			new_phyint_flags = went_up ?
8632 			    phyint->phyint_flags | PHYI_RUNNING :
8633 			    phyint->phyint_flags & ~PHYI_RUNNING;
8634 
8635 			if (IS_IPMP(ill)) {
8636 				new_phyint_flags = went_up ?
8637 				    new_phyint_flags & ~PHYI_FAILED :
8638 				    new_phyint_flags | PHYI_FAILED;
8639 			}
8640 
8641 			if (new_phyint_flags != phyint->phyint_flags) {
8642 				phyint->phyint_flags = new_phyint_flags;
8643 				changed = B_TRUE;
8644 			}
8645 			mutex_exit(&phyint->phyint_lock);
8646 			/*
8647 			 * ill_restart_dad handles the DAD restart and routing
8648 			 * socket notification logic.
8649 			 */
8650 			if (changed) {
8651 				ill_restart_dad(phyint->phyint_illv4, went_up);
8652 				ill_restart_dad(phyint->phyint_illv6, went_up);
8653 			}
8654 			break;
8655 		}
8656 		case DL_NOTE_PROMISC_ON_PHYS: {
8657 			phyint_t *phyint = ill->ill_phyint;
8658 
8659 			mutex_enter(&phyint->phyint_lock);
8660 			phyint->phyint_flags |= PHYI_PROMISC;
8661 			mutex_exit(&phyint->phyint_lock);
8662 			break;
8663 		}
8664 		case DL_NOTE_PROMISC_OFF_PHYS: {
8665 			phyint_t *phyint = ill->ill_phyint;
8666 
8667 			mutex_enter(&phyint->phyint_lock);
8668 			phyint->phyint_flags &= ~PHYI_PROMISC;
8669 			mutex_exit(&phyint->phyint_lock);
8670 			break;
8671 		}
8672 		case DL_NOTE_CAPAB_RENEG:
8673 			/*
8674 			 * Something changed on the driver side.
8675 			 * It wants us to renegotiate the capabilities
8676 			 * on this ill. One possible cause is the aggregation
8677 			 * interface under us where a port got added or
8678 			 * went away.
8679 			 *
8680 			 * If the capability negotiation is already done
8681 			 * or is in progress, reset the capabilities and
8682 			 * mark the ill's ill_capab_reneg to be B_TRUE,
8683 			 * so that when the ack comes back, we can start
8684 			 * the renegotiation process.
8685 			 *
8686 			 * Note that if ill_capab_reneg is already B_TRUE
8687 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
8688 			 * the capability resetting request has been sent
8689 			 * and the renegotiation has not been started yet;
8690 			 * nothing needs to be done in this case.
8691 			 */
8692 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
8693 			ill_capability_reset(ill, B_TRUE);
8694 			ipsq_current_finish(ipsq);
8695 			break;
8696 
8697 		case DL_NOTE_ALLOWED_IPS:
8698 			ill_set_allowed_ips(ill, mp);
8699 			break;
8700 		default:
8701 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
8702 			    "type 0x%x for DL_NOTIFY_IND\n",
8703 			    notify->dl_notification));
8704 			break;
8705 		}
8706 
8707 		/*
8708 		 * As this is an asynchronous operation, we
8709 		 * should not call ill_dlpi_done
8710 		 */
8711 		break;
8712 	}
8713 	case DL_NOTIFY_ACK: {
8714 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
8715 
8716 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
8717 			ill->ill_note_link = 1;
8718 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
8719 		break;
8720 	}
8721 	case DL_PHYS_ADDR_ACK: {
8722 		/*
8723 		 * As part of plumbing the interface via SIOCSLIFNAME,
8724 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
8725 		 * whose answers we receive here.  As each answer is received,
8726 		 * we call ill_dlpi_done() to dispatch the next request as
8727 		 * we're processing the current one.  Once all answers have
8728 		 * been received, we use ipsq_pending_mp_get() to dequeue the
8729 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
8730 		 * is invoked from an ill queue, conn_oper_pending_ill is not
8731 		 * available, but we know the ioctl is pending on ill_wq.)
8732 		 */
8733 		uint_t	paddrlen, paddroff;
8734 		uint8_t	*addr;
8735 
8736 		paddrreq = ill->ill_phys_addr_pend;
8737 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
8738 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
8739 		addr = mp->b_rptr + paddroff;
8740 
8741 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
8742 		if (paddrreq == DL_IPV6_TOKEN) {
8743 			/*
8744 			 * bcopy to low-order bits of ill_token
8745 			 *
8746 			 * XXX Temporary hack - currently, all known tokens
8747 			 * are 64 bits, so I'll cheat for the moment.
8748 			 */
8749 			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
8750 			ill->ill_token_length = paddrlen;
8751 			break;
8752 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
8753 			ASSERT(ill->ill_nd_lla_mp == NULL);
8754 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
8755 			mp = NULL;
8756 			break;
8757 		} else if (paddrreq == DL_CURR_DEST_ADDR) {
8758 			ASSERT(ill->ill_dest_addr_mp == NULL);
8759 			ill->ill_dest_addr_mp = mp;
8760 			ill->ill_dest_addr = addr;
8761 			mp = NULL;
8762 			if (ill->ill_isv6) {
8763 				ill_setdesttoken(ill);
8764 				ipif_setdestlinklocal(ill->ill_ipif);
8765 			}
8766 			break;
8767 		}
8768 
8769 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
8770 		ASSERT(ill->ill_phys_addr_mp == NULL);
8771 		if (!ill->ill_ifname_pending)
8772 			break;
8773 		ill->ill_ifname_pending = 0;
8774 		if (!ioctl_aborted)
8775 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
8776 		if (mp1 != NULL) {
8777 			ASSERT(connp == NULL);
8778 			q = ill->ill_wq;
8779 		}
8780 		/*
8781 		 * If any error acks received during the plumbing sequence,
8782 		 * ill_ifname_pending_err will be set. Break out and send up
8783 		 * the error to the pending ioctl.
8784 		 */
8785 		if (ill->ill_ifname_pending_err != 0) {
8786 			err = ill->ill_ifname_pending_err;
8787 			ill->ill_ifname_pending_err = 0;
8788 			break;
8789 		}
8790 
8791 		ill->ill_phys_addr_mp = mp;
8792 		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
8793 		mp = NULL;
8794 
8795 		/*
8796 		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
8797 		 * provider doesn't support physical addresses.  We check both
8798 		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
8799 		 * not have physical addresses, but historically adversises a
8800 		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
8801 		 * its DL_PHYS_ADDR_ACK.
8802 		 */
8803 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
8804 			ill->ill_phys_addr = NULL;
8805 		} else if (paddrlen != ill->ill_phys_addr_length) {
8806 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
8807 			    paddrlen, ill->ill_phys_addr_length));
8808 			err = EINVAL;
8809 			break;
8810 		}
8811 
8812 		if (ill->ill_nd_lla_mp == NULL) {
8813 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
8814 				err = ENOMEM;
8815 				break;
8816 			}
8817 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
8818 		}
8819 
8820 		if (ill->ill_isv6) {
8821 			ill_setdefaulttoken(ill);
8822 			ipif_setlinklocal(ill->ill_ipif);
8823 		}
8824 		break;
8825 	}
8826 	case DL_OK_ACK:
8827 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
8828 		    dl_primstr((int)dloa->dl_correct_primitive),
8829 		    dloa->dl_correct_primitive));
8830 		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
8831 		    char *, dl_primstr(dloa->dl_correct_primitive),
8832 		    ill_t *, ill);
8833 
8834 		switch (dloa->dl_correct_primitive) {
8835 		case DL_ENABMULTI_REQ:
8836 		case DL_DISABMULTI_REQ:
8837 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8838 			break;
8839 		case DL_PROMISCON_REQ:
8840 		case DL_PROMISCOFF_REQ:
8841 		case DL_UNBIND_REQ:
8842 		case DL_ATTACH_REQ:
8843 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
8844 			break;
8845 		}
8846 		break;
8847 	default:
8848 		break;
8849 	}
8850 
8851 	freemsg(mp);
8852 	if (mp1 == NULL)
8853 		return;
8854 
8855 	/*
8856 	 * The operation must complete without EINPROGRESS since
8857 	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
8858 	 * the operation will be stuck forever inside the IPSQ.
8859 	 */
8860 	ASSERT(err != EINPROGRESS);
8861 
8862 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
8863 	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
8864 	    ipif_t *, NULL);
8865 
8866 	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
8867 	case 0:
8868 		ipsq_current_finish(ipsq);
8869 		break;
8870 
8871 	case SIOCSLIFNAME:
8872 	case IF_UNITSEL: {
8873 		ill_t *ill_other = ILL_OTHER(ill);
8874 
8875 		/*
8876 		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
8877 		 * ill has a peer which is in an IPMP group, then place ill
8878 		 * into the same group.  One catch: although ifconfig plumbs
8879 		 * the appropriate IPMP meta-interface prior to plumbing this
8880 		 * ill, it is possible for multiple ifconfig applications to
8881 		 * race (or for another application to adjust plumbing), in
8882 		 * which case the IPMP meta-interface we need will be missing.
8883 		 * If so, kick the phyint out of the group.
8884 		 */
8885 		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
8886 			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
8887 			ipmp_illgrp_t	*illg;
8888 
8889 			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
8890 			if (illg == NULL)
8891 				ipmp_phyint_leave_grp(ill->ill_phyint);
8892 			else
8893 				ipmp_ill_join_illgrp(ill, illg);
8894 		}
8895 
8896 		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
8897 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8898 		else
8899 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8900 		break;
8901 	}
8902 	case SIOCLIFADDIF:
8903 		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
8904 		break;
8905 
8906 	default:
8907 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
8908 		break;
8909 	}
8910 }
8911 
8912 /*
8913  * ip_rput_other is called by ip_rput to handle messages modifying the global
8914  * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
8915  */
8916 /* ARGSUSED */
8917 void
8918 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
8919 {
8920 	ill_t		*ill = q->q_ptr;
8921 	struct iocblk	*iocp;
8922 
8923 	ip1dbg(("ip_rput_other "));
8924 	if (ipsq != NULL) {
8925 		ASSERT(IAM_WRITER_IPSQ(ipsq));
8926 		ASSERT(ipsq->ipsq_xop ==
8927 		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
8928 	}
8929 
8930 	switch (mp->b_datap->db_type) {
8931 	case M_ERROR:
8932 	case M_HANGUP:
8933 		/*
8934 		 * The device has a problem.  We force the ILL down.  It can
8935 		 * be brought up again manually using SIOCSIFFLAGS (via
8936 		 * ifconfig or equivalent).
8937 		 */
8938 		ASSERT(ipsq != NULL);
8939 		if (mp->b_rptr < mp->b_wptr)
8940 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
8941 		if (ill->ill_error == 0)
8942 			ill->ill_error = ENXIO;
8943 		if (!ill_down_start(q, mp))
8944 			return;
8945 		ipif_all_down_tail(ipsq, q, mp, NULL);
8946 		break;
8947 	case M_IOCNAK: {
8948 		iocp = (struct iocblk *)mp->b_rptr;
8949 
8950 		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
8951 		/*
8952 		 * If this was the first attempt, turn off the fastpath
8953 		 * probing.
8954 		 */
8955 		mutex_enter(&ill->ill_lock);
8956 		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
8957 			ill->ill_dlpi_fastpath_state = IDS_FAILED;
8958 			mutex_exit(&ill->ill_lock);
8959 			/*
8960 			 * don't flush the nce_t entries: we use them
8961 			 * as an index to the ncec itself.
8962 			 */
8963 			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
8964 			    ill->ill_name));
8965 		} else {
8966 			mutex_exit(&ill->ill_lock);
8967 		}
8968 		freemsg(mp);
8969 		break;
8970 	}
8971 	default:
8972 		ASSERT(0);
8973 		break;
8974 	}
8975 }
8976 
8977 /*
8978  * Update any source route, record route or timestamp options
8979  * When it fails it has consumed the message and BUMPed the MIB.
8980  */
8981 boolean_t
8982 ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
8983     ip_recv_attr_t *ira)
8984 {
8985 	ipoptp_t	opts;
8986 	uchar_t		*opt;
8987 	uint8_t		optval;
8988 	uint8_t		optlen;
8989 	ipaddr_t	dst;
8990 	ipaddr_t	ifaddr;
8991 	uint32_t	ts;
8992 	timestruc_t	now;
8993 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
8994 
8995 	ip2dbg(("ip_forward_options\n"));
8996 	dst = ipha->ipha_dst;
8997 	for (optval = ipoptp_first(&opts, ipha);
8998 	    optval != IPOPT_EOL;
8999 	    optval = ipoptp_next(&opts)) {
9000 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9001 		opt = opts.ipoptp_cur;
9002 		optlen = opts.ipoptp_len;
9003 		ip2dbg(("ip_forward_options: opt %d, len %d\n",
9004 		    optval, opts.ipoptp_len));
9005 		switch (optval) {
9006 			uint32_t off;
9007 		case IPOPT_SSRR:
9008 		case IPOPT_LSRR:
9009 			/* Check if adminstratively disabled */
9010 			if (!ipst->ips_ip_forward_src_routed) {
9011 				BUMP_MIB(dst_ill->ill_ip_mib,
9012 				    ipIfStatsForwProhibits);
9013 				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
9014 				    mp, dst_ill);
9015 				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
9016 				    ira);
9017 				return (B_FALSE);
9018 			}
9019 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9020 				/*
9021 				 * Must be partial since ip_input_options
9022 				 * checked for strict.
9023 				 */
9024 				break;
9025 			}
9026 			off = opt[IPOPT_OFFSET];
9027 			off--;
9028 		redo_srr:
9029 			if (optlen < IP_ADDR_LEN ||
9030 			    off > optlen - IP_ADDR_LEN) {
9031 				/* End of source route */
9032 				ip1dbg((
9033 				    "ip_forward_options: end of SR\n"));
9034 				break;
9035 			}
9036 			/* Pick a reasonable address on the outbound if */
9037 			ASSERT(dst_ill != NULL);
9038 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9039 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9040 			    NULL) != 0) {
9041 				/* No source! Shouldn't happen */
9042 				ifaddr = INADDR_ANY;
9043 			}
9044 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9045 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9046 			ip1dbg(("ip_forward_options: next hop 0x%x\n",
9047 			    ntohl(dst)));
9048 
9049 			/*
9050 			 * Check if our address is present more than
9051 			 * once as consecutive hops in source route.
9052 			 */
9053 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9054 				off += IP_ADDR_LEN;
9055 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9056 				goto redo_srr;
9057 			}
9058 			ipha->ipha_dst = dst;
9059 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9060 			break;
9061 		case IPOPT_RR:
9062 			off = opt[IPOPT_OFFSET];
9063 			off--;
9064 			if (optlen < IP_ADDR_LEN ||
9065 			    off > optlen - IP_ADDR_LEN) {
9066 				/* No more room - ignore */
9067 				ip1dbg((
9068 				    "ip_forward_options: end of RR\n"));
9069 				break;
9070 			}
9071 			/* Pick a reasonable address on the outbound if */
9072 			ASSERT(dst_ill != NULL);
9073 			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
9074 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9075 			    NULL) != 0) {
9076 				/* No source! Shouldn't happen */
9077 				ifaddr = INADDR_ANY;
9078 			}
9079 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9080 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9081 			break;
9082 		case IPOPT_TS:
9083 			/* Insert timestamp if there is room */
9084 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9085 			case IPOPT_TS_TSONLY:
9086 				off = IPOPT_TS_TIMELEN;
9087 				break;
9088 			case IPOPT_TS_PRESPEC:
9089 			case IPOPT_TS_PRESPEC_RFC791:
9090 				/* Verify that the address matched */
9091 				off = opt[IPOPT_OFFSET] - 1;
9092 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9093 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9094 					/* Not for us */
9095 					break;
9096 				}
9097 				/* FALLTHROUGH */
9098 			case IPOPT_TS_TSANDADDR:
9099 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9100 				break;
9101 			default:
9102 				/*
9103 				 * ip_*put_options should have already
9104 				 * dropped this packet.
9105 				 */
9106 				cmn_err(CE_PANIC, "ip_forward_options: "
9107 				    "unknown IT - bug in ip_input_options?\n");
9108 				return (B_TRUE);	/* Keep "lint" happy */
9109 			}
9110 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9111 				/* Increase overflow counter */
9112 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9113 				opt[IPOPT_POS_OV_FLG] =
9114 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9115 				    (off << 4));
9116 				break;
9117 			}
9118 			off = opt[IPOPT_OFFSET] - 1;
9119 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9120 			case IPOPT_TS_PRESPEC:
9121 			case IPOPT_TS_PRESPEC_RFC791:
9122 			case IPOPT_TS_TSANDADDR:
9123 				/* Pick a reasonable addr on the outbound if */
9124 				ASSERT(dst_ill != NULL);
9125 				if (ip_select_source_v4(dst_ill, INADDR_ANY,
9126 				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
9127 				    NULL, NULL) != 0) {
9128 					/* No source! Shouldn't happen */
9129 					ifaddr = INADDR_ANY;
9130 				}
9131 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9132 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9133 				/* FALLTHROUGH */
9134 			case IPOPT_TS_TSONLY:
9135 				off = opt[IPOPT_OFFSET] - 1;
9136 				/* Compute # of milliseconds since midnight */
9137 				gethrestime(&now);
9138 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9139 				    NSEC2MSEC(now.tv_nsec);
9140 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9141 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9142 				break;
9143 			}
9144 			break;
9145 		}
9146 	}
9147 	return (B_TRUE);
9148 }
9149 
9150 /*
9151  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
9152  * returns 'true' if there are still fragments left on the queue, in
9153  * which case we restart the timer.
9154  */
9155 void
9156 ill_frag_timer(void *arg)
9157 {
9158 	ill_t	*ill = (ill_t *)arg;
9159 	boolean_t frag_pending;
9160 	ip_stack_t *ipst = ill->ill_ipst;
9161 	time_t	timeout;
9162 
9163 	mutex_enter(&ill->ill_lock);
9164 	ASSERT(!ill->ill_fragtimer_executing);
9165 	if (ill->ill_state_flags & ILL_CONDEMNED) {
9166 		ill->ill_frag_timer_id = 0;
9167 		mutex_exit(&ill->ill_lock);
9168 		return;
9169 	}
9170 	ill->ill_fragtimer_executing = 1;
9171 	mutex_exit(&ill->ill_lock);
9172 
9173 	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9174 	    ipst->ips_ip_reassembly_timeout);
9175 
9176 	frag_pending = ill_frag_timeout(ill, timeout);
9177 
9178 	/*
9179 	 * Restart the timer, if we have fragments pending or if someone
9180 	 * wanted us to be scheduled again.
9181 	 */
9182 	mutex_enter(&ill->ill_lock);
9183 	ill->ill_fragtimer_executing = 0;
9184 	ill->ill_frag_timer_id = 0;
9185 	if (frag_pending || ill->ill_fragtimer_needrestart)
9186 		ill_frag_timer_start(ill);
9187 	mutex_exit(&ill->ill_lock);
9188 }
9189 
9190 void
9191 ill_frag_timer_start(ill_t *ill)
9192 {
9193 	ip_stack_t *ipst = ill->ill_ipst;
9194 	clock_t	timeo_ms;
9195 
9196 	ASSERT(MUTEX_HELD(&ill->ill_lock));
9197 
9198 	/* If the ill is closing or opening don't proceed */
9199 	if (ill->ill_state_flags & ILL_CONDEMNED)
9200 		return;
9201 
9202 	if (ill->ill_fragtimer_executing) {
9203 		/*
9204 		 * ill_frag_timer is currently executing. Just record the
9205 		 * the fact that we want the timer to be restarted.
9206 		 * ill_frag_timer will post a timeout before it returns,
9207 		 * ensuring it will be called again.
9208 		 */
9209 		ill->ill_fragtimer_needrestart = 1;
9210 		return;
9211 	}
9212 
9213 	if (ill->ill_frag_timer_id == 0) {
9214 		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
9215 		    ipst->ips_ip_reassembly_timeout) * SECONDS;
9216 
9217 		/*
9218 		 * The timer is neither running nor is the timeout handler
9219 		 * executing. Post a timeout so that ill_frag_timer will be
9220 		 * called
9221 		 */
9222 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
9223 		    MSEC_TO_TICK(timeo_ms >> 1));
9224 		ill->ill_fragtimer_needrestart = 0;
9225 	}
9226 }
9227 
9228 /*
9229  * Update any source route, record route or timestamp options.
9230  * Check that we are at end of strict source route.
9231  * The options have already been checked for sanity in ip_input_options().
9232  */
9233 boolean_t
9234 ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
9235 {
9236 	ipoptp_t	opts;
9237 	uchar_t		*opt;
9238 	uint8_t		optval;
9239 	uint8_t		optlen;
9240 	ipaddr_t	dst;
9241 	ipaddr_t	ifaddr;
9242 	uint32_t	ts;
9243 	timestruc_t	now;
9244 	ill_t		*ill = ira->ira_ill;
9245 	ip_stack_t	*ipst = ill->ill_ipst;
9246 
9247 	ip2dbg(("ip_input_local_options\n"));
9248 
9249 	for (optval = ipoptp_first(&opts, ipha);
9250 	    optval != IPOPT_EOL;
9251 	    optval = ipoptp_next(&opts)) {
9252 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
9253 		opt = opts.ipoptp_cur;
9254 		optlen = opts.ipoptp_len;
9255 		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
9256 		    optval, optlen));
9257 		switch (optval) {
9258 			uint32_t off;
9259 		case IPOPT_SSRR:
9260 		case IPOPT_LSRR:
9261 			off = opt[IPOPT_OFFSET];
9262 			off--;
9263 			if (optlen < IP_ADDR_LEN ||
9264 			    off > optlen - IP_ADDR_LEN) {
9265 				/* End of source route */
9266 				ip1dbg(("ip_input_local_options: end of SR\n"));
9267 				break;
9268 			}
9269 			/*
9270 			 * This will only happen if two consecutive entries
9271 			 * in the source route contains our address or if
9272 			 * it is a packet with a loose source route which
9273 			 * reaches us before consuming the whole source route
9274 			 */
9275 			ip1dbg(("ip_input_local_options: not end of SR\n"));
9276 			if (optval == IPOPT_SSRR) {
9277 				goto bad_src_route;
9278 			}
9279 			/*
9280 			 * Hack: instead of dropping the packet truncate the
9281 			 * source route to what has been used by filling the
9282 			 * rest with IPOPT_NOP.
9283 			 */
9284 			opt[IPOPT_OLEN] = (uint8_t)off;
9285 			while (off < optlen) {
9286 				opt[off++] = IPOPT_NOP;
9287 			}
9288 			break;
9289 		case IPOPT_RR:
9290 			off = opt[IPOPT_OFFSET];
9291 			off--;
9292 			if (optlen < IP_ADDR_LEN ||
9293 			    off > optlen - IP_ADDR_LEN) {
9294 				/* No more room - ignore */
9295 				ip1dbg((
9296 				    "ip_input_local_options: end of RR\n"));
9297 				break;
9298 			}
9299 			/* Pick a reasonable address on the outbound if */
9300 			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
9301 			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
9302 			    NULL) != 0) {
9303 				/* No source! Shouldn't happen */
9304 				ifaddr = INADDR_ANY;
9305 			}
9306 			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9307 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9308 			break;
9309 		case IPOPT_TS:
9310 			/* Insert timestamp if there is romm */
9311 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9312 			case IPOPT_TS_TSONLY:
9313 				off = IPOPT_TS_TIMELEN;
9314 				break;
9315 			case IPOPT_TS_PRESPEC:
9316 			case IPOPT_TS_PRESPEC_RFC791:
9317 				/* Verify that the address matched */
9318 				off = opt[IPOPT_OFFSET] - 1;
9319 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9320 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9321 					/* Not for us */
9322 					break;
9323 				}
9324 				/* FALLTHROUGH */
9325 			case IPOPT_TS_TSANDADDR:
9326 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9327 				break;
9328 			default:
9329 				/*
9330 				 * ip_*put_options should have already
9331 				 * dropped this packet.
9332 				 */
9333 				cmn_err(CE_PANIC, "ip_input_local_options: "
9334 				    "unknown IT - bug in ip_input_options?\n");
9335 				return (B_TRUE);	/* Keep "lint" happy */
9336 			}
9337 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
9338 				/* Increase overflow counter */
9339 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
9340 				opt[IPOPT_POS_OV_FLG] =
9341 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
9342 				    (off << 4));
9343 				break;
9344 			}
9345 			off = opt[IPOPT_OFFSET] - 1;
9346 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9347 			case IPOPT_TS_PRESPEC:
9348 			case IPOPT_TS_PRESPEC_RFC791:
9349 			case IPOPT_TS_TSANDADDR:
9350 				/* Pick a reasonable addr on the outbound if */
9351 				if (ip_select_source_v4(ill, INADDR_ANY,
9352 				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
9353 				    &ifaddr, NULL, NULL) != 0) {
9354 					/* No source! Shouldn't happen */
9355 					ifaddr = INADDR_ANY;
9356 				}
9357 				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
9358 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
9359 				/* FALLTHROUGH */
9360 			case IPOPT_TS_TSONLY:
9361 				off = opt[IPOPT_OFFSET] - 1;
9362 				/* Compute # of milliseconds since midnight */
9363 				gethrestime(&now);
9364 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
9365 				    NSEC2MSEC(now.tv_nsec);
9366 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
9367 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
9368 				break;
9369 			}
9370 			break;
9371 		}
9372 	}
9373 	return (B_TRUE);
9374 
9375 bad_src_route:
9376 	/* make sure we clear any indication of a hardware checksum */
9377 	DB_CKSUMFLAGS(mp) = 0;
9378 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
9379 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9380 	return (B_FALSE);
9381 
9382 }
9383 
9384 /*
9385  * Process IP options in an inbound packet.  Always returns the nexthop.
9386  * Normally this is the passed in nexthop, but if there is an option
9387  * that effects the nexthop (such as a source route) that will be returned.
9388  * Sets *errorp if there is an error, in which case an ICMP error has been sent
9389  * and mp freed.
9390  */
9391 ipaddr_t
9392 ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
9393     ip_recv_attr_t *ira, int *errorp)
9394 {
9395 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
9396 	ipoptp_t	opts;
9397 	uchar_t		*opt;
9398 	uint8_t		optval;
9399 	uint8_t		optlen;
9400 	intptr_t	code = 0;
9401 	ire_t		*ire;
9402 
9403 	ip2dbg(("ip_input_options\n"));
9404 	*errorp = 0;
9405 	for (optval = ipoptp_first(&opts, ipha);
9406 	    optval != IPOPT_EOL;
9407 	    optval = ipoptp_next(&opts)) {
9408 		opt = opts.ipoptp_cur;
9409 		optlen = opts.ipoptp_len;
9410 		ip2dbg(("ip_input_options: opt %d, len %d\n",
9411 		    optval, optlen));
9412 		/*
9413 		 * Note: we need to verify the checksum before we
9414 		 * modify anything thus this routine only extracts the next
9415 		 * hop dst from any source route.
9416 		 */
9417 		switch (optval) {
9418 			uint32_t off;
9419 		case IPOPT_SSRR:
9420 		case IPOPT_LSRR:
9421 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
9422 				if (optval == IPOPT_SSRR) {
9423 					ip1dbg(("ip_input_options: not next"
9424 					    " strict source route 0x%x\n",
9425 					    ntohl(dst)));
9426 					code = (char *)&ipha->ipha_dst -
9427 					    (char *)ipha;
9428 					goto param_prob; /* RouterReq's */
9429 				}
9430 				ip2dbg(("ip_input_options: "
9431 				    "not next source route 0x%x\n",
9432 				    ntohl(dst)));
9433 				break;
9434 			}
9435 
9436 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9437 				ip1dbg((
9438 				    "ip_input_options: bad option offset\n"));
9439 				code = (char *)&opt[IPOPT_OLEN] -
9440 				    (char *)ipha;
9441 				goto param_prob;
9442 			}
9443 			off = opt[IPOPT_OFFSET];
9444 			off--;
9445 		redo_srr:
9446 			if (optlen < IP_ADDR_LEN ||
9447 			    off > optlen - IP_ADDR_LEN) {
9448 				/* End of source route */
9449 				ip1dbg(("ip_input_options: end of SR\n"));
9450 				break;
9451 			}
9452 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
9453 			ip1dbg(("ip_input_options: next hop 0x%x\n",
9454 			    ntohl(dst)));
9455 
9456 			/*
9457 			 * Check if our address is present more than
9458 			 * once as consecutive hops in source route.
9459 			 * XXX verify per-interface ip_forwarding
9460 			 * for source route?
9461 			 */
9462 			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
9463 				off += IP_ADDR_LEN;
9464 				goto redo_srr;
9465 			}
9466 
9467 			if (dst == htonl(INADDR_LOOPBACK)) {
9468 				ip1dbg(("ip_input_options: loopback addr in "
9469 				    "source route!\n"));
9470 				goto bad_src_route;
9471 			}
9472 			/*
9473 			 * For strict: verify that dst is directly
9474 			 * reachable.
9475 			 */
9476 			if (optval == IPOPT_SSRR) {
9477 				ire = ire_ftable_lookup_v4(dst, 0, 0,
9478 				    IRE_INTERFACE, NULL, ALL_ZONES,
9479 				    ira->ira_tsl,
9480 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
9481 				    NULL);
9482 				if (ire == NULL) {
9483 					ip1dbg(("ip_input_options: SSRR not "
9484 					    "directly reachable: 0x%x\n",
9485 					    ntohl(dst)));
9486 					goto bad_src_route;
9487 				}
9488 				ire_refrele(ire);
9489 			}
9490 			/*
9491 			 * Defer update of the offset and the record route
9492 			 * until the packet is forwarded.
9493 			 */
9494 			break;
9495 		case IPOPT_RR:
9496 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9497 				ip1dbg((
9498 				    "ip_input_options: bad option offset\n"));
9499 				code = (char *)&opt[IPOPT_OLEN] -
9500 				    (char *)ipha;
9501 				goto param_prob;
9502 			}
9503 			break;
9504 		case IPOPT_TS:
9505 			/*
9506 			 * Verify that length >= 5 and that there is either
9507 			 * room for another timestamp or that the overflow
9508 			 * counter is not maxed out.
9509 			 */
9510 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
9511 			if (optlen < IPOPT_MINLEN_IT) {
9512 				goto param_prob;
9513 			}
9514 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
9515 				ip1dbg((
9516 				    "ip_input_options: bad option offset\n"));
9517 				code = (char *)&opt[IPOPT_OFFSET] -
9518 				    (char *)ipha;
9519 				goto param_prob;
9520 			}
9521 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
9522 			case IPOPT_TS_TSONLY:
9523 				off = IPOPT_TS_TIMELEN;
9524 				break;
9525 			case IPOPT_TS_TSANDADDR:
9526 			case IPOPT_TS_PRESPEC:
9527 			case IPOPT_TS_PRESPEC_RFC791:
9528 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
9529 				break;
9530 			default:
9531 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
9532 				    (char *)ipha;
9533 				goto param_prob;
9534 			}
9535 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
9536 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
9537 				/*
9538 				 * No room and the overflow counter is 15
9539 				 * already.
9540 				 */
9541 				goto param_prob;
9542 			}
9543 			break;
9544 		}
9545 	}
9546 
9547 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
9548 		return (dst);
9549 	}
9550 
9551 	ip1dbg(("ip_input_options: error processing IP options."));
9552 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
9553 
9554 param_prob:
9555 	/* make sure we clear any indication of a hardware checksum */
9556 	DB_CKSUMFLAGS(mp) = 0;
9557 	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
9558 	icmp_param_problem(mp, (uint8_t)code, ira);
9559 	*errorp = -1;
9560 	return (dst);
9561 
9562 bad_src_route:
9563 	/* make sure we clear any indication of a hardware checksum */
9564 	DB_CKSUMFLAGS(mp) = 0;
9565 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
9566 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
9567 	*errorp = -1;
9568 	return (dst);
9569 }
9570 
9571 /*
9572  * IP & ICMP info in >=14 msg's ...
9573  *  - ip fixed part (mib2_ip_t)
9574  *  - icmp fixed part (mib2_icmp_t)
9575  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
9576  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
9577  *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
9578  *  - ipRouteAttributeTable (ip 102)	labeled routes
9579  *  - ip multicast membership (ip_member_t)
9580  *  - ip multicast source filtering (ip_grpsrc_t)
9581  *  - igmp fixed part (struct igmpstat)
9582  *  - multicast routing stats (struct mrtstat)
9583  *  - multicast routing vifs (array of struct vifctl)
9584  *  - multicast routing routes (array of struct mfcctl)
9585  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
9586  *					One per ill plus one generic
9587  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
9588  *					One per ill plus one generic
9589  *  - ipv6RouteEntry			all IPv6 IREs
9590  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
9591  *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
9592  *  - ipv6AddrEntry			all IPv6 ipifs
9593  *  - ipv6 multicast membership (ipv6_member_t)
9594  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
9595  *
9596  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
9597  * already filled in by the caller.
9598  * If legacy_req is true then MIB structures needs to be truncated to their
9599  * legacy sizes before being returned.
9600  * Return value of 0 indicates that no messages were sent and caller
9601  * should free mpctl.
9602  */
9603 int
9604 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level, boolean_t legacy_req)
9605 {
9606 	ip_stack_t *ipst;
9607 	sctp_stack_t *sctps;
9608 
9609 	if (q->q_next != NULL) {
9610 		ipst = ILLQ_TO_IPST(q);
9611 	} else {
9612 		ipst = CONNQ_TO_IPST(q);
9613 	}
9614 	ASSERT(ipst != NULL);
9615 	sctps = ipst->ips_netstack->netstack_sctp;
9616 
9617 	if (mpctl == NULL || mpctl->b_cont == NULL) {
9618 		return (0);
9619 	}
9620 
9621 	/*
9622 	 * For the purposes of the (broken) packet shell use
9623 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
9624 	 * to make TCP and UDP appear first in the list of mib items.
9625 	 * TBD: We could expand this and use it in netstat so that
9626 	 * the kernel doesn't have to produce large tables (connections,
9627 	 * routes, etc) when netstat only wants the statistics or a particular
9628 	 * table.
9629 	 */
9630 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
9631 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
9632 			return (1);
9633 		}
9634 	}
9635 
9636 	if (level != MIB2_TCP) {
9637 		if ((mpctl = udp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9638 			return (1);
9639 		}
9640 	}
9641 
9642 	if (level != MIB2_UDP) {
9643 		if ((mpctl = tcp_snmp_get(q, mpctl, legacy_req)) == NULL) {
9644 			return (1);
9645 		}
9646 	}
9647 
9648 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
9649 	    ipst, legacy_req)) == NULL) {
9650 		return (1);
9651 	}
9652 
9653 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst,
9654 	    legacy_req)) == NULL) {
9655 		return (1);
9656 	}
9657 
9658 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
9659 		return (1);
9660 	}
9661 
9662 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
9663 		return (1);
9664 	}
9665 
9666 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
9667 		return (1);
9668 	}
9669 
9670 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
9671 		return (1);
9672 	}
9673 
9674 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst,
9675 	    legacy_req)) == NULL) {
9676 		return (1);
9677 	}
9678 
9679 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst,
9680 	    legacy_req)) == NULL) {
9681 		return (1);
9682 	}
9683 
9684 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
9685 		return (1);
9686 	}
9687 
9688 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
9689 		return (1);
9690 	}
9691 
9692 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
9693 		return (1);
9694 	}
9695 
9696 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
9697 		return (1);
9698 	}
9699 
9700 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
9701 		return (1);
9702 	}
9703 
9704 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
9705 		return (1);
9706 	}
9707 
9708 	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
9709 	if (mpctl == NULL)
9710 		return (1);
9711 
9712 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
9713 	if (mpctl == NULL)
9714 		return (1);
9715 
9716 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
9717 		return (1);
9718 	}
9719 	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
9720 		return (1);
9721 	}
9722 	freemsg(mpctl);
9723 	return (1);
9724 }
9725 
9726 /* Get global (legacy) IPv4 statistics */
9727 static mblk_t *
9728 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
9729     ip_stack_t *ipst, boolean_t legacy_req)
9730 {
9731 	mib2_ip_t		old_ip_mib;
9732 	struct opthdr		*optp;
9733 	mblk_t			*mp2ctl;
9734 	mib2_ipAddrEntry_t	mae;
9735 
9736 	/*
9737 	 * make a copy of the original message
9738 	 */
9739 	mp2ctl = copymsg(mpctl);
9740 
9741 	/* fixed length IP structure... */
9742 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9743 	optp->level = MIB2_IP;
9744 	optp->name = 0;
9745 	SET_MIB(old_ip_mib.ipForwarding,
9746 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
9747 	SET_MIB(old_ip_mib.ipDefaultTTL,
9748 	    (uint32_t)ipst->ips_ip_def_ttl);
9749 	SET_MIB(old_ip_mib.ipReasmTimeout,
9750 	    ipst->ips_ip_reassembly_timeout);
9751 	SET_MIB(old_ip_mib.ipAddrEntrySize,
9752 	    (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
9753 	    sizeof (mib2_ipAddrEntry_t));
9754 	SET_MIB(old_ip_mib.ipRouteEntrySize,
9755 	    sizeof (mib2_ipRouteEntry_t));
9756 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
9757 	    sizeof (mib2_ipNetToMediaEntry_t));
9758 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
9759 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
9760 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
9761 	    sizeof (mib2_ipAttributeEntry_t));
9762 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
9763 	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));
9764 
9765 	/*
9766 	 * Grab the statistics from the new IP MIB
9767 	 */
9768 	SET_MIB(old_ip_mib.ipInReceives,
9769 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
9770 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
9771 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
9772 	SET_MIB(old_ip_mib.ipForwDatagrams,
9773 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
9774 	SET_MIB(old_ip_mib.ipInUnknownProtos,
9775 	    ipmib->ipIfStatsInUnknownProtos);
9776 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
9777 	SET_MIB(old_ip_mib.ipInDelivers,
9778 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
9779 	SET_MIB(old_ip_mib.ipOutRequests,
9780 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
9781 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
9782 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
9783 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
9784 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
9785 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
9786 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
9787 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
9788 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
9789 
9790 	/* ipRoutingDiscards is not being used */
9791 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
9792 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
9793 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
9794 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
9795 	SET_MIB(old_ip_mib.ipReasmDuplicates,
9796 	    ipmib->ipIfStatsReasmDuplicates);
9797 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
9798 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
9799 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
9800 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
9801 	SET_MIB(old_ip_mib.rawipInOverflows,
9802 	    ipmib->rawipIfStatsInOverflows);
9803 
9804 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
9805 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
9806 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
9807 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
9808 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
9809 	    ipmib->ipIfStatsOutSwitchIPVersion);
9810 
9811 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
9812 	    (int)sizeof (old_ip_mib))) {
9813 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
9814 		    (uint_t)sizeof (old_ip_mib)));
9815 	}
9816 
9817 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9818 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
9819 	    (int)optp->level, (int)optp->name, (int)optp->len));
9820 	qreply(q, mpctl);
9821 	return (mp2ctl);
9822 }
9823 
9824 /* Per interface IPv4 statistics */
9825 static mblk_t *
9826 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9827     boolean_t legacy_req)
9828 {
9829 	struct opthdr		*optp;
9830 	mblk_t			*mp2ctl;
9831 	ill_t			*ill;
9832 	ill_walk_context_t	ctx;
9833 	mblk_t			*mp_tail = NULL;
9834 	mib2_ipIfStatsEntry_t	global_ip_mib;
9835 	mib2_ipAddrEntry_t	mae;
9836 
9837 	/*
9838 	 * Make a copy of the original message
9839 	 */
9840 	mp2ctl = copymsg(mpctl);
9841 
9842 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9843 	optp->level = MIB2_IP;
9844 	optp->name = MIB2_IP_TRAFFIC_STATS;
9845 	/* Include "unknown interface" ip_mib */
9846 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
9847 	ipst->ips_ip_mib.ipIfStatsIfIndex =
9848 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
9849 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
9850 	    (ipst->ips_ip_forwarding ? 1 : 2));
9851 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
9852 	    (uint32_t)ipst->ips_ip_def_ttl);
9853 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
9854 	    sizeof (mib2_ipIfStatsEntry_t));
9855 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
9856 	    sizeof (mib2_ipAddrEntry_t));
9857 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
9858 	    sizeof (mib2_ipRouteEntry_t));
9859 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
9860 	    sizeof (mib2_ipNetToMediaEntry_t));
9861 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
9862 	    sizeof (ip_member_t));
9863 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
9864 	    sizeof (ip_grpsrc_t));
9865 
9866 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
9867 
9868 	if (legacy_req) {
9869 		SET_MIB(global_ip_mib.ipIfStatsAddrEntrySize,
9870 		    LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t));
9871 	}
9872 
9873 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9874 	    (char *)&global_ip_mib, (int)sizeof (global_ip_mib))) {
9875 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9876 		    "failed to allocate %u bytes\n",
9877 		    (uint_t)sizeof (global_ip_mib)));
9878 	}
9879 
9880 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
9881 	ill = ILL_START_WALK_V4(&ctx, ipst);
9882 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
9883 		ill->ill_ip_mib->ipIfStatsIfIndex =
9884 		    ill->ill_phyint->phyint_ifindex;
9885 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
9886 		    (ipst->ips_ip_forwarding ? 1 : 2));
9887 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
9888 		    (uint32_t)ipst->ips_ip_def_ttl);
9889 
9890 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
9891 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
9892 		    (char *)ill->ill_ip_mib,
9893 		    (int)sizeof (*ill->ill_ip_mib))) {
9894 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9895 			    "failed to allocate %u bytes\n",
9896 			    (uint_t)sizeof (*ill->ill_ip_mib)));
9897 		}
9898 	}
9899 	rw_exit(&ipst->ips_ill_g_lock);
9900 
9901 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9902 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
9903 	    "level %d, name %d, len %d\n",
9904 	    (int)optp->level, (int)optp->name, (int)optp->len));
9905 	qreply(q, mpctl);
9906 
9907 	if (mp2ctl == NULL)
9908 		return (NULL);
9909 
9910 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst,
9911 	    legacy_req));
9912 }
9913 
9914 /* Global IPv4 ICMP statistics */
9915 static mblk_t *
9916 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9917 {
9918 	struct opthdr		*optp;
9919 	mblk_t			*mp2ctl;
9920 
9921 	/*
9922 	 * Make a copy of the original message
9923 	 */
9924 	mp2ctl = copymsg(mpctl);
9925 
9926 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9927 	optp->level = MIB2_ICMP;
9928 	optp->name = 0;
9929 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
9930 	    (int)sizeof (ipst->ips_icmp_mib))) {
9931 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
9932 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
9933 	}
9934 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9935 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
9936 	    (int)optp->level, (int)optp->name, (int)optp->len));
9937 	qreply(q, mpctl);
9938 	return (mp2ctl);
9939 }
9940 
9941 /* Global IPv4 IGMP statistics */
9942 static mblk_t *
9943 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9944 {
9945 	struct opthdr		*optp;
9946 	mblk_t			*mp2ctl;
9947 
9948 	/*
9949 	 * make a copy of the original message
9950 	 */
9951 	mp2ctl = copymsg(mpctl);
9952 
9953 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9954 	optp->level = EXPER_IGMP;
9955 	optp->name = 0;
9956 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
9957 	    (int)sizeof (ipst->ips_igmpstat))) {
9958 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
9959 		    (uint_t)sizeof (ipst->ips_igmpstat)));
9960 	}
9961 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9962 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
9963 	    (int)optp->level, (int)optp->name, (int)optp->len));
9964 	qreply(q, mpctl);
9965 	return (mp2ctl);
9966 }
9967 
9968 /* Global IPv4 Multicast Routing statistics */
9969 static mblk_t *
9970 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
9971 {
9972 	struct opthdr		*optp;
9973 	mblk_t			*mp2ctl;
9974 
9975 	/*
9976 	 * make a copy of the original message
9977 	 */
9978 	mp2ctl = copymsg(mpctl);
9979 
9980 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
9981 	optp->level = EXPER_DVMRP;
9982 	optp->name = 0;
9983 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
9984 		ip0dbg(("ip_mroute_stats: failed\n"));
9985 	}
9986 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
9987 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
9988 	    (int)optp->level, (int)optp->name, (int)optp->len));
9989 	qreply(q, mpctl);
9990 	return (mp2ctl);
9991 }
9992 
9993 /* IPv4 address information */
9994 static mblk_t *
9995 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
9996     boolean_t legacy_req)
9997 {
9998 	struct opthdr		*optp;
9999 	mblk_t			*mp2ctl;
10000 	mblk_t			*mp_tail = NULL;
10001 	ill_t			*ill;
10002 	ipif_t			*ipif;
10003 	uint_t			bitval;
10004 	mib2_ipAddrEntry_t	mae;
10005 	size_t			mae_size;
10006 	zoneid_t		zoneid;
10007 	ill_walk_context_t	ctx;
10008 
10009 	/*
10010 	 * make a copy of the original message
10011 	 */
10012 	mp2ctl = copymsg(mpctl);
10013 
10014 	mae_size = (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
10015 	    sizeof (mib2_ipAddrEntry_t);
10016 
10017 	/* ipAddrEntryTable */
10018 
10019 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10020 	optp->level = MIB2_IP;
10021 	optp->name = MIB2_IP_ADDR;
10022 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10023 
10024 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10025 	ill = ILL_START_WALK_V4(&ctx, ipst);
10026 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10027 		for (ipif = ill->ill_ipif; ipif != NULL;
10028 		    ipif = ipif->ipif_next) {
10029 			if (ipif->ipif_zoneid != zoneid &&
10030 			    ipif->ipif_zoneid != ALL_ZONES)
10031 				continue;
10032 			/* Sum of count from dead IRE_LO* and our current */
10033 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10034 			if (ipif->ipif_ire_local != NULL) {
10035 				mae.ipAdEntInfo.ae_ibcnt +=
10036 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10037 			}
10038 			mae.ipAdEntInfo.ae_obcnt = 0;
10039 			mae.ipAdEntInfo.ae_focnt = 0;
10040 
10041 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
10042 			    OCTET_LENGTH);
10043 			mae.ipAdEntIfIndex.o_length =
10044 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
10045 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
10046 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
10047 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
10048 			mae.ipAdEntInfo.ae_subnet_len =
10049 			    ip_mask_to_plen(ipif->ipif_net_mask);
10050 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
10051 			for (bitval = 1;
10052 			    bitval &&
10053 			    !(bitval & ipif->ipif_brd_addr);
10054 			    bitval <<= 1)
10055 				noop;
10056 			mae.ipAdEntBcastAddr = bitval;
10057 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
10058 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10059 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
10060 			mae.ipAdEntInfo.ae_broadcast_addr =
10061 			    ipif->ipif_brd_addr;
10062 			mae.ipAdEntInfo.ae_pp_dst_addr =
10063 			    ipif->ipif_pp_dst_addr;
10064 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
10065 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10066 			mae.ipAdEntRetransmitTime =
10067 			    ill->ill_reachable_retrans_time;
10068 
10069 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10070 			    (char *)&mae, (int)mae_size)) {
10071 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
10072 				    "allocate %u bytes\n", (uint_t)mae_size));
10073 			}
10074 		}
10075 	}
10076 	rw_exit(&ipst->ips_ill_g_lock);
10077 
10078 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10079 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
10080 	    (int)optp->level, (int)optp->name, (int)optp->len));
10081 	qreply(q, mpctl);
10082 	return (mp2ctl);
10083 }
10084 
10085 /* IPv6 address information */
10086 static mblk_t *
10087 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10088     boolean_t legacy_req)
10089 {
10090 	struct opthdr		*optp;
10091 	mblk_t			*mp2ctl;
10092 	mblk_t			*mp_tail = NULL;
10093 	ill_t			*ill;
10094 	ipif_t			*ipif;
10095 	mib2_ipv6AddrEntry_t	mae6;
10096 	size_t			mae6_size;
10097 	zoneid_t		zoneid;
10098 	ill_walk_context_t	ctx;
10099 
10100 	/*
10101 	 * make a copy of the original message
10102 	 */
10103 	mp2ctl = copymsg(mpctl);
10104 
10105 	mae6_size = (legacy_req) ?
10106 	    LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t) :
10107 	    sizeof (mib2_ipv6AddrEntry_t);
10108 
10109 	/* ipv6AddrEntryTable */
10110 
10111 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10112 	optp->level = MIB2_IP6;
10113 	optp->name = MIB2_IP6_ADDR;
10114 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10115 
10116 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10117 	ill = ILL_START_WALK_V6(&ctx, ipst);
10118 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10119 		for (ipif = ill->ill_ipif; ipif != NULL;
10120 		    ipif = ipif->ipif_next) {
10121 			if (ipif->ipif_zoneid != zoneid &&
10122 			    ipif->ipif_zoneid != ALL_ZONES)
10123 				continue;
10124 			/* Sum of count from dead IRE_LO* and our current */
10125 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
10126 			if (ipif->ipif_ire_local != NULL) {
10127 				mae6.ipv6AddrInfo.ae_ibcnt +=
10128 				    ipif->ipif_ire_local->ire_ib_pkt_count;
10129 			}
10130 			mae6.ipv6AddrInfo.ae_obcnt = 0;
10131 			mae6.ipv6AddrInfo.ae_focnt = 0;
10132 
10133 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
10134 			    OCTET_LENGTH);
10135 			mae6.ipv6AddrIfIndex.o_length =
10136 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
10137 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
10138 			mae6.ipv6AddrPfxLength =
10139 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
10140 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
10141 			mae6.ipv6AddrInfo.ae_subnet_len =
10142 			    mae6.ipv6AddrPfxLength;
10143 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;
10144 
10145 			/* Type: stateless(1), stateful(2), unknown(3) */
10146 			if (ipif->ipif_flags & IPIF_ADDRCONF)
10147 				mae6.ipv6AddrType = 1;
10148 			else
10149 				mae6.ipv6AddrType = 2;
10150 			/* Anycast: true(1), false(2) */
10151 			if (ipif->ipif_flags & IPIF_ANYCAST)
10152 				mae6.ipv6AddrAnycastFlag = 1;
10153 			else
10154 				mae6.ipv6AddrAnycastFlag = 2;
10155 
10156 			/*
10157 			 * Address status: preferred(1), deprecated(2),
10158 			 * invalid(3), inaccessible(4), unknown(5)
10159 			 */
10160 			if (ipif->ipif_flags & IPIF_NOLOCAL)
10161 				mae6.ipv6AddrStatus = 3;
10162 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
10163 				mae6.ipv6AddrStatus = 2;
10164 			else
10165 				mae6.ipv6AddrStatus = 1;
10166 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
10167 			mae6.ipv6AddrInfo.ae_metric  =
10168 			    ipif->ipif_ill->ill_metric;
10169 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
10170 			    ipif->ipif_v6pp_dst_addr;
10171 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
10172 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
10173 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
10174 			mae6.ipv6AddrIdentifier = ill->ill_token;
10175 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
10176 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
10177 			mae6.ipv6AddrRetransmitTime =
10178 			    ill->ill_reachable_retrans_time;
10179 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10180 			    (char *)&mae6, (int)mae6_size)) {
10181 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
10182 				    "allocate %u bytes\n",
10183 				    (uint_t)mae6_size));
10184 			}
10185 		}
10186 	}
10187 	rw_exit(&ipst->ips_ill_g_lock);
10188 
10189 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10190 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
10191 	    (int)optp->level, (int)optp->name, (int)optp->len));
10192 	qreply(q, mpctl);
10193 	return (mp2ctl);
10194 }
10195 
10196 /* IPv4 multicast group membership. */
10197 static mblk_t *
10198 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10199 {
10200 	struct opthdr		*optp;
10201 	mblk_t			*mp2ctl;
10202 	ill_t			*ill;
10203 	ipif_t			*ipif;
10204 	ilm_t			*ilm;
10205 	ip_member_t		ipm;
10206 	mblk_t			*mp_tail = NULL;
10207 	ill_walk_context_t	ctx;
10208 	zoneid_t		zoneid;
10209 
10210 	/*
10211 	 * make a copy of the original message
10212 	 */
10213 	mp2ctl = copymsg(mpctl);
10214 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10215 
10216 	/* ipGroupMember table */
10217 	optp = (struct opthdr *)&mpctl->b_rptr[
10218 	    sizeof (struct T_optmgmt_ack)];
10219 	optp->level = MIB2_IP;
10220 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
10221 
10222 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10223 	ill = ILL_START_WALK_V4(&ctx, ipst);
10224 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10225 		/* Make sure the ill isn't going away. */
10226 		if (!ill_check_and_refhold(ill))
10227 			continue;
10228 		rw_exit(&ipst->ips_ill_g_lock);
10229 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10230 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10231 			if (ilm->ilm_zoneid != zoneid &&
10232 			    ilm->ilm_zoneid != ALL_ZONES)
10233 				continue;
10234 
10235 			/* Is there an ipif for ilm_ifaddr? */
10236 			for (ipif = ill->ill_ipif; ipif != NULL;
10237 			    ipif = ipif->ipif_next) {
10238 				if (!IPIF_IS_CONDEMNED(ipif) &&
10239 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10240 				    ilm->ilm_ifaddr != INADDR_ANY)
10241 					break;
10242 			}
10243 			if (ipif != NULL) {
10244 				ipif_get_name(ipif,
10245 				    ipm.ipGroupMemberIfIndex.o_bytes,
10246 				    OCTET_LENGTH);
10247 			} else {
10248 				ill_get_name(ill,
10249 				    ipm.ipGroupMemberIfIndex.o_bytes,
10250 				    OCTET_LENGTH);
10251 			}
10252 			ipm.ipGroupMemberIfIndex.o_length =
10253 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
10254 
10255 			ipm.ipGroupMemberAddress = ilm->ilm_addr;
10256 			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
10257 			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
10258 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10259 			    (char *)&ipm, (int)sizeof (ipm))) {
10260 				ip1dbg(("ip_snmp_get_mib2_ip_group: "
10261 				    "failed to allocate %u bytes\n",
10262 				    (uint_t)sizeof (ipm)));
10263 			}
10264 		}
10265 		rw_exit(&ill->ill_mcast_lock);
10266 		ill_refrele(ill);
10267 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10268 	}
10269 	rw_exit(&ipst->ips_ill_g_lock);
10270 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10271 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10272 	    (int)optp->level, (int)optp->name, (int)optp->len));
10273 	qreply(q, mpctl);
10274 	return (mp2ctl);
10275 }
10276 
10277 /* IPv6 multicast group membership. */
10278 static mblk_t *
10279 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10280 {
10281 	struct opthdr		*optp;
10282 	mblk_t			*mp2ctl;
10283 	ill_t			*ill;
10284 	ilm_t			*ilm;
10285 	ipv6_member_t		ipm6;
10286 	mblk_t			*mp_tail = NULL;
10287 	ill_walk_context_t	ctx;
10288 	zoneid_t		zoneid;
10289 
10290 	/*
10291 	 * make a copy of the original message
10292 	 */
10293 	mp2ctl = copymsg(mpctl);
10294 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10295 
10296 	/* ip6GroupMember table */
10297 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10298 	optp->level = MIB2_IP6;
10299 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
10300 
10301 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10302 	ill = ILL_START_WALK_V6(&ctx, ipst);
10303 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10304 		/* Make sure the ill isn't going away. */
10305 		if (!ill_check_and_refhold(ill))
10306 			continue;
10307 		rw_exit(&ipst->ips_ill_g_lock);
10308 		/*
10309 		 * Normally we don't have any members on under IPMP interfaces.
10310 		 * We report them as a debugging aid.
10311 		 */
10312 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10313 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
10314 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10315 			if (ilm->ilm_zoneid != zoneid &&
10316 			    ilm->ilm_zoneid != ALL_ZONES)
10317 				continue;	/* not this zone */
10318 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
10319 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
10320 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
10321 			if (!snmp_append_data2(mpctl->b_cont,
10322 			    &mp_tail,
10323 			    (char *)&ipm6, (int)sizeof (ipm6))) {
10324 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
10325 				    "failed to allocate %u bytes\n",
10326 				    (uint_t)sizeof (ipm6)));
10327 			}
10328 		}
10329 		rw_exit(&ill->ill_mcast_lock);
10330 		ill_refrele(ill);
10331 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10332 	}
10333 	rw_exit(&ipst->ips_ill_g_lock);
10334 
10335 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10336 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10337 	    (int)optp->level, (int)optp->name, (int)optp->len));
10338 	qreply(q, mpctl);
10339 	return (mp2ctl);
10340 }
10341 
10342 /* IP multicast filtered sources */
10343 static mblk_t *
10344 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10345 {
10346 	struct opthdr		*optp;
10347 	mblk_t			*mp2ctl;
10348 	ill_t			*ill;
10349 	ipif_t			*ipif;
10350 	ilm_t			*ilm;
10351 	ip_grpsrc_t		ips;
10352 	mblk_t			*mp_tail = NULL;
10353 	ill_walk_context_t	ctx;
10354 	zoneid_t		zoneid;
10355 	int			i;
10356 	slist_t			*sl;
10357 
10358 	/*
10359 	 * make a copy of the original message
10360 	 */
10361 	mp2ctl = copymsg(mpctl);
10362 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10363 
10364 	/* ipGroupSource table */
10365 	optp = (struct opthdr *)&mpctl->b_rptr[
10366 	    sizeof (struct T_optmgmt_ack)];
10367 	optp->level = MIB2_IP;
10368 	optp->name = EXPER_IP_GROUP_SOURCES;
10369 
10370 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10371 	ill = ILL_START_WALK_V4(&ctx, ipst);
10372 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10373 		/* Make sure the ill isn't going away. */
10374 		if (!ill_check_and_refhold(ill))
10375 			continue;
10376 		rw_exit(&ipst->ips_ill_g_lock);
10377 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10378 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10379 			sl = ilm->ilm_filter;
10380 			if (ilm->ilm_zoneid != zoneid &&
10381 			    ilm->ilm_zoneid != ALL_ZONES)
10382 				continue;
10383 			if (SLIST_IS_EMPTY(sl))
10384 				continue;
10385 
10386 			/* Is there an ipif for ilm_ifaddr? */
10387 			for (ipif = ill->ill_ipif; ipif != NULL;
10388 			    ipif = ipif->ipif_next) {
10389 				if (!IPIF_IS_CONDEMNED(ipif) &&
10390 				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
10391 				    ilm->ilm_ifaddr != INADDR_ANY)
10392 					break;
10393 			}
10394 			if (ipif != NULL) {
10395 				ipif_get_name(ipif,
10396 				    ips.ipGroupSourceIfIndex.o_bytes,
10397 				    OCTET_LENGTH);
10398 			} else {
10399 				ill_get_name(ill,
10400 				    ips.ipGroupSourceIfIndex.o_bytes,
10401 				    OCTET_LENGTH);
10402 			}
10403 			ips.ipGroupSourceIfIndex.o_length =
10404 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
10405 
10406 			ips.ipGroupSourceGroup = ilm->ilm_addr;
10407 			for (i = 0; i < sl->sl_numsrc; i++) {
10408 				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
10409 					continue;
10410 				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
10411 				    ips.ipGroupSourceAddress);
10412 				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
10413 				    (char *)&ips, (int)sizeof (ips)) == 0) {
10414 					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
10415 					    " failed to allocate %u bytes\n",
10416 					    (uint_t)sizeof (ips)));
10417 				}
10418 			}
10419 		}
10420 		rw_exit(&ill->ill_mcast_lock);
10421 		ill_refrele(ill);
10422 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10423 	}
10424 	rw_exit(&ipst->ips_ill_g_lock);
10425 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10426 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10427 	    (int)optp->level, (int)optp->name, (int)optp->len));
10428 	qreply(q, mpctl);
10429 	return (mp2ctl);
10430 }
10431 
10432 /* IPv6 multicast filtered sources. */
10433 static mblk_t *
10434 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10435 {
10436 	struct opthdr		*optp;
10437 	mblk_t			*mp2ctl;
10438 	ill_t			*ill;
10439 	ilm_t			*ilm;
10440 	ipv6_grpsrc_t		ips6;
10441 	mblk_t			*mp_tail = NULL;
10442 	ill_walk_context_t	ctx;
10443 	zoneid_t		zoneid;
10444 	int			i;
10445 	slist_t			*sl;
10446 
10447 	/*
10448 	 * make a copy of the original message
10449 	 */
10450 	mp2ctl = copymsg(mpctl);
10451 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10452 
10453 	/* ip6GroupMember table */
10454 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10455 	optp->level = MIB2_IP6;
10456 	optp->name = EXPER_IP6_GROUP_SOURCES;
10457 
10458 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10459 	ill = ILL_START_WALK_V6(&ctx, ipst);
10460 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10461 		/* Make sure the ill isn't going away. */
10462 		if (!ill_check_and_refhold(ill))
10463 			continue;
10464 		rw_exit(&ipst->ips_ill_g_lock);
10465 		/*
10466 		 * Normally we don't have any members on under IPMP interfaces.
10467 		 * We report them as a debugging aid.
10468 		 */
10469 		rw_enter(&ill->ill_mcast_lock, RW_READER);
10470 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
10471 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
10472 			sl = ilm->ilm_filter;
10473 			if (ilm->ilm_zoneid != zoneid &&
10474 			    ilm->ilm_zoneid != ALL_ZONES)
10475 				continue;
10476 			if (SLIST_IS_EMPTY(sl))
10477 				continue;
10478 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
10479 			for (i = 0; i < sl->sl_numsrc; i++) {
10480 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
10481 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10482 				    (char *)&ips6, (int)sizeof (ips6))) {
10483 					ip1dbg(("ip_snmp_get_mib2_ip6_"
10484 					    "group_src: failed to allocate "
10485 					    "%u bytes\n",
10486 					    (uint_t)sizeof (ips6)));
10487 				}
10488 			}
10489 		}
10490 		rw_exit(&ill->ill_mcast_lock);
10491 		ill_refrele(ill);
10492 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10493 	}
10494 	rw_exit(&ipst->ips_ill_g_lock);
10495 
10496 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10497 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
10498 	    (int)optp->level, (int)optp->name, (int)optp->len));
10499 	qreply(q, mpctl);
10500 	return (mp2ctl);
10501 }
10502 
10503 /* Multicast routing virtual interface table. */
10504 static mblk_t *
10505 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10506 {
10507 	struct opthdr		*optp;
10508 	mblk_t			*mp2ctl;
10509 
10510 	/*
10511 	 * make a copy of the original message
10512 	 */
10513 	mp2ctl = copymsg(mpctl);
10514 
10515 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10516 	optp->level = EXPER_DVMRP;
10517 	optp->name = EXPER_DVMRP_VIF;
10518 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
10519 		ip0dbg(("ip_mroute_vif: failed\n"));
10520 	}
10521 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10522 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
10523 	    (int)optp->level, (int)optp->name, (int)optp->len));
10524 	qreply(q, mpctl);
10525 	return (mp2ctl);
10526 }
10527 
10528 /* Multicast routing table. */
10529 static mblk_t *
10530 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10531 {
10532 	struct opthdr		*optp;
10533 	mblk_t			*mp2ctl;
10534 
10535 	/*
10536 	 * make a copy of the original message
10537 	 */
10538 	mp2ctl = copymsg(mpctl);
10539 
10540 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10541 	optp->level = EXPER_DVMRP;
10542 	optp->name = EXPER_DVMRP_MRT;
10543 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
10544 		ip0dbg(("ip_mroute_mrt: failed\n"));
10545 	}
10546 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10547 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
10548 	    (int)optp->level, (int)optp->name, (int)optp->len));
10549 	qreply(q, mpctl);
10550 	return (mp2ctl);
10551 }
10552 
10553 /*
10554  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
10555  * in one IRE walk.
10556  */
10557 static mblk_t *
10558 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
10559     ip_stack_t *ipst)
10560 {
10561 	struct opthdr	*optp;
10562 	mblk_t		*mp2ctl;	/* Returned */
10563 	mblk_t		*mp3ctl;	/* nettomedia */
10564 	mblk_t		*mp4ctl;	/* routeattrs */
10565 	iproutedata_t	ird;
10566 	zoneid_t	zoneid;
10567 
10568 	/*
10569 	 * make copies of the original message
10570 	 *	- mp2ctl is returned unchanged to the caller for its use
10571 	 *	- mpctl is sent upstream as ipRouteEntryTable
10572 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
10573 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
10574 	 */
10575 	mp2ctl = copymsg(mpctl);
10576 	mp3ctl = copymsg(mpctl);
10577 	mp4ctl = copymsg(mpctl);
10578 	if (mp3ctl == NULL || mp4ctl == NULL) {
10579 		freemsg(mp4ctl);
10580 		freemsg(mp3ctl);
10581 		freemsg(mp2ctl);
10582 		freemsg(mpctl);
10583 		return (NULL);
10584 	}
10585 
10586 	bzero(&ird, sizeof (ird));
10587 
10588 	ird.ird_route.lp_head = mpctl->b_cont;
10589 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10590 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10591 	/*
10592 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10593 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10594 	 * intended a temporary solution until a proper MIB API is provided
10595 	 * that provides complete filtering/caller-opt-in.
10596 	 */
10597 	if (level == EXPER_IP_AND_ALL_IRES)
10598 		ird.ird_flags |= IRD_REPORT_ALL;
10599 
10600 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10601 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
10602 
10603 	/* ipRouteEntryTable in mpctl */
10604 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10605 	optp->level = MIB2_IP;
10606 	optp->name = MIB2_IP_ROUTE;
10607 	optp->len = msgdsize(ird.ird_route.lp_head);
10608 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10609 	    (int)optp->level, (int)optp->name, (int)optp->len));
10610 	qreply(q, mpctl);
10611 
10612 	/* ipNetToMediaEntryTable in mp3ctl */
10613 	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);
10614 
10615 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10616 	optp->level = MIB2_IP;
10617 	optp->name = MIB2_IP_MEDIA;
10618 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10619 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10620 	    (int)optp->level, (int)optp->name, (int)optp->len));
10621 	qreply(q, mp3ctl);
10622 
10623 	/* ipRouteAttributeTable in mp4ctl */
10624 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10625 	optp->level = MIB2_IP;
10626 	optp->name = EXPER_IP_RTATTR;
10627 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10628 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
10629 	    (int)optp->level, (int)optp->name, (int)optp->len));
10630 	if (optp->len == 0)
10631 		freemsg(mp4ctl);
10632 	else
10633 		qreply(q, mp4ctl);
10634 
10635 	return (mp2ctl);
10636 }
10637 
10638 /*
10639  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
10640  * ipv6NetToMediaEntryTable in an NDP walk.
10641  */
10642 static mblk_t *
10643 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
10644     ip_stack_t *ipst)
10645 {
10646 	struct opthdr	*optp;
10647 	mblk_t		*mp2ctl;	/* Returned */
10648 	mblk_t		*mp3ctl;	/* nettomedia */
10649 	mblk_t		*mp4ctl;	/* routeattrs */
10650 	iproutedata_t	ird;
10651 	zoneid_t	zoneid;
10652 
10653 	/*
10654 	 * make copies of the original message
10655 	 *	- mp2ctl is returned unchanged to the caller for its use
10656 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
10657 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
10658 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
10659 	 */
10660 	mp2ctl = copymsg(mpctl);
10661 	mp3ctl = copymsg(mpctl);
10662 	mp4ctl = copymsg(mpctl);
10663 	if (mp3ctl == NULL || mp4ctl == NULL) {
10664 		freemsg(mp4ctl);
10665 		freemsg(mp3ctl);
10666 		freemsg(mp2ctl);
10667 		freemsg(mpctl);
10668 		return (NULL);
10669 	}
10670 
10671 	bzero(&ird, sizeof (ird));
10672 
10673 	ird.ird_route.lp_head = mpctl->b_cont;
10674 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
10675 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
10676 	/*
10677 	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
10678 	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
10679 	 * intended a temporary solution until a proper MIB API is provided
10680 	 * that provides complete filtering/caller-opt-in.
10681 	 */
10682 	if (level == EXPER_IP_AND_ALL_IRES)
10683 		ird.ird_flags |= IRD_REPORT_ALL;
10684 
10685 	zoneid = Q_TO_CONN(q)->conn_zoneid;
10686 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
10687 
10688 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10689 	optp->level = MIB2_IP6;
10690 	optp->name = MIB2_IP6_ROUTE;
10691 	optp->len = msgdsize(ird.ird_route.lp_head);
10692 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10693 	    (int)optp->level, (int)optp->name, (int)optp->len));
10694 	qreply(q, mpctl);
10695 
10696 	/* ipv6NetToMediaEntryTable in mp3ctl */
10697 	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
10698 
10699 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10700 	optp->level = MIB2_IP6;
10701 	optp->name = MIB2_IP6_MEDIA;
10702 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
10703 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10704 	    (int)optp->level, (int)optp->name, (int)optp->len));
10705 	qreply(q, mp3ctl);
10706 
10707 	/* ipv6RouteAttributeTable in mp4ctl */
10708 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10709 	optp->level = MIB2_IP6;
10710 	optp->name = EXPER_IP_RTATTR;
10711 	optp->len = msgdsize(ird.ird_attrs.lp_head);
10712 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
10713 	    (int)optp->level, (int)optp->name, (int)optp->len));
10714 	if (optp->len == 0)
10715 		freemsg(mp4ctl);
10716 	else
10717 		qreply(q, mp4ctl);
10718 
10719 	return (mp2ctl);
10720 }
10721 
10722 /*
10723  * IPv6 mib: One per ill
10724  */
10725 static mblk_t *
10726 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
10727     boolean_t legacy_req)
10728 {
10729 	struct opthdr		*optp;
10730 	mblk_t			*mp2ctl;
10731 	ill_t			*ill;
10732 	ill_walk_context_t	ctx;
10733 	mblk_t			*mp_tail = NULL;
10734 	mib2_ipv6AddrEntry_t	mae6;
10735 	mib2_ipIfStatsEntry_t	*ise;
10736 	size_t			ise_size, iae_size;
10737 
10738 	/*
10739 	 * Make a copy of the original message
10740 	 */
10741 	mp2ctl = copymsg(mpctl);
10742 
10743 	/* fixed length IPv6 structure ... */
10744 
10745 	if (legacy_req) {
10746 		ise_size = LEGACY_MIB_SIZE(&ipst->ips_ip6_mib,
10747 		    mib2_ipIfStatsEntry_t);
10748 		iae_size = LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t);
10749 	} else {
10750 		ise_size = sizeof (mib2_ipIfStatsEntry_t);
10751 		iae_size = sizeof (mib2_ipv6AddrEntry_t);
10752 	}
10753 
10754 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10755 	optp->level = MIB2_IP6;
10756 	optp->name = 0;
10757 	/* Include "unknown interface" ip6_mib */
10758 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
10759 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
10760 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
10761 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
10762 	    ipst->ips_ipv6_forwarding ? 1 : 2);
10763 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
10764 	    ipst->ips_ipv6_def_hops);
10765 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
10766 	    sizeof (mib2_ipIfStatsEntry_t));
10767 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
10768 	    sizeof (mib2_ipv6AddrEntry_t));
10769 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
10770 	    sizeof (mib2_ipv6RouteEntry_t));
10771 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
10772 	    sizeof (mib2_ipv6NetToMediaEntry_t));
10773 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
10774 	    sizeof (ipv6_member_t));
10775 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
10776 	    sizeof (ipv6_grpsrc_t));
10777 
10778 	/*
10779 	 * Synchronize 64- and 32-bit counters
10780 	 */
10781 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
10782 	    ipIfStatsHCInReceives);
10783 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
10784 	    ipIfStatsHCInDelivers);
10785 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
10786 	    ipIfStatsHCOutRequests);
10787 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
10788 	    ipIfStatsHCOutForwDatagrams);
10789 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
10790 	    ipIfStatsHCOutMcastPkts);
10791 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
10792 	    ipIfStatsHCInMcastPkts);
10793 
10794 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10795 	    (char *)&ipst->ips_ip6_mib, (int)ise_size)) {
10796 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
10797 		    (uint_t)ise_size));
10798 	} else if (legacy_req) {
10799 		/* Adjust the EntrySize fields for legacy requests. */
10800 		ise =
10801 		    (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr - (int)ise_size);
10802 		SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10803 		SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10804 	}
10805 
10806 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10807 	ill = ILL_START_WALK_V6(&ctx, ipst);
10808 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10809 		ill->ill_ip_mib->ipIfStatsIfIndex =
10810 		    ill->ill_phyint->phyint_ifindex;
10811 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
10812 		    ipst->ips_ipv6_forwarding ? 1 : 2);
10813 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
10814 		    ill->ill_max_hops);
10815 
10816 		/*
10817 		 * Synchronize 64- and 32-bit counters
10818 		 */
10819 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
10820 		    ipIfStatsHCInReceives);
10821 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
10822 		    ipIfStatsHCInDelivers);
10823 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
10824 		    ipIfStatsHCOutRequests);
10825 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
10826 		    ipIfStatsHCOutForwDatagrams);
10827 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
10828 		    ipIfStatsHCOutMcastPkts);
10829 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
10830 		    ipIfStatsHCInMcastPkts);
10831 
10832 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10833 		    (char *)ill->ill_ip_mib, (int)ise_size)) {
10834 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
10835 			"%u bytes\n", (uint_t)ise_size));
10836 		} else if (legacy_req) {
10837 			/* Adjust the EntrySize fields for legacy requests. */
10838 			ise = (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr -
10839 			    (int)ise_size);
10840 			SET_MIB(ise->ipIfStatsEntrySize, ise_size);
10841 			SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
10842 		}
10843 	}
10844 	rw_exit(&ipst->ips_ill_g_lock);
10845 
10846 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10847 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
10848 	    (int)optp->level, (int)optp->name, (int)optp->len));
10849 	qreply(q, mpctl);
10850 	return (mp2ctl);
10851 }
10852 
10853 /*
10854  * ICMPv6 mib: One per ill
10855  */
10856 static mblk_t *
10857 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
10858 {
10859 	struct opthdr		*optp;
10860 	mblk_t			*mp2ctl;
10861 	ill_t			*ill;
10862 	ill_walk_context_t	ctx;
10863 	mblk_t			*mp_tail = NULL;
10864 	/*
10865 	 * Make a copy of the original message
10866 	 */
10867 	mp2ctl = copymsg(mpctl);
10868 
10869 	/* fixed length ICMPv6 structure ... */
10870 
10871 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
10872 	optp->level = MIB2_ICMP6;
10873 	optp->name = 0;
10874 	/* Include "unknown interface" icmp6_mib */
10875 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
10876 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
10877 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
10878 	    sizeof (mib2_ipv6IfIcmpEntry_t);
10879 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10880 	    (char *)&ipst->ips_icmp6_mib,
10881 	    (int)sizeof (ipst->ips_icmp6_mib))) {
10882 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
10883 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
10884 	}
10885 
10886 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
10887 	ill = ILL_START_WALK_V6(&ctx, ipst);
10888 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
10889 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
10890 		    ill->ill_phyint->phyint_ifindex;
10891 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
10892 		    (char *)ill->ill_icmp6_mib,
10893 		    (int)sizeof (*ill->ill_icmp6_mib))) {
10894 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
10895 			    "%u bytes\n",
10896 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
10897 		}
10898 	}
10899 	rw_exit(&ipst->ips_ill_g_lock);
10900 
10901 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
10902 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
10903 	    (int)optp->level, (int)optp->name, (int)optp->len));
10904 	qreply(q, mpctl);
10905 	return (mp2ctl);
10906 }
10907 
10908 /*
10909  * ire_walk routine to create both ipRouteEntryTable and
10910  * ipRouteAttributeTable in one IRE walk
10911  */
10912 static void
10913 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
10914 {
10915 	ill_t				*ill;
10916 	mib2_ipRouteEntry_t		*re;
10917 	mib2_ipAttributeEntry_t		iaes;
10918 	tsol_ire_gw_secattr_t		*attrp;
10919 	tsol_gc_t			*gc = NULL;
10920 	tsol_gcgrp_t			*gcgrp = NULL;
10921 	ip_stack_t			*ipst = ire->ire_ipst;
10922 
10923 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
10924 
10925 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
10926 		if (ire->ire_testhidden)
10927 			return;
10928 		if (ire->ire_type & IRE_IF_CLONE)
10929 			return;
10930 	}
10931 
10932 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
10933 		return;
10934 
10935 	if ((attrp = ire->ire_gw_secattr) != NULL) {
10936 		mutex_enter(&attrp->igsa_lock);
10937 		if ((gc = attrp->igsa_gc) != NULL) {
10938 			gcgrp = gc->gc_grp;
10939 			ASSERT(gcgrp != NULL);
10940 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
10941 		}
10942 		mutex_exit(&attrp->igsa_lock);
10943 	}
10944 	/*
10945 	 * Return all IRE types for route table... let caller pick and choose
10946 	 */
10947 	re->ipRouteDest = ire->ire_addr;
10948 	ill = ire->ire_ill;
10949 	re->ipRouteIfIndex.o_length = 0;
10950 	if (ill != NULL) {
10951 		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
10952 		re->ipRouteIfIndex.o_length =
10953 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
10954 	}
10955 	re->ipRouteMetric1 = -1;
10956 	re->ipRouteMetric2 = -1;
10957 	re->ipRouteMetric3 = -1;
10958 	re->ipRouteMetric4 = -1;
10959 
10960 	re->ipRouteNextHop = ire->ire_gateway_addr;
10961 	/* indirect(4), direct(3), or invalid(2) */
10962 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
10963 		re->ipRouteType = 2;
10964 	else if (ire->ire_type & IRE_ONLINK)
10965 		re->ipRouteType = 3;
10966 	else
10967 		re->ipRouteType = 4;
10968 
10969 	re->ipRouteProto = -1;
10970 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
10971 	re->ipRouteMask = ire->ire_mask;
10972 	re->ipRouteMetric5 = -1;
10973 	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
10974 	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
10975 		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
10976 
10977 	re->ipRouteInfo.re_frag_flag	= 0;
10978 	re->ipRouteInfo.re_rtt		= 0;
10979 	re->ipRouteInfo.re_src_addr	= 0;
10980 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
10981 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
10982 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
10983 	re->ipRouteInfo.re_flags	= ire->ire_flags;
10984 
10985 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
10986 	if (ire->ire_type & IRE_INTERFACE) {
10987 		ire_t *child;
10988 
10989 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
10990 		child = ire->ire_dep_children;
10991 		while (child != NULL) {
10992 			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
10993 			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
10994 			child = child->ire_dep_sib_next;
10995 		}
10996 		rw_exit(&ipst->ips_ire_dep_lock);
10997 	}
10998 
10999 	if (ire->ire_flags & RTF_DYNAMIC) {
11000 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11001 	} else {
11002 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
11003 	}
11004 
11005 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11006 	    (char *)re, (int)sizeof (*re))) {
11007 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
11008 		    (uint_t)sizeof (*re)));
11009 	}
11010 
11011 	if (gc != NULL) {
11012 		iaes.iae_routeidx = ird->ird_idx;
11013 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11014 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11015 
11016 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11017 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11018 			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
11019 			    "bytes\n", (uint_t)sizeof (iaes)));
11020 		}
11021 	}
11022 
11023 	/* bump route index for next pass */
11024 	ird->ird_idx++;
11025 
11026 	kmem_free(re, sizeof (*re));
11027 	if (gcgrp != NULL)
11028 		rw_exit(&gcgrp->gcgrp_rwlock);
11029 }
11030 
11031 /*
11032  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
11033  */
11034 static void
11035 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
11036 {
11037 	ill_t				*ill;
11038 	mib2_ipv6RouteEntry_t		*re;
11039 	mib2_ipAttributeEntry_t		iaes;
11040 	tsol_ire_gw_secattr_t		*attrp;
11041 	tsol_gc_t			*gc = NULL;
11042 	tsol_gcgrp_t			*gcgrp = NULL;
11043 	ip_stack_t			*ipst = ire->ire_ipst;
11044 
11045 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
11046 
11047 	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
11048 		if (ire->ire_testhidden)
11049 			return;
11050 		if (ire->ire_type & IRE_IF_CLONE)
11051 			return;
11052 	}
11053 
11054 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
11055 		return;
11056 
11057 	if ((attrp = ire->ire_gw_secattr) != NULL) {
11058 		mutex_enter(&attrp->igsa_lock);
11059 		if ((gc = attrp->igsa_gc) != NULL) {
11060 			gcgrp = gc->gc_grp;
11061 			ASSERT(gcgrp != NULL);
11062 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
11063 		}
11064 		mutex_exit(&attrp->igsa_lock);
11065 	}
11066 	/*
11067 	 * Return all IRE types for route table... let caller pick and choose
11068 	 */
11069 	re->ipv6RouteDest = ire->ire_addr_v6;
11070 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
11071 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
11072 	re->ipv6RouteIfIndex.o_length = 0;
11073 	ill = ire->ire_ill;
11074 	if (ill != NULL) {
11075 		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
11076 		re->ipv6RouteIfIndex.o_length =
11077 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
11078 	}
11079 
11080 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
11081 
11082 	mutex_enter(&ire->ire_lock);
11083 	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
11084 	mutex_exit(&ire->ire_lock);
11085 
11086 	/* remote(4), local(3), or discard(2) */
11087 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
11088 		re->ipv6RouteType = 2;
11089 	else if (ire->ire_type & IRE_ONLINK)
11090 		re->ipv6RouteType = 3;
11091 	else
11092 		re->ipv6RouteType = 4;
11093 
11094 	re->ipv6RouteProtocol	= -1;
11095 	re->ipv6RoutePolicy	= 0;
11096 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
11097 	re->ipv6RouteNextHopRDI	= 0;
11098 	re->ipv6RouteWeight	= 0;
11099 	re->ipv6RouteMetric	= 0;
11100 	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
11101 	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
11102 		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;
11103 
11104 	re->ipv6RouteInfo.re_frag_flag	= 0;
11105 	re->ipv6RouteInfo.re_rtt	= 0;
11106 	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
11107 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
11108 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
11109 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
11110 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
11111 
11112 	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
11113 	if (ire->ire_type & IRE_INTERFACE) {
11114 		ire_t *child;
11115 
11116 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
11117 		child = ire->ire_dep_children;
11118 		while (child != NULL) {
11119 			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
11120 			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
11121 			child = child->ire_dep_sib_next;
11122 		}
11123 		rw_exit(&ipst->ips_ire_dep_lock);
11124 	}
11125 	if (ire->ire_flags & RTF_DYNAMIC) {
11126 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
11127 	} else {
11128 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
11129 	}
11130 
11131 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
11132 	    (char *)re, (int)sizeof (*re))) {
11133 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
11134 		    (uint_t)sizeof (*re)));
11135 	}
11136 
11137 	if (gc != NULL) {
11138 		iaes.iae_routeidx = ird->ird_idx;
11139 		iaes.iae_doi = gc->gc_db->gcdb_doi;
11140 		iaes.iae_slrange = gc->gc_db->gcdb_slrange;
11141 
11142 		if (!snmp_append_data2(ird->ird_attrs.lp_head,
11143 		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
11144 			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
11145 			    "bytes\n", (uint_t)sizeof (iaes)));
11146 		}
11147 	}
11148 
11149 	/* bump route index for next pass */
11150 	ird->ird_idx++;
11151 
11152 	kmem_free(re, sizeof (*re));
11153 	if (gcgrp != NULL)
11154 		rw_exit(&gcgrp->gcgrp_rwlock);
11155 }
11156 
11157 /*
11158  * ncec_walk routine to create ipv6NetToMediaEntryTable
11159  */
11160 static int
11161 ip_snmp_get2_v6_media(ncec_t *ncec, iproutedata_t *ird)
11162 {
11163 	ill_t				*ill;
11164 	mib2_ipv6NetToMediaEntry_t	ntme;
11165 
11166 	ill = ncec->ncec_ill;
11167 	/* skip arpce entries, and loopback ncec entries */
11168 	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
11169 		return (0);
11170 	/*
11171 	 * Neighbor cache entry attached to IRE with on-link
11172 	 * destination.
11173 	 * We report all IPMP groups on ncec_ill which is normally the upper.
11174 	 */
11175 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
11176 	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
11177 	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
11178 	if (ncec->ncec_lladdr != NULL) {
11179 		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
11180 		    ntme.ipv6NetToMediaPhysAddress.o_length);
11181 	}
11182 	/*
11183 	 * Note: Returns ND_* states. Should be:
11184 	 * reachable(1), stale(2), delay(3), probe(4),
11185 	 * invalid(5), unknown(6)
11186 	 */
11187 	ntme.ipv6NetToMediaState = ncec->ncec_state;
11188 	ntme.ipv6NetToMediaLastUpdated = 0;
11189 
11190 	/* other(1), dynamic(2), static(3), local(4) */
11191 	if (NCE_MYADDR(ncec)) {
11192 		ntme.ipv6NetToMediaType = 4;
11193 	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
11194 		ntme.ipv6NetToMediaType = 1; /* proxy */
11195 	} else if (ncec->ncec_flags & NCE_F_STATIC) {
11196 		ntme.ipv6NetToMediaType = 3;
11197 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
11198 		ntme.ipv6NetToMediaType = 1;
11199 	} else {
11200 		ntme.ipv6NetToMediaType = 2;
11201 	}
11202 
11203 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11204 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11205 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
11206 		    (uint_t)sizeof (ntme)));
11207 	}
11208 	return (0);
11209 }
11210 
11211 int
11212 nce2ace(ncec_t *ncec)
11213 {
11214 	int flags = 0;
11215 
11216 	if (NCE_ISREACHABLE(ncec))
11217 		flags |= ACE_F_RESOLVED;
11218 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11219 		flags |= ACE_F_AUTHORITY;
11220 	if (ncec->ncec_flags & NCE_F_PUBLISH)
11221 		flags |= ACE_F_PUBLISH;
11222 	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
11223 		flags |= ACE_F_PERMANENT;
11224 	if (NCE_MYADDR(ncec))
11225 		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
11226 	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
11227 		flags |= ACE_F_UNVERIFIED;
11228 	if (ncec->ncec_flags & NCE_F_AUTHORITY)
11229 		flags |= ACE_F_AUTHORITY;
11230 	if (ncec->ncec_flags & NCE_F_DELAYED)
11231 		flags |= ACE_F_DELAYED;
11232 	return (flags);
11233 }
11234 
11235 /*
11236  * ncec_walk routine to create ipNetToMediaEntryTable
11237  */
11238 static int
11239 ip_snmp_get2_v4_media(ncec_t *ncec, iproutedata_t *ird)
11240 {
11241 	ill_t				*ill;
11242 	mib2_ipNetToMediaEntry_t	ntme;
11243 	const char			*name = "unknown";
11244 	ipaddr_t			ncec_addr;
11245 
11246 	ill = ncec->ncec_ill;
11247 	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
11248 	    ill->ill_net_type == IRE_LOOPBACK)
11249 		return (0);
11250 
11251 	/* We report all IPMP groups on ncec_ill which is normally the upper. */
11252 	name = ill->ill_name;
11253 	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
11254 	if (NCE_MYADDR(ncec)) {
11255 		ntme.ipNetToMediaType = 4;
11256 	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
11257 		ntme.ipNetToMediaType = 1;
11258 	} else {
11259 		ntme.ipNetToMediaType = 3;
11260 	}
11261 	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
11262 	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
11263 	    ntme.ipNetToMediaIfIndex.o_length);
11264 
11265 	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
11266 	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));
11267 
11268 	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
11269 	ncec_addr = INADDR_BROADCAST;
11270 	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
11271 	    sizeof (ncec_addr));
11272 	/*
11273 	 * map all the flags to the ACE counterpart.
11274 	 */
11275 	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);
11276 
11277 	ntme.ipNetToMediaPhysAddress.o_length =
11278 	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);
11279 
11280 	if (!NCE_ISREACHABLE(ncec))
11281 		ntme.ipNetToMediaPhysAddress.o_length = 0;
11282 	else {
11283 		if (ncec->ncec_lladdr != NULL) {
11284 			bcopy(ncec->ncec_lladdr,
11285 			    ntme.ipNetToMediaPhysAddress.o_bytes,
11286 			    ntme.ipNetToMediaPhysAddress.o_length);
11287 		}
11288 	}
11289 
11290 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
11291 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
11292 		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
11293 		    (uint_t)sizeof (ntme)));
11294 	}
11295 	return (0);
11296 }
11297 
11298 /*
11299  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
11300  */
11301 /* ARGSUSED */
11302 int
11303 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
11304 {
11305 	switch (level) {
11306 	case MIB2_IP:
11307 	case MIB2_ICMP:
11308 		switch (name) {
11309 		default:
11310 			break;
11311 		}
11312 		return (1);
11313 	default:
11314 		return (1);
11315 	}
11316 }
11317 
11318 /*
11319  * When there exists both a 64- and 32-bit counter of a particular type
11320  * (i.e., InReceives), only the 64-bit counters are added.
11321  */
11322 void
11323 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
11324 {
11325 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
11326 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
11327 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
11328 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
11329 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
11330 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
11331 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
11332 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
11333 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
11334 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
11335 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
11336 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
11337 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
11338 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
11339 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
11340 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
11341 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
11342 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
11343 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
11344 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
11345 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
11346 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
11347 	    o2->ipIfStatsInWrongIPVersion);
11348 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
11349 	    o2->ipIfStatsInWrongIPVersion);
11350 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
11351 	    o2->ipIfStatsOutSwitchIPVersion);
11352 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
11353 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
11354 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
11355 	    o2->ipIfStatsHCInForwDatagrams);
11356 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
11357 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
11358 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
11359 	    o2->ipIfStatsHCOutForwDatagrams);
11360 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
11361 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
11362 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
11363 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
11364 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
11365 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
11366 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
11367 	    o2->ipIfStatsHCOutMcastOctets);
11368 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
11369 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
11370 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
11371 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
11372 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
11373 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
11374 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
11375 }
11376 
11377 void
11378 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
11379 {
11380 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
11381 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
11382 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
11383 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
11384 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
11385 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
11386 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
11387 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
11388 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
11389 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
11390 	    o2->ipv6IfIcmpInRouterSolicits);
11391 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
11392 	    o2->ipv6IfIcmpInRouterAdvertisements);
11393 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
11394 	    o2->ipv6IfIcmpInNeighborSolicits);
11395 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
11396 	    o2->ipv6IfIcmpInNeighborAdvertisements);
11397 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
11398 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
11399 	    o2->ipv6IfIcmpInGroupMembQueries);
11400 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
11401 	    o2->ipv6IfIcmpInGroupMembResponses);
11402 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
11403 	    o2->ipv6IfIcmpInGroupMembReductions);
11404 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
11405 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
11406 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
11407 	    o2->ipv6IfIcmpOutDestUnreachs);
11408 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
11409 	    o2->ipv6IfIcmpOutAdminProhibs);
11410 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
11411 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
11412 	    o2->ipv6IfIcmpOutParmProblems);
11413 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
11414 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
11415 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
11416 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
11417 	    o2->ipv6IfIcmpOutRouterSolicits);
11418 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
11419 	    o2->ipv6IfIcmpOutRouterAdvertisements);
11420 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
11421 	    o2->ipv6IfIcmpOutNeighborSolicits);
11422 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
11423 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
11424 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
11425 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
11426 	    o2->ipv6IfIcmpOutGroupMembQueries);
11427 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
11428 	    o2->ipv6IfIcmpOutGroupMembResponses);
11429 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
11430 	    o2->ipv6IfIcmpOutGroupMembReductions);
11431 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
11432 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
11433 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
11434 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
11435 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
11436 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
11437 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
11438 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
11439 	    o2->ipv6IfIcmpInGroupMembTotal);
11440 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
11441 	    o2->ipv6IfIcmpInGroupMembBadQueries);
11442 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
11443 	    o2->ipv6IfIcmpInGroupMembBadReports);
11444 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
11445 	    o2->ipv6IfIcmpInGroupMembOurReports);
11446 }
11447 
11448 /*
11449  * Called before the options are updated to check if this packet will
11450  * be source routed from here.
11451  * This routine assumes that the options are well formed i.e. that they
11452  * have already been checked.
11453  */
11454 boolean_t
11455 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
11456 {
11457 	ipoptp_t	opts;
11458 	uchar_t		*opt;
11459 	uint8_t		optval;
11460 	uint8_t		optlen;
11461 	ipaddr_t	dst;
11462 
11463 	if (IS_SIMPLE_IPH(ipha)) {
11464 		ip2dbg(("not source routed\n"));
11465 		return (B_FALSE);
11466 	}
11467 	dst = ipha->ipha_dst;
11468 	for (optval = ipoptp_first(&opts, ipha);
11469 	    optval != IPOPT_EOL;
11470 	    optval = ipoptp_next(&opts)) {
11471 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11472 		opt = opts.ipoptp_cur;
11473 		optlen = opts.ipoptp_len;
11474 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
11475 		    optval, optlen));
11476 		switch (optval) {
11477 			uint32_t off;
11478 		case IPOPT_SSRR:
11479 		case IPOPT_LSRR:
11480 			/*
11481 			 * If dst is one of our addresses and there are some
11482 			 * entries left in the source route return (true).
11483 			 */
11484 			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
11485 				ip2dbg(("ip_source_routed: not next"
11486 				    " source route 0x%x\n",
11487 				    ntohl(dst)));
11488 				return (B_FALSE);
11489 			}
11490 			off = opt[IPOPT_OFFSET];
11491 			off--;
11492 			if (optlen < IP_ADDR_LEN ||
11493 			    off > optlen - IP_ADDR_LEN) {
11494 				/* End of source route */
11495 				ip1dbg(("ip_source_routed: end of SR\n"));
11496 				return (B_FALSE);
11497 			}
11498 			return (B_TRUE);
11499 		}
11500 	}
11501 	ip2dbg(("not source routed\n"));
11502 	return (B_FALSE);
11503 }
11504 
11505 /*
11506  * ip_unbind is called by the transports to remove a conn from
11507  * the fanout table.
11508  */
11509 void
11510 ip_unbind(conn_t *connp)
11511 {
11512 
11513 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
11514 
11515 	if (is_system_labeled() && connp->conn_anon_port) {
11516 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
11517 		    connp->conn_mlp_type, connp->conn_proto,
11518 		    ntohs(connp->conn_lport), B_FALSE);
11519 		connp->conn_anon_port = 0;
11520 	}
11521 	connp->conn_mlp_type = mlptSingle;
11522 
11523 	ipcl_hash_remove(connp);
11524 }
11525 
11526 /*
11527  * Used for deciding the MSS size for the upper layer. Thus
11528  * we need to check the outbound policy values in the conn.
11529  */
11530 int
11531 conn_ipsec_length(conn_t *connp)
11532 {
11533 	ipsec_latch_t *ipl;
11534 
11535 	ipl = connp->conn_latch;
11536 	if (ipl == NULL)
11537 		return (0);
11538 
11539 	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
11540 		return (0);
11541 
11542 	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
11543 }
11544 
11545 /*
11546  * Returns an estimate of the IPsec headers size. This is used if
11547  * we don't want to call into IPsec to get the exact size.
11548  */
11549 int
11550 ipsec_out_extra_length(ip_xmit_attr_t *ixa)
11551 {
11552 	ipsec_action_t *a;
11553 
11554 	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
11555 		return (0);
11556 
11557 	a = ixa->ixa_ipsec_action;
11558 	if (a == NULL) {
11559 		ASSERT(ixa->ixa_ipsec_policy != NULL);
11560 		a = ixa->ixa_ipsec_policy->ipsp_act;
11561 	}
11562 	ASSERT(a != NULL);
11563 
11564 	return (a->ipa_ovhd);
11565 }
11566 
11567 /*
11568  * If there are any source route options, return the true final
11569  * destination. Otherwise, return the destination.
11570  */
11571 ipaddr_t
11572 ip_get_dst(ipha_t *ipha)
11573 {
11574 	ipoptp_t	opts;
11575 	uchar_t		*opt;
11576 	uint8_t		optval;
11577 	uint8_t		optlen;
11578 	ipaddr_t	dst;
11579 	uint32_t off;
11580 
11581 	dst = ipha->ipha_dst;
11582 
11583 	if (IS_SIMPLE_IPH(ipha))
11584 		return (dst);
11585 
11586 	for (optval = ipoptp_first(&opts, ipha);
11587 	    optval != IPOPT_EOL;
11588 	    optval = ipoptp_next(&opts)) {
11589 		opt = opts.ipoptp_cur;
11590 		optlen = opts.ipoptp_len;
11591 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11592 		switch (optval) {
11593 		case IPOPT_SSRR:
11594 		case IPOPT_LSRR:
11595 			off = opt[IPOPT_OFFSET];
11596 			/*
11597 			 * If one of the conditions is true, it means
11598 			 * end of options and dst already has the right
11599 			 * value.
11600 			 */
11601 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
11602 				off = optlen - IP_ADDR_LEN;
11603 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
11604 			}
11605 			return (dst);
11606 		default:
11607 			break;
11608 		}
11609 	}
11610 
11611 	return (dst);
11612 }
11613 
11614 /*
11615  * Outbound IP fragmentation routine.
11616  * Assumes the caller has checked whether or not fragmentation should
11617  * be allowed. Here we copy the DF bit from the header to all the generated
11618  * fragments.
11619  */
11620 int
11621 ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
11622     uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
11623     zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
11624 {
11625 	int		i1;
11626 	int		hdr_len;
11627 	mblk_t		*hdr_mp;
11628 	ipha_t		*ipha;
11629 	int		ip_data_end;
11630 	int		len;
11631 	mblk_t		*mp = mp_orig;
11632 	int		offset;
11633 	ill_t		*ill = nce->nce_ill;
11634 	ip_stack_t	*ipst = ill->ill_ipst;
11635 	mblk_t		*carve_mp;
11636 	uint32_t	frag_flag;
11637 	uint_t		priority = mp->b_band;
11638 	int		error = 0;
11639 
11640 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);
11641 
11642 	if (pkt_len != msgdsize(mp)) {
11643 		ip0dbg(("Packet length mismatch: %d, %ld\n",
11644 		    pkt_len, msgdsize(mp)));
11645 		freemsg(mp);
11646 		return (EINVAL);
11647 	}
11648 
11649 	if (max_frag == 0) {
11650 		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
11651 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11652 		ip_drop_output("FragFails: zero max_frag", mp, ill);
11653 		freemsg(mp);
11654 		return (EINVAL);
11655 	}
11656 
11657 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
11658 	ipha = (ipha_t *)mp->b_rptr;
11659 	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
11660 	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;
11661 
11662 	/*
11663 	 * Establish the starting offset.  May not be zero if we are fragging
11664 	 * a fragment that is being forwarded.
11665 	 */
11666 	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;
11667 
11668 	/* TODO why is this test needed? */
11669 	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
11670 		/* TODO: notify ulp somehow */
11671 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11672 		ip_drop_output("FragFails: bad starting offset", mp, ill);
11673 		freemsg(mp);
11674 		return (EINVAL);
11675 	}
11676 
11677 	hdr_len = IPH_HDR_LENGTH(ipha);
11678 	ipha->ipha_hdr_checksum = 0;
11679 
11680 	/*
11681 	 * Establish the number of bytes maximum per frag, after putting
11682 	 * in the header.
11683 	 */
11684 	len = (max_frag - hdr_len) & ~7;
11685 
11686 	/* Get a copy of the header for the trailing frags */
11687 	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
11688 	    mp);
11689 	if (hdr_mp == NULL) {
11690 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11691 		ip_drop_output("FragFails: no hdr_mp", mp, ill);
11692 		freemsg(mp);
11693 		return (ENOBUFS);
11694 	}
11695 
11696 	/* Store the starting offset, with the MoreFrags flag. */
11697 	i1 = offset | IPH_MF | frag_flag;
11698 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
11699 
11700 	/* Establish the ending byte offset, based on the starting offset. */
11701 	offset <<= 3;
11702 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
11703 
11704 	/* Store the length of the first fragment in the IP header. */
11705 	i1 = len + hdr_len;
11706 	ASSERT(i1 <= IP_MAXPACKET);
11707 	ipha->ipha_length = htons((uint16_t)i1);
11708 
11709 	/*
11710 	 * Compute the IP header checksum for the first frag.  We have to
11711 	 * watch out that we stop at the end of the header.
11712 	 */
11713 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11714 
11715 	/*
11716 	 * Now carve off the first frag.  Note that this will include the
11717 	 * original IP header.
11718 	 */
11719 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
11720 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11721 		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
11722 		freeb(hdr_mp);
11723 		freemsg(mp_orig);
11724 		return (ENOBUFS);
11725 	}
11726 
11727 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11728 
11729 	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
11730 	    ixa_cookie);
11731 	if (error != 0 && error != EWOULDBLOCK) {
11732 		/* No point in sending the other fragments */
11733 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11734 		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
11735 		freeb(hdr_mp);
11736 		freemsg(mp_orig);
11737 		return (error);
11738 	}
11739 
11740 	/* No need to redo state machine in loop */
11741 	ixaflags &= ~IXAF_REACH_CONF;
11742 
11743 	/* Advance the offset to the second frag starting point. */
11744 	offset += len;
11745 	/*
11746 	 * Update hdr_len from the copied header - there might be less options
11747 	 * in the later fragments.
11748 	 */
11749 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
11750 	/* Loop until done. */
11751 	for (;;) {
11752 		uint16_t	offset_and_flags;
11753 		uint16_t	ip_len;
11754 
11755 		if (ip_data_end - offset > len) {
11756 			/*
11757 			 * Carve off the appropriate amount from the original
11758 			 * datagram.
11759 			 */
11760 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11761 				mp = NULL;
11762 				break;
11763 			}
11764 			/*
11765 			 * More frags after this one.  Get another copy
11766 			 * of the header.
11767 			 */
11768 			if (carve_mp->b_datap->db_ref == 1 &&
11769 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11770 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11771 				/* Inline IP header */
11772 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11773 				    hdr_mp->b_rptr;
11774 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11775 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11776 				mp = carve_mp;
11777 			} else {
11778 				if (!(mp = copyb(hdr_mp))) {
11779 					freemsg(carve_mp);
11780 					break;
11781 				}
11782 				/* Get priority marking, if any. */
11783 				mp->b_band = priority;
11784 				mp->b_cont = carve_mp;
11785 			}
11786 			ipha = (ipha_t *)mp->b_rptr;
11787 			offset_and_flags = IPH_MF;
11788 		} else {
11789 			/*
11790 			 * Last frag.  Consume the header. Set len to
11791 			 * the length of this last piece.
11792 			 */
11793 			len = ip_data_end - offset;
11794 
11795 			/*
11796 			 * Carve off the appropriate amount from the original
11797 			 * datagram.
11798 			 */
11799 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
11800 				mp = NULL;
11801 				break;
11802 			}
11803 			if (carve_mp->b_datap->db_ref == 1 &&
11804 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
11805 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
11806 				/* Inline IP header */
11807 				carve_mp->b_rptr -= hdr_mp->b_wptr -
11808 				    hdr_mp->b_rptr;
11809 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
11810 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
11811 				mp = carve_mp;
11812 				freeb(hdr_mp);
11813 				hdr_mp = mp;
11814 			} else {
11815 				mp = hdr_mp;
11816 				/* Get priority marking, if any. */
11817 				mp->b_band = priority;
11818 				mp->b_cont = carve_mp;
11819 			}
11820 			ipha = (ipha_t *)mp->b_rptr;
11821 			/* A frag of a frag might have IPH_MF non-zero */
11822 			offset_and_flags =
11823 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
11824 			    IPH_MF;
11825 		}
11826 		offset_and_flags |= (uint16_t)(offset >> 3);
11827 		offset_and_flags |= (uint16_t)frag_flag;
11828 		/* Store the offset and flags in the IP header. */
11829 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
11830 
11831 		/* Store the length in the IP header. */
11832 		ip_len = (uint16_t)(len + hdr_len);
11833 		ipha->ipha_length = htons(ip_len);
11834 
11835 		/*
11836 		 * Set the IP header checksum.	Note that mp is just
11837 		 * the header, so this is easy to pass to ip_csum.
11838 		 */
11839 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
11840 
11841 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);
11842 
11843 		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
11844 		    nolzid, ixa_cookie);
11845 		/* All done if we just consumed the hdr_mp. */
11846 		if (mp == hdr_mp) {
11847 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
11848 			return (error);
11849 		}
11850 		if (error != 0 && error != EWOULDBLOCK) {
11851 			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
11852 			    mblk_t *, hdr_mp);
11853 			/* No point in sending the other fragments */
11854 			break;
11855 		}
11856 
11857 		/* Otherwise, advance and loop. */
11858 		offset += len;
11859 	}
11860 	/* Clean up following allocation failure. */
11861 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
11862 	ip_drop_output("FragFails: loop ended", NULL, ill);
11863 	if (mp != hdr_mp)
11864 		freeb(hdr_mp);
11865 	if (mp != mp_orig)
11866 		freemsg(mp_orig);
11867 	return (error);
11868 }
11869 
11870 /*
11871  * Copy the header plus those options which have the copy bit set
11872  */
11873 static mblk_t *
11874 ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
11875     mblk_t *src)
11876 {
11877 	mblk_t	*mp;
11878 	uchar_t	*up;
11879 
11880 	/*
11881 	 * Quick check if we need to look for options without the copy bit
11882 	 * set
11883 	 */
11884 	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
11885 	if (!mp)
11886 		return (mp);
11887 	mp->b_rptr += ipst->ips_ip_wroff_extra;
11888 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
11889 		bcopy(rptr, mp->b_rptr, hdr_len);
11890 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
11891 		return (mp);
11892 	}
11893 	up  = mp->b_rptr;
11894 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
11895 	up += IP_SIMPLE_HDR_LENGTH;
11896 	rptr += IP_SIMPLE_HDR_LENGTH;
11897 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
11898 	while (hdr_len > 0) {
11899 		uint32_t optval;
11900 		uint32_t optlen;
11901 
11902 		optval = *rptr;
11903 		if (optval == IPOPT_EOL)
11904 			break;
11905 		if (optval == IPOPT_NOP)
11906 			optlen = 1;
11907 		else
11908 			optlen = rptr[1];
11909 		if (optval & IPOPT_COPY) {
11910 			bcopy(rptr, up, optlen);
11911 			up += optlen;
11912 		}
11913 		rptr += optlen;
11914 		hdr_len -= optlen;
11915 	}
11916 	/*
11917 	 * Make sure that we drop an even number of words by filling
11918 	 * with EOL to the next word boundary.
11919 	 */
11920 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
11921 	    hdr_len & 0x3; hdr_len++)
11922 		*up++ = IPOPT_EOL;
11923 	mp->b_wptr = up;
11924 	/* Update header length */
11925 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
11926 	return (mp);
11927 }
11928 
11929 /*
11930  * Update any source route, record route, or timestamp options when
11931  * sending a packet back to ourselves.
11932  * Check that we are at end of strict source route.
11933  * The options have been sanity checked by ip_output_options().
11934  */
11935 void
11936 ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
11937 {
11938 	ipoptp_t	opts;
11939 	uchar_t		*opt;
11940 	uint8_t		optval;
11941 	uint8_t		optlen;
11942 	ipaddr_t	dst;
11943 	uint32_t	ts;
11944 	timestruc_t	now;
11945 
11946 	for (optval = ipoptp_first(&opts, ipha);
11947 	    optval != IPOPT_EOL;
11948 	    optval = ipoptp_next(&opts)) {
11949 		opt = opts.ipoptp_cur;
11950 		optlen = opts.ipoptp_len;
11951 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
11952 		switch (optval) {
11953 			uint32_t off;
11954 		case IPOPT_SSRR:
11955 		case IPOPT_LSRR:
11956 			off = opt[IPOPT_OFFSET];
11957 			off--;
11958 			if (optlen < IP_ADDR_LEN ||
11959 			    off > optlen - IP_ADDR_LEN) {
11960 				/* End of source route */
11961 				break;
11962 			}
11963 			/*
11964 			 * This will only happen if two consecutive entries
11965 			 * in the source route contains our address or if
11966 			 * it is a packet with a loose source route which
11967 			 * reaches us before consuming the whole source route
11968 			 */
11969 
11970 			if (optval == IPOPT_SSRR) {
11971 				return;
11972 			}
11973 			/*
11974 			 * Hack: instead of dropping the packet truncate the
11975 			 * source route to what has been used by filling the
11976 			 * rest with IPOPT_NOP.
11977 			 */
11978 			opt[IPOPT_OLEN] = (uint8_t)off;
11979 			while (off < optlen) {
11980 				opt[off++] = IPOPT_NOP;
11981 			}
11982 			break;
11983 		case IPOPT_RR:
11984 			off = opt[IPOPT_OFFSET];
11985 			off--;
11986 			if (optlen < IP_ADDR_LEN ||
11987 			    off > optlen - IP_ADDR_LEN) {
11988 				/* No more room - ignore */
11989 				ip1dbg((
11990 				    "ip_output_local_options: end of RR\n"));
11991 				break;
11992 			}
11993 			dst = htonl(INADDR_LOOPBACK);
11994 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
11995 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
11996 			break;
11997 		case IPOPT_TS:
11998 			/* Insert timestamp if there is romm */
11999 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12000 			case IPOPT_TS_TSONLY:
12001 				off = IPOPT_TS_TIMELEN;
12002 				break;
12003 			case IPOPT_TS_PRESPEC:
12004 			case IPOPT_TS_PRESPEC_RFC791:
12005 				/* Verify that the address matched */
12006 				off = opt[IPOPT_OFFSET] - 1;
12007 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
12008 				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
12009 					/* Not for us */
12010 					break;
12011 				}
12012 				/* FALLTHROUGH */
12013 			case IPOPT_TS_TSANDADDR:
12014 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
12015 				break;
12016 			default:
12017 				/*
12018 				 * ip_*put_options should have already
12019 				 * dropped this packet.
12020 				 */
12021 				cmn_err(CE_PANIC, "ip_output_local_options: "
12022 				    "unknown IT - bug in ip_output_options?\n");
12023 				return;	/* Keep "lint" happy */
12024 			}
12025 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
12026 				/* Increase overflow counter */
12027 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
12028 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
12029 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
12030 				    (off << 4);
12031 				break;
12032 			}
12033 			off = opt[IPOPT_OFFSET] - 1;
12034 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
12035 			case IPOPT_TS_PRESPEC:
12036 			case IPOPT_TS_PRESPEC_RFC791:
12037 			case IPOPT_TS_TSANDADDR:
12038 				dst = htonl(INADDR_LOOPBACK);
12039 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
12040 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
12041 				/* FALLTHROUGH */
12042 			case IPOPT_TS_TSONLY:
12043 				off = opt[IPOPT_OFFSET] - 1;
12044 				/* Compute # of milliseconds since midnight */
12045 				gethrestime(&now);
12046 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
12047 				    NSEC2MSEC(now.tv_nsec);
12048 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
12049 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
12050 				break;
12051 			}
12052 			break;
12053 		}
12054 	}
12055 }
12056 
12057 /*
12058  * Prepend an M_DATA fastpath header, and if none present prepend a
12059  * DL_UNITDATA_REQ. Frees the mblk on failure.
12060  *
12061  * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
12062  * If there is a change to them, the nce will be deleted (condemned) and
12063  * a new nce_t will be created when packets are sent. Thus we need no locks
12064  * to access those fields.
12065  *
12066  * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
12067  * we place b_band in dl_priority.dl_max.
12068  */
12069 static mblk_t *
12070 ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
12071 {
12072 	uint_t	hlen;
12073 	mblk_t *mp1;
12074 	uint_t	priority;
12075 	uchar_t *rptr;
12076 
12077 	rptr = mp->b_rptr;
12078 
12079 	ASSERT(DB_TYPE(mp) == M_DATA);
12080 	priority = mp->b_band;
12081 
12082 	ASSERT(nce != NULL);
12083 	if ((mp1 = nce->nce_fp_mp) != NULL) {
12084 		hlen = MBLKL(mp1);
12085 		/*
12086 		 * Check if we have enough room to prepend fastpath
12087 		 * header
12088 		 */
12089 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
12090 			rptr -= hlen;
12091 			bcopy(mp1->b_rptr, rptr, hlen);
12092 			/*
12093 			 * Set the b_rptr to the start of the link layer
12094 			 * header
12095 			 */
12096 			mp->b_rptr = rptr;
12097 			return (mp);
12098 		}
12099 		mp1 = copyb(mp1);
12100 		if (mp1 == NULL) {
12101 			ill_t *ill = nce->nce_ill;
12102 
12103 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12104 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12105 			freemsg(mp);
12106 			return (NULL);
12107 		}
12108 		mp1->b_band = priority;
12109 		mp1->b_cont = mp;
12110 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
12111 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
12112 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
12113 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
12114 		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
12115 		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
12116 		/*
12117 		 * XXX disable ICK_VALID and compute checksum
12118 		 * here; can happen if nce_fp_mp changes and
12119 		 * it can't be copied now due to insufficient
12120 		 * space. (unlikely, fp mp can change, but it
12121 		 * does not increase in length)
12122 		 */
12123 		return (mp1);
12124 	}
12125 	mp1 = copyb(nce->nce_dlur_mp);
12126 
12127 	if (mp1 == NULL) {
12128 		ill_t *ill = nce->nce_ill;
12129 
12130 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12131 		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12132 		freemsg(mp);
12133 		return (NULL);
12134 	}
12135 	mp1->b_cont = mp;
12136 	if (priority != 0) {
12137 		mp1->b_band = priority;
12138 		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
12139 		    priority;
12140 	}
12141 	return (mp1);
12142 }
12143 
12144 /*
12145  * Finish the outbound IPsec processing. This function is called from
12146  * ipsec_out_process() if the IPsec packet was processed
12147  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12148  * asynchronously.
12149  *
12150  * This is common to IPv4 and IPv6.
12151  */
12152 int
12153 ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
12154 {
12155 	iaflags_t	ixaflags = ixa->ixa_flags;
12156 	uint_t		pktlen;
12157 
12158 
12159 	/* AH/ESP don't update ixa_pktlen when they modify the packet */
12160 	if (ixaflags & IXAF_IS_IPV4) {
12161 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12162 
12163 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12164 		pktlen = ntohs(ipha->ipha_length);
12165 	} else {
12166 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12167 
12168 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12169 		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12170 	}
12171 
12172 	/*
12173 	 * We release any hard reference on the SAs here to make
12174 	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
12175 	 * on the SAs.
12176 	 * If in the future we want the hard latching of the SAs in the
12177 	 * ip_xmit_attr_t then we should remove this.
12178 	 */
12179 	if (ixa->ixa_ipsec_esp_sa != NULL) {
12180 		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12181 		ixa->ixa_ipsec_esp_sa = NULL;
12182 	}
12183 	if (ixa->ixa_ipsec_ah_sa != NULL) {
12184 		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12185 		ixa->ixa_ipsec_ah_sa = NULL;
12186 	}
12187 
12188 	/* Do we need to fragment? */
12189 	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
12190 	    pktlen > ixa->ixa_fragsize) {
12191 		if (ixaflags & IXAF_IS_IPV4) {
12192 			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
12193 			/*
12194 			 * We check for the DF case in ipsec_out_process
12195 			 * hence this only handles the non-DF case.
12196 			 */
12197 			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
12198 			    pktlen, ixa->ixa_fragsize,
12199 			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12200 			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
12201 			    &ixa->ixa_cookie));
12202 		} else {
12203 			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
12204 			if (mp == NULL) {
12205 				/* MIB and ip_drop_output already done */
12206 				return (ENOMEM);
12207 			}
12208 			pktlen += sizeof (ip6_frag_t);
12209 			if (pktlen > ixa->ixa_fragsize) {
12210 				return (ip_fragment_v6(mp, ixa->ixa_nce,
12211 				    ixa->ixa_flags, pktlen,
12212 				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
12213 				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
12214 				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
12215 			}
12216 		}
12217 	}
12218 	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
12219 	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
12220 	    ixa->ixa_no_loop_zoneid, NULL));
12221 }
12222 
12223 /*
12224  * Finish the inbound IPsec processing. This function is called from
12225  * ipsec_out_process() if the IPsec packet was processed
12226  * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
12227  * asynchronously.
12228  *
12229  * This is common to IPv4 and IPv6.
12230  */
12231 void
12232 ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
12233 {
12234 	iaflags_t	iraflags = ira->ira_flags;
12235 
12236 	/* Length might have changed */
12237 	if (iraflags & IRAF_IS_IPV4) {
12238 		ipha_t		*ipha = (ipha_t *)mp->b_rptr;
12239 
12240 		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
12241 		ira->ira_pktlen = ntohs(ipha->ipha_length);
12242 		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
12243 		ira->ira_protocol = ipha->ipha_protocol;
12244 
12245 		ip_fanout_v4(mp, ipha, ira);
12246 	} else {
12247 		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
12248 		uint8_t		*nexthdrp;
12249 
12250 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
12251 		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
12252 		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
12253 		    &nexthdrp)) {
12254 			/* Malformed packet */
12255 			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
12256 			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
12257 			freemsg(mp);
12258 			return;
12259 		}
12260 		ira->ira_protocol = *nexthdrp;
12261 		ip_fanout_v6(mp, ip6h, ira);
12262 	}
12263 }
12264 
12265 /*
12266  * Select which AH & ESP SA's to use (if any) for the outbound packet.
12267  *
12268  * If this function returns B_TRUE, the requested SA's have been filled
12269  * into the ixa_ipsec_*_sa pointers.
12270  *
12271  * If the function returns B_FALSE, the packet has been "consumed", most
12272  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
12273  *
12274  * The SA references created by the protocol-specific "select"
12275  * function will be released in ip_output_post_ipsec.
12276  */
12277 static boolean_t
12278 ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
12279 {
12280 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
12281 	ipsec_policy_t *pp;
12282 	ipsec_action_t *ap;
12283 
12284 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12285 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12286 	    (ixa->ixa_ipsec_action != NULL));
12287 
12288 	ap = ixa->ixa_ipsec_action;
12289 	if (ap == NULL) {
12290 		pp = ixa->ixa_ipsec_policy;
12291 		ASSERT(pp != NULL);
12292 		ap = pp->ipsp_act;
12293 		ASSERT(ap != NULL);
12294 	}
12295 
12296 	/*
12297 	 * We have an action.  now, let's select SA's.
12298 	 * A side effect of setting ixa_ipsec_*_sa is that it will
12299 	 * be cached in the conn_t.
12300 	 */
12301 	if (ap->ipa_want_esp) {
12302 		if (ixa->ixa_ipsec_esp_sa == NULL) {
12303 			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
12304 			    IPPROTO_ESP);
12305 		}
12306 		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
12307 	}
12308 
12309 	if (ap->ipa_want_ah) {
12310 		if (ixa->ixa_ipsec_ah_sa == NULL) {
12311 			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
12312 			    IPPROTO_AH);
12313 		}
12314 		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
12315 		/*
12316 		 * The ESP and AH processing order needs to be preserved
12317 		 * when both protocols are required (ESP should be applied
12318 		 * before AH for an outbound packet). Force an ESP ACQUIRE
12319 		 * when both ESP and AH are required, and an AH ACQUIRE
12320 		 * is needed.
12321 		 */
12322 		if (ap->ipa_want_esp && need_ah_acquire)
12323 			need_esp_acquire = B_TRUE;
12324 	}
12325 
12326 	/*
12327 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
12328 	 * Release SAs that got referenced, but will not be used until we
12329 	 * acquire _all_ of the SAs we need.
12330 	 */
12331 	if (need_ah_acquire || need_esp_acquire) {
12332 		if (ixa->ixa_ipsec_ah_sa != NULL) {
12333 			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
12334 			ixa->ixa_ipsec_ah_sa = NULL;
12335 		}
12336 		if (ixa->ixa_ipsec_esp_sa != NULL) {
12337 			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
12338 			ixa->ixa_ipsec_esp_sa = NULL;
12339 		}
12340 
12341 		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
12342 		return (B_FALSE);
12343 	}
12344 
12345 	return (B_TRUE);
12346 }
12347 
12348 /*
12349  * Handle IPsec output processing.
12350  * This function is only entered once for a given packet.
12351  * We try to do things synchronously, but if we need to have user-level
12352  * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
12353  * will be completed
12354  *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
12355  *  - when asynchronous ESP is done it will do AH
12356  *
12357  * In all cases we come back in ip_output_post_ipsec() to fragment and
12358  * send out the packet.
12359  */
12360 int
12361 ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
12362 {
12363 	ill_t		*ill = ixa->ixa_nce->nce_ill;
12364 	ip_stack_t	*ipst = ixa->ixa_ipst;
12365 	ipsec_stack_t	*ipss;
12366 	ipsec_policy_t	*pp;
12367 	ipsec_action_t	*ap;
12368 
12369 	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
12370 
12371 	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
12372 	    (ixa->ixa_ipsec_action != NULL));
12373 
12374 	ipss = ipst->ips_netstack->netstack_ipsec;
12375 	if (!ipsec_loaded(ipss)) {
12376 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12377 		ip_drop_packet(mp, B_TRUE, ill,
12378 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
12379 		    &ipss->ipsec_dropper);
12380 		return (ENOTSUP);
12381 	}
12382 
12383 	ap = ixa->ixa_ipsec_action;
12384 	if (ap == NULL) {
12385 		pp = ixa->ixa_ipsec_policy;
12386 		ASSERT(pp != NULL);
12387 		ap = pp->ipsp_act;
12388 		ASSERT(ap != NULL);
12389 	}
12390 
12391 	/* Handle explicit drop action and bypass. */
12392 	switch (ap->ipa_act.ipa_type) {
12393 	case IPSEC_ACT_DISCARD:
12394 	case IPSEC_ACT_REJECT:
12395 		ip_drop_packet(mp, B_FALSE, ill,
12396 		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
12397 		return (EHOSTUNREACH);	/* IPsec policy failure */
12398 	case IPSEC_ACT_BYPASS:
12399 		return (ip_output_post_ipsec(mp, ixa));
12400 	}
12401 
12402 	/*
12403 	 * The order of processing is first insert a IP header if needed.
12404 	 * Then insert the ESP header and then the AH header.
12405 	 */
12406 	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
12407 		/*
12408 		 * First get the outer IP header before sending
12409 		 * it to ESP.
12410 		 */
12411 		ipha_t *oipha, *iipha;
12412 		mblk_t *outer_mp, *inner_mp;
12413 
12414 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
12415 			(void) mi_strlog(ill->ill_rq, 0,
12416 			    SL_ERROR|SL_TRACE|SL_CONSOLE,
12417 			    "ipsec_out_process: "
12418 			    "Self-Encapsulation failed: Out of memory\n");
12419 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
12420 			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
12421 			freemsg(mp);
12422 			return (ENOBUFS);
12423 		}
12424 		inner_mp = mp;
12425 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
12426 		oipha = (ipha_t *)outer_mp->b_rptr;
12427 		iipha = (ipha_t *)inner_mp->b_rptr;
12428 		*oipha = *iipha;
12429 		outer_mp->b_wptr += sizeof (ipha_t);
12430 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
12431 		    sizeof (ipha_t));
12432 		oipha->ipha_protocol = IPPROTO_ENCAP;
12433 		oipha->ipha_version_and_hdr_length =
12434 		    IP_SIMPLE_HDR_VERSION;
12435 		oipha->ipha_hdr_checksum = 0;
12436 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
12437 		outer_mp->b_cont = inner_mp;
12438 		mp = outer_mp;
12439 
12440 		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
12441 	}
12442 
12443 	/* If we need to wait for a SA then we can't return any errno */
12444 	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
12445 	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
12446 	    !ipsec_out_select_sa(mp, ixa))
12447 		return (0);
12448 
12449 	/*
12450 	 * By now, we know what SA's to use.  Toss over to ESP & AH
12451 	 * to do the heavy lifting.
12452 	 */
12453 	if (ap->ipa_want_esp) {
12454 		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);
12455 
12456 		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
12457 		if (mp == NULL) {
12458 			/*
12459 			 * Either it failed or is pending. In the former case
12460 			 * ipIfStatsInDiscards was increased.
12461 			 */
12462 			return (0);
12463 		}
12464 	}
12465 
12466 	if (ap->ipa_want_ah) {
12467 		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);
12468 
12469 		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
12470 		if (mp == NULL) {
12471 			/*
12472 			 * Either it failed or is pending. In the former case
12473 			 * ipIfStatsInDiscards was increased.
12474 			 */
12475 			return (0);
12476 		}
12477 	}
12478 	/*
12479 	 * We are done with IPsec processing. Send it over
12480 	 * the wire.
12481 	 */
12482 	return (ip_output_post_ipsec(mp, ixa));
12483 }
12484 
12485 /*
12486  * ioctls that go through a down/up sequence may need to wait for the down
12487  * to complete. This involves waiting for the ire and ipif refcnts to go down
12488  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
12489  */
12490 /* ARGSUSED */
12491 void
12492 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
12493 {
12494 	struct iocblk *iocp;
12495 	mblk_t *mp1;
12496 	ip_ioctl_cmd_t *ipip;
12497 	int err;
12498 	sin_t	*sin;
12499 	struct lifreq *lifr;
12500 	struct ifreq *ifr;
12501 
12502 	iocp = (struct iocblk *)mp->b_rptr;
12503 	ASSERT(ipsq != NULL);
12504 	/* Existence of mp1 verified in ip_wput_nondata */
12505 	mp1 = mp->b_cont->b_cont;
12506 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12507 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
12508 		/*
12509 		 * Special case where ipx_current_ipif is not set:
12510 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
12511 		 * We are here as were not able to complete the operation in
12512 		 * ipif_set_values because we could not become exclusive on
12513 		 * the new ipsq.
12514 		 */
12515 		ill_t *ill = q->q_ptr;
12516 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
12517 	}
12518 	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);
12519 
12520 	if (ipip->ipi_cmd_type == IF_CMD) {
12521 		/* This a old style SIOC[GS]IF* command */
12522 		ifr = (struct ifreq *)mp1->b_rptr;
12523 		sin = (sin_t *)&ifr->ifr_addr;
12524 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
12525 		/* This a new style SIOC[GS]LIF* command */
12526 		lifr = (struct lifreq *)mp1->b_rptr;
12527 		sin = (sin_t *)&lifr->lifr_addr;
12528 	} else {
12529 		sin = NULL;
12530 	}
12531 
12532 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
12533 	    q, mp, ipip, mp1->b_rptr);
12534 
12535 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
12536 	    int, ipip->ipi_cmd,
12537 	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
12538 	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);
12539 
12540 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12541 }
12542 
12543 /*
12544  * ioctl processing
12545  *
12546  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
12547  * the ioctl command in the ioctl tables, determines the copyin data size
12548  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
12549  *
12550  * ioctl processing then continues when the M_IOCDATA makes its way down to
12551  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
12552  * associated 'conn' is refheld till the end of the ioctl and the general
12553  * ioctl processing function ip_process_ioctl() is called to extract the
12554  * arguments and process the ioctl.  To simplify extraction, ioctl commands
12555  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
12556  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
12557  * is used to extract the ioctl's arguments.
12558  *
12559  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
12560  * so goes thru the serialization primitive ipsq_try_enter. Then the
12561  * appropriate function to handle the ioctl is called based on the entry in
12562  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
12563  * which also refreleases the 'conn' that was refheld at the start of the
12564  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
12565  *
12566  * Many exclusive ioctls go thru an internal down up sequence as part of
12567  * the operation. For example an attempt to change the IP address of an
12568  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
12569  * does all the cleanup such as deleting all ires that use this address.
12570  * Then we need to wait till all references to the interface go away.
12571  */
12572 void
12573 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
12574 {
12575 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
12576 	ip_ioctl_cmd_t *ipip = arg;
12577 	ip_extract_func_t *extract_funcp;
12578 	cmd_info_t ci;
12579 	int err;
12580 	boolean_t entered_ipsq = B_FALSE;
12581 
12582 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
12583 
12584 	if (ipip == NULL)
12585 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12586 
12587 	/*
12588 	 * SIOCLIFADDIF needs to go thru a special path since the
12589 	 * ill may not exist yet. This happens in the case of lo0
12590 	 * which is created using this ioctl.
12591 	 */
12592 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
12593 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
12594 		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
12595 		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12596 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12597 		return;
12598 	}
12599 
12600 	ci.ci_ipif = NULL;
12601 	switch (ipip->ipi_cmd_type) {
12602 	case MISC_CMD:
12603 	case MSFILT_CMD:
12604 		/*
12605 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
12606 		 */
12607 		if (ipip->ipi_cmd == IF_UNITSEL) {
12608 			/* ioctl comes down the ill */
12609 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
12610 			ipif_refhold(ci.ci_ipif);
12611 		}
12612 		err = 0;
12613 		ci.ci_sin = NULL;
12614 		ci.ci_sin6 = NULL;
12615 		ci.ci_lifr = NULL;
12616 		extract_funcp = NULL;
12617 		break;
12618 
12619 	case IF_CMD:
12620 	case LIF_CMD:
12621 		extract_funcp = ip_extract_lifreq;
12622 		break;
12623 
12624 	case ARP_CMD:
12625 	case XARP_CMD:
12626 		extract_funcp = ip_extract_arpreq;
12627 		break;
12628 
12629 	default:
12630 		ASSERT(0);
12631 	}
12632 
12633 	if (extract_funcp != NULL) {
12634 		err = (*extract_funcp)(q, mp, ipip, &ci);
12635 		if (err != 0) {
12636 			DTRACE_PROBE4(ipif__ioctl,
12637 			    char *, "ip_process_ioctl finish err",
12638 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12639 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12640 			return;
12641 		}
12642 
12643 		/*
12644 		 * All of the extraction functions return a refheld ipif.
12645 		 */
12646 		ASSERT(ci.ci_ipif != NULL);
12647 	}
12648 
12649 	if (!(ipip->ipi_flags & IPI_WR)) {
12650 		/*
12651 		 * A return value of EINPROGRESS means the ioctl is
12652 		 * either queued and waiting for some reason or has
12653 		 * already completed.
12654 		 */
12655 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
12656 		    ci.ci_lifr);
12657 		if (ci.ci_ipif != NULL) {
12658 			DTRACE_PROBE4(ipif__ioctl,
12659 			    char *, "ip_process_ioctl finish RD",
12660 			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
12661 			    ipif_t *, ci.ci_ipif);
12662 			ipif_refrele(ci.ci_ipif);
12663 		} else {
12664 			DTRACE_PROBE4(ipif__ioctl,
12665 			    char *, "ip_process_ioctl finish RD",
12666 			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
12667 		}
12668 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
12669 		return;
12670 	}
12671 
12672 	ASSERT(ci.ci_ipif != NULL);
12673 
12674 	/*
12675 	 * If ipsq is non-NULL, we are already being called exclusively
12676 	 */
12677 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
12678 	if (ipsq == NULL) {
12679 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
12680 		    NEW_OP, B_TRUE);
12681 		if (ipsq == NULL) {
12682 			ipif_refrele(ci.ci_ipif);
12683 			return;
12684 		}
12685 		entered_ipsq = B_TRUE;
12686 	}
12687 	/*
12688 	 * Release the ipif so that ipif_down and friends that wait for
12689 	 * references to go away are not misled about the current ipif_refcnt
12690 	 * values. We are writer so we can access the ipif even after releasing
12691 	 * the ipif.
12692 	 */
12693 	ipif_refrele(ci.ci_ipif);
12694 
12695 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
12696 
12697 	/*
12698 	 * A return value of EINPROGRESS means the ioctl is
12699 	 * either queued and waiting for some reason or has
12700 	 * already completed.
12701 	 */
12702 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
12703 
12704 	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
12705 	    int, ipip->ipi_cmd,
12706 	    ill_t *, ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill,
12707 	    ipif_t *, ci.ci_ipif);
12708 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
12709 
12710 	if (entered_ipsq)
12711 		ipsq_exit(ipsq);
12712 }
12713 
12714 /*
12715  * Complete the ioctl. Typically ioctls use the mi package and need to
12716  * do mi_copyout/mi_copy_done.
12717  */
12718 void
12719 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
12720 {
12721 	conn_t	*connp = NULL;
12722 
12723 	if (err == EINPROGRESS)
12724 		return;
12725 
12726 	if (CONN_Q(q)) {
12727 		connp = Q_TO_CONN(q);
12728 		ASSERT(connp->conn_ref >= 2);
12729 	}
12730 
12731 	switch (mode) {
12732 	case COPYOUT:
12733 		if (err == 0)
12734 			mi_copyout(q, mp);
12735 		else
12736 			mi_copy_done(q, mp, err);
12737 		break;
12738 
12739 	case NO_COPYOUT:
12740 		mi_copy_done(q, mp, err);
12741 		break;
12742 
12743 	default:
12744 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
12745 		break;
12746 	}
12747 
12748 	/*
12749 	 * The conn refhold and ioctlref placed on the conn at the start of the
12750 	 * ioctl are released here.
12751 	 */
12752 	if (connp != NULL) {
12753 		CONN_DEC_IOCTLREF(connp);
12754 		CONN_OPER_PENDING_DONE(connp);
12755 	}
12756 
12757 	if (ipsq != NULL)
12758 		ipsq_current_finish(ipsq);
12759 }
12760 
12761 /* Handles all non data messages */
12762 void
12763 ip_wput_nondata(queue_t *q, mblk_t *mp)
12764 {
12765 	mblk_t		*mp1;
12766 	struct iocblk	*iocp;
12767 	ip_ioctl_cmd_t	*ipip;
12768 	conn_t		*connp;
12769 	cred_t		*cr;
12770 	char		*proto_str;
12771 
12772 	if (CONN_Q(q))
12773 		connp = Q_TO_CONN(q);
12774 	else
12775 		connp = NULL;
12776 
12777 	switch (DB_TYPE(mp)) {
12778 	case M_IOCTL:
12779 		/*
12780 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
12781 		 * will arrange to copy in associated control structures.
12782 		 */
12783 		ip_sioctl_copyin_setup(q, mp);
12784 		return;
12785 	case M_IOCDATA:
12786 		/*
12787 		 * Ensure that this is associated with one of our trans-
12788 		 * parent ioctls.  If it's not ours, discard it if we're
12789 		 * running as a driver, or pass it on if we're a module.
12790 		 */
12791 		iocp = (struct iocblk *)mp->b_rptr;
12792 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
12793 		if (ipip == NULL) {
12794 			if (q->q_next == NULL) {
12795 				goto nak;
12796 			} else {
12797 				putnext(q, mp);
12798 			}
12799 			return;
12800 		}
12801 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
12802 			/*
12803 			 * The ioctl is one we recognise, but is not consumed
12804 			 * by IP as a module and we are a module, so we drop
12805 			 */
12806 			goto nak;
12807 		}
12808 
12809 		/* IOCTL continuation following copyin or copyout. */
12810 		if (mi_copy_state(q, mp, NULL) == -1) {
12811 			/*
12812 			 * The copy operation failed.  mi_copy_state already
12813 			 * cleaned up, so we're out of here.
12814 			 */
12815 			return;
12816 		}
12817 		/*
12818 		 * If we just completed a copy in, we become writer and
12819 		 * continue processing in ip_sioctl_copyin_done.  If it
12820 		 * was a copy out, we call mi_copyout again.  If there is
12821 		 * nothing more to copy out, it will complete the IOCTL.
12822 		 */
12823 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
12824 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
12825 				mi_copy_done(q, mp, EPROTO);
12826 				return;
12827 			}
12828 			/*
12829 			 * Check for cases that need more copying.  A return
12830 			 * value of 0 means a second copyin has been started,
12831 			 * so we return; a return value of 1 means no more
12832 			 * copying is needed, so we continue.
12833 			 */
12834 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
12835 			    MI_COPY_COUNT(mp) == 1) {
12836 				if (ip_copyin_msfilter(q, mp) == 0)
12837 					return;
12838 			}
12839 			/*
12840 			 * Refhold the conn, till the ioctl completes. This is
12841 			 * needed in case the ioctl ends up in the pending mp
12842 			 * list. Every mp in the ipx_pending_mp list must have
12843 			 * a refhold on the conn to resume processing. The
12844 			 * refhold is released when the ioctl completes
12845 			 * (whether normally or abnormally). An ioctlref is also
12846 			 * placed on the conn to prevent TCP from removing the
12847 			 * queue needed to send the ioctl reply back.
12848 			 * In all cases ip_ioctl_finish is called to finish
12849 			 * the ioctl and release the refholds.
12850 			 */
12851 			if (connp != NULL) {
12852 				/* This is not a reentry */
12853 				CONN_INC_REF(connp);
12854 				CONN_INC_IOCTLREF(connp);
12855 			} else {
12856 				if (!(ipip->ipi_flags & IPI_MODOK)) {
12857 					mi_copy_done(q, mp, EINVAL);
12858 					return;
12859 				}
12860 			}
12861 
12862 			ip_process_ioctl(NULL, q, mp, ipip);
12863 
12864 		} else {
12865 			mi_copyout(q, mp);
12866 		}
12867 		return;
12868 
12869 	case M_IOCNAK:
12870 		/*
12871 		 * The only way we could get here is if a resolver didn't like
12872 		 * an IOCTL we sent it.	 This shouldn't happen.
12873 		 */
12874 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
12875 		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
12876 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
12877 		freemsg(mp);
12878 		return;
12879 	case M_IOCACK:
12880 		/* /dev/ip shouldn't see this */
12881 		goto nak;
12882 	case M_FLUSH:
12883 		if (*mp->b_rptr & FLUSHW)
12884 			flushq(q, FLUSHALL);
12885 		if (q->q_next) {
12886 			putnext(q, mp);
12887 			return;
12888 		}
12889 		if (*mp->b_rptr & FLUSHR) {
12890 			*mp->b_rptr &= ~FLUSHW;
12891 			qreply(q, mp);
12892 			return;
12893 		}
12894 		freemsg(mp);
12895 		return;
12896 	case M_CTL:
12897 		break;
12898 	case M_PROTO:
12899 	case M_PCPROTO:
12900 		/*
12901 		 * The only PROTO messages we expect are SNMP-related.
12902 		 */
12903 		switch (((union T_primitives *)mp->b_rptr)->type) {
12904 		case T_SVR4_OPTMGMT_REQ:
12905 			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
12906 			    "flags %x\n",
12907 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
12908 
12909 			if (connp == NULL) {
12910 				proto_str = "T_SVR4_OPTMGMT_REQ";
12911 				goto protonak;
12912 			}
12913 
12914 			/*
12915 			 * All Solaris components should pass a db_credp
12916 			 * for this TPI message, hence we ASSERT.
12917 			 * But in case there is some other M_PROTO that looks
12918 			 * like a TPI message sent by some other kernel
12919 			 * component, we check and return an error.
12920 			 */
12921 			cr = msg_getcred(mp, NULL);
12922 			ASSERT(cr != NULL);
12923 			if (cr == NULL) {
12924 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
12925 				if (mp != NULL)
12926 					qreply(q, mp);
12927 				return;
12928 			}
12929 
12930 			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
12931 				proto_str = "Bad SNMPCOM request?";
12932 				goto protonak;
12933 			}
12934 			return;
12935 		default:
12936 			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
12937 			    (int)*(uint_t *)mp->b_rptr));
12938 			freemsg(mp);
12939 			return;
12940 		}
12941 	default:
12942 		break;
12943 	}
12944 	if (q->q_next) {
12945 		putnext(q, mp);
12946 	} else
12947 		freemsg(mp);
12948 	return;
12949 
12950 nak:
12951 	iocp->ioc_error = EINVAL;
12952 	mp->b_datap->db_type = M_IOCNAK;
12953 	iocp->ioc_count = 0;
12954 	qreply(q, mp);
12955 	return;
12956 
12957 protonak:
12958 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
12959 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
12960 		qreply(q, mp);
12961 }
12962 
12963 /*
12964  * Process IP options in an outbound packet.  Verify that the nexthop in a
12965  * strict source route is onlink.
12966  * Returns non-zero if something fails in which case an ICMP error has been
12967  * sent and mp freed.
12968  *
12969  * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
12970  */
12971 int
12972 ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
12973 {
12974 	ipoptp_t	opts;
12975 	uchar_t		*opt;
12976 	uint8_t		optval;
12977 	uint8_t		optlen;
12978 	ipaddr_t	dst;
12979 	intptr_t	code = 0;
12980 	ire_t		*ire;
12981 	ip_stack_t	*ipst = ixa->ixa_ipst;
12982 	ip_recv_attr_t	iras;
12983 
12984 	ip2dbg(("ip_output_options\n"));
12985 
12986 	dst = ipha->ipha_dst;
12987 	for (optval = ipoptp_first(&opts, ipha);
12988 	    optval != IPOPT_EOL;
12989 	    optval = ipoptp_next(&opts)) {
12990 		opt = opts.ipoptp_cur;
12991 		optlen = opts.ipoptp_len;
12992 		ip2dbg(("ip_output_options: opt %d, len %d\n",
12993 		    optval, optlen));
12994 		switch (optval) {
12995 			uint32_t off;
12996 		case IPOPT_SSRR:
12997 		case IPOPT_LSRR:
12998 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
12999 				ip1dbg((
13000 				    "ip_output_options: bad option offset\n"));
13001 				code = (char *)&opt[IPOPT_OLEN] -
13002 				    (char *)ipha;
13003 				goto param_prob;
13004 			}
13005 			off = opt[IPOPT_OFFSET];
13006 			ip1dbg(("ip_output_options: next hop 0x%x\n",
13007 			    ntohl(dst)));
13008 			/*
13009 			 * For strict: verify that dst is directly
13010 			 * reachable.
13011 			 */
13012 			if (optval == IPOPT_SSRR) {
13013 				ire = ire_ftable_lookup_v4(dst, 0, 0,
13014 				    IRE_INTERFACE, NULL, ALL_ZONES,
13015 				    ixa->ixa_tsl,
13016 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
13017 				    NULL);
13018 				if (ire == NULL) {
13019 					ip1dbg(("ip_output_options: SSRR not"
13020 					    " directly reachable: 0x%x\n",
13021 					    ntohl(dst)));
13022 					goto bad_src_route;
13023 				}
13024 				ire_refrele(ire);
13025 			}
13026 			break;
13027 		case IPOPT_RR:
13028 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13029 				ip1dbg((
13030 				    "ip_output_options: bad option offset\n"));
13031 				code = (char *)&opt[IPOPT_OLEN] -
13032 				    (char *)ipha;
13033 				goto param_prob;
13034 			}
13035 			break;
13036 		case IPOPT_TS:
13037 			/*
13038 			 * Verify that length >=5 and that there is either
13039 			 * room for another timestamp or that the overflow
13040 			 * counter is not maxed out.
13041 			 */
13042 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
13043 			if (optlen < IPOPT_MINLEN_IT) {
13044 				goto param_prob;
13045 			}
13046 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
13047 				ip1dbg((
13048 				    "ip_output_options: bad option offset\n"));
13049 				code = (char *)&opt[IPOPT_OFFSET] -
13050 				    (char *)ipha;
13051 				goto param_prob;
13052 			}
13053 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
13054 			case IPOPT_TS_TSONLY:
13055 				off = IPOPT_TS_TIMELEN;
13056 				break;
13057 			case IPOPT_TS_TSANDADDR:
13058 			case IPOPT_TS_PRESPEC:
13059 			case IPOPT_TS_PRESPEC_RFC791:
13060 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
13061 				break;
13062 			default:
13063 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
13064 				    (char *)ipha;
13065 				goto param_prob;
13066 			}
13067 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
13068 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
13069 				/*
13070 				 * No room and the overflow counter is 15
13071 				 * already.
13072 				 */
13073 				goto param_prob;
13074 			}
13075 			break;
13076 		}
13077 	}
13078 
13079 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
13080 		return (0);
13081 
13082 	ip1dbg(("ip_output_options: error processing IP options."));
13083 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
13084 
13085 param_prob:
13086 	bzero(&iras, sizeof (iras));
13087 	iras.ira_ill = iras.ira_rill = ill;
13088 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13089 	iras.ira_rifindex = iras.ira_ruifindex;
13090 	iras.ira_flags = IRAF_IS_IPV4;
13091 
13092 	ip_drop_output("ip_output_options", mp, ill);
13093 	icmp_param_problem(mp, (uint8_t)code, &iras);
13094 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13095 	return (-1);
13096 
13097 bad_src_route:
13098 	bzero(&iras, sizeof (iras));
13099 	iras.ira_ill = iras.ira_rill = ill;
13100 	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
13101 	iras.ira_rifindex = iras.ira_ruifindex;
13102 	iras.ira_flags = IRAF_IS_IPV4;
13103 
13104 	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
13105 	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
13106 	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
13107 	return (-1);
13108 }
13109 
13110 /*
13111  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
13112  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
13113  * thru /etc/system.
13114  */
13115 #define	CONN_MAXDRAINCNT	64
13116 
13117 static void
13118 conn_drain_init(ip_stack_t *ipst)
13119 {
13120 	int i, j;
13121 	idl_tx_list_t *itl_tx;
13122 
13123 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
13124 
13125 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
13126 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
13127 		/*
13128 		 * Default value of the number of drainers is the
13129 		 * number of cpus, subject to maximum of 8 drainers.
13130 		 */
13131 		if (boot_max_ncpus != -1)
13132 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
13133 		else
13134 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
13135 	}
13136 
13137 	ipst->ips_idl_tx_list =
13138 	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
13139 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13140 		itl_tx =  &ipst->ips_idl_tx_list[i];
13141 		itl_tx->txl_drain_list =
13142 		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
13143 		    sizeof (idl_t), KM_SLEEP);
13144 		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
13145 		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
13146 			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
13147 			    MUTEX_DEFAULT, NULL);
13148 			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
13149 		}
13150 	}
13151 }
13152 
13153 static void
13154 conn_drain_fini(ip_stack_t *ipst)
13155 {
13156 	int i;
13157 	idl_tx_list_t *itl_tx;
13158 
13159 	for (i = 0; i < TX_FANOUT_SIZE; i++) {
13160 		itl_tx =  &ipst->ips_idl_tx_list[i];
13161 		kmem_free(itl_tx->txl_drain_list,
13162 		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
13163 	}
13164 	kmem_free(ipst->ips_idl_tx_list,
13165 	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
13166 	ipst->ips_idl_tx_list = NULL;
13167 }
13168 
13169 /*
13170  * Flow control has blocked us from proceeding.  Insert the given conn in one
13171  * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
13172  * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
13173  * will call conn_walk_drain().  See the flow control notes at the top of this
13174  * file for more details.
13175  */
13176 void
13177 conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
13178 {
13179 	idl_t	*idl = tx_list->txl_drain_list;
13180 	uint_t	index;
13181 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
13182 
13183 	mutex_enter(&connp->conn_lock);
13184 	if (connp->conn_state_flags & CONN_CLOSING) {
13185 		/*
13186 		 * The conn is closing as a result of which CONN_CLOSING
13187 		 * is set. Return.
13188 		 */
13189 		mutex_exit(&connp->conn_lock);
13190 		return;
13191 	} else if (connp->conn_idl == NULL) {
13192 		/*
13193 		 * Assign the next drain list round robin. We dont' use
13194 		 * a lock, and thus it may not be strictly round robin.
13195 		 * Atomicity of load/stores is enough to make sure that
13196 		 * conn_drain_list_index is always within bounds.
13197 		 */
13198 		index = tx_list->txl_drain_index;
13199 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
13200 		connp->conn_idl = &tx_list->txl_drain_list[index];
13201 		index++;
13202 		if (index == ipst->ips_conn_drain_list_cnt)
13203 			index = 0;
13204 		tx_list->txl_drain_index = index;
13205 	} else {
13206 		ASSERT(connp->conn_idl->idl_itl == tx_list);
13207 	}
13208 	mutex_exit(&connp->conn_lock);
13209 
13210 	idl = connp->conn_idl;
13211 	mutex_enter(&idl->idl_lock);
13212 	if ((connp->conn_drain_prev != NULL) ||
13213 	    (connp->conn_state_flags & CONN_CLOSING)) {
13214 		/*
13215 		 * The conn is either already in the drain list or closing.
13216 		 * (We needed to check for CONN_CLOSING again since close can
13217 		 * sneak in between dropping conn_lock and acquiring idl_lock.)
13218 		 */
13219 		mutex_exit(&idl->idl_lock);
13220 		return;
13221 	}
13222 
13223 	/*
13224 	 * The conn is not in the drain list. Insert it at the
13225 	 * tail of the drain list. The drain list is circular
13226 	 * and doubly linked. idl_conn points to the 1st element
13227 	 * in the list.
13228 	 */
13229 	if (idl->idl_conn == NULL) {
13230 		idl->idl_conn = connp;
13231 		connp->conn_drain_next = connp;
13232 		connp->conn_drain_prev = connp;
13233 	} else {
13234 		conn_t *head = idl->idl_conn;
13235 
13236 		connp->conn_drain_next = head;
13237 		connp->conn_drain_prev = head->conn_drain_prev;
13238 		head->conn_drain_prev->conn_drain_next = connp;
13239 		head->conn_drain_prev = connp;
13240 	}
13241 	/*
13242 	 * For non streams based sockets assert flow control.
13243 	 */
13244 	conn_setqfull(connp, NULL);
13245 	mutex_exit(&idl->idl_lock);
13246 }
13247 
13248 static void
13249 conn_drain_remove(conn_t *connp)
13250 {
13251 	idl_t *idl = connp->conn_idl;
13252 
13253 	if (idl != NULL) {
13254 		/*
13255 		 * Remove ourself from the drain list.
13256 		 */
13257 		if (connp->conn_drain_next == connp) {
13258 			/* Singleton in the list */
13259 			ASSERT(connp->conn_drain_prev == connp);
13260 			idl->idl_conn = NULL;
13261 		} else {
13262 			connp->conn_drain_prev->conn_drain_next =
13263 			    connp->conn_drain_next;
13264 			connp->conn_drain_next->conn_drain_prev =
13265 			    connp->conn_drain_prev;
13266 			if (idl->idl_conn == connp)
13267 				idl->idl_conn = connp->conn_drain_next;
13268 		}
13269 
13270 		/*
13271 		 * NOTE: because conn_idl is associated with a specific drain
13272 		 * list which in turn is tied to the index the TX ring
13273 		 * (txl_cookie) hashes to, and because the TX ring can change
13274 		 * over the lifetime of the conn_t, we must clear conn_idl so
13275 		 * a subsequent conn_drain_insert() will set conn_idl again
13276 		 * based on the latest txl_cookie.
13277 		 */
13278 		connp->conn_idl = NULL;
13279 	}
13280 	connp->conn_drain_next = NULL;
13281 	connp->conn_drain_prev = NULL;
13282 
13283 	conn_clrqfull(connp, NULL);
13284 	/*
13285 	 * For streams based sockets open up flow control.
13286 	 */
13287 	if (!IPCL_IS_NONSTR(connp))
13288 		enableok(connp->conn_wq);
13289 }
13290 
13291 /*
13292  * This conn is closing, and we are called from ip_close. OR
13293  * this conn is draining because flow-control on the ill has been relieved.
13294  *
13295  * We must also need to remove conn's on this idl from the list, and also
13296  * inform the sockfs upcalls about the change in flow-control.
13297  */
13298 static void
13299 conn_drain(conn_t *connp, boolean_t closing)
13300 {
13301 	idl_t *idl;
13302 	conn_t *next_connp;
13303 
13304 	/*
13305 	 * connp->conn_idl is stable at this point, and no lock is needed
13306 	 * to check it. If we are called from ip_close, close has already
13307 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
13308 	 * called us only because conn_idl is non-null. If we are called thru
13309 	 * service, conn_idl could be null, but it cannot change because
13310 	 * service is single-threaded per queue, and there cannot be another
13311 	 * instance of service trying to call conn_drain_insert on this conn
13312 	 * now.
13313 	 */
13314 	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);
13315 
13316 	/*
13317 	 * If the conn doesn't exist or is not on a drain list, bail.
13318 	 */
13319 	if (connp == NULL || connp->conn_idl == NULL ||
13320 	    connp->conn_drain_prev == NULL) {
13321 		return;
13322 	}
13323 
13324 	idl = connp->conn_idl;
13325 	ASSERT(MUTEX_HELD(&idl->idl_lock));
13326 
13327 	if (!closing) {
13328 		next_connp = connp->conn_drain_next;
13329 		while (next_connp != connp) {
13330 			conn_t *delconnp = next_connp;
13331 
13332 			next_connp = next_connp->conn_drain_next;
13333 			conn_drain_remove(delconnp);
13334 		}
13335 		ASSERT(connp->conn_drain_next == idl->idl_conn);
13336 	}
13337 	conn_drain_remove(connp);
13338 }
13339 
13340 /*
13341  * Write service routine. Shared perimeter entry point.
13342  * The device queue's messages has fallen below the low water mark and STREAMS
13343  * has backenabled the ill_wq. Send sockfs notification about flow-control on
13344  * each waiting conn.
13345  */
13346 void
13347 ip_wsrv(queue_t *q)
13348 {
13349 	ill_t	*ill;
13350 
13351 	ill = (ill_t *)q->q_ptr;
13352 	if (ill->ill_state_flags == 0) {
13353 		ip_stack_t *ipst = ill->ill_ipst;
13354 
13355 		/*
13356 		 * The device flow control has opened up.
13357 		 * Walk through conn drain lists and qenable the
13358 		 * first conn in each list. This makes sense only
13359 		 * if the stream is fully plumbed and setup.
13360 		 * Hence the ill_state_flags check above.
13361 		 */
13362 		ip1dbg(("ip_wsrv: walking\n"));
13363 		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
13364 		enableok(ill->ill_wq);
13365 	}
13366 }
13367 
13368 /*
13369  * Callback to disable flow control in IP.
13370  *
13371  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
13372  * is enabled.
13373  *
13374  * When MAC_TX() is not able to send any more packets, dld sets its queue
13375  * to QFULL and enable the STREAMS flow control. Later, when the underlying
13376  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
13377  * function and wakes up corresponding mac worker threads, which in turn
13378  * calls this callback function, and disables flow control.
13379  */
13380 void
13381 ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
13382 {
13383 	ill_t *ill = (ill_t *)arg;
13384 	ip_stack_t *ipst = ill->ill_ipst;
13385 	idl_tx_list_t *idl_txl;
13386 
13387 	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
13388 	mutex_enter(&idl_txl->txl_lock);
13389 	/* add code to to set a flag to indicate idl_txl is enabled */
13390 	conn_walk_drain(ipst, idl_txl);
13391 	mutex_exit(&idl_txl->txl_lock);
13392 }
13393 
13394 /*
13395  * Flow control has been relieved and STREAMS has backenabled us; drain
13396  * all the conn lists on `tx_list'.
13397  */
13398 static void
13399 conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
13400 {
13401 	int i;
13402 	idl_t *idl;
13403 
13404 	IP_STAT(ipst, ip_conn_walk_drain);
13405 
13406 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
13407 		idl = &tx_list->txl_drain_list[i];
13408 		mutex_enter(&idl->idl_lock);
13409 		conn_drain(idl->idl_conn, B_FALSE);
13410 		mutex_exit(&idl->idl_lock);
13411 	}
13412 }
13413 
13414 /*
13415  * Determine if the ill and multicast aspects of that packets
13416  * "matches" the conn.
13417  */
13418 boolean_t
13419 conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
13420 {
13421 	ill_t		*ill = ira->ira_rill;
13422 	zoneid_t	zoneid = ira->ira_zoneid;
13423 	uint_t		in_ifindex;
13424 	ipaddr_t	dst, src;
13425 
13426 	dst = ipha->ipha_dst;
13427 	src = ipha->ipha_src;
13428 
13429 	/*
13430 	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
13431 	 * unicast, broadcast and multicast reception to
13432 	 * conn_incoming_ifindex.
13433 	 * conn_wantpacket is called for unicast, broadcast and
13434 	 * multicast packets.
13435 	 */
13436 	in_ifindex = connp->conn_incoming_ifindex;
13437 
13438 	/* mpathd can bind to the under IPMP interface, which we allow */
13439 	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
13440 		if (!IS_UNDER_IPMP(ill))
13441 			return (B_FALSE);
13442 
13443 		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
13444 			return (B_FALSE);
13445 	}
13446 
13447 	if (!IPCL_ZONE_MATCH(connp, zoneid))
13448 		return (B_FALSE);
13449 
13450 	if (!(ira->ira_flags & IRAF_MULTICAST))
13451 		return (B_TRUE);
13452 
13453 	if (connp->conn_multi_router) {
13454 		/* multicast packet and multicast router socket: send up */
13455 		return (B_TRUE);
13456 	}
13457 
13458 	if (ipha->ipha_protocol == IPPROTO_PIM ||
13459 	    ipha->ipha_protocol == IPPROTO_RSVP)
13460 		return (B_TRUE);
13461 
13462 	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
13463 }
13464 
13465 void
13466 conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
13467 {
13468 	if (IPCL_IS_NONSTR(connp)) {
13469 		(*connp->conn_upcalls->su_txq_full)
13470 		    (connp->conn_upper_handle, B_TRUE);
13471 		if (flow_stopped != NULL)
13472 			*flow_stopped = B_TRUE;
13473 	} else {
13474 		queue_t *q = connp->conn_wq;
13475 
13476 		ASSERT(q != NULL);
13477 		if (!(q->q_flag & QFULL)) {
13478 			mutex_enter(QLOCK(q));
13479 			if (!(q->q_flag & QFULL)) {
13480 				/* still need to set QFULL */
13481 				q->q_flag |= QFULL;
13482 				/* set flow_stopped to true under QLOCK */
13483 				if (flow_stopped != NULL)
13484 					*flow_stopped = B_TRUE;
13485 				mutex_exit(QLOCK(q));
13486 			} else {
13487 				/* flow_stopped is left unchanged */
13488 				mutex_exit(QLOCK(q));
13489 			}
13490 		}
13491 	}
13492 }
13493 
13494 void
13495 conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
13496 {
13497 	if (IPCL_IS_NONSTR(connp)) {
13498 		(*connp->conn_upcalls->su_txq_full)
13499 		    (connp->conn_upper_handle, B_FALSE);
13500 		if (flow_stopped != NULL)
13501 			*flow_stopped = B_FALSE;
13502 	} else {
13503 		queue_t *q = connp->conn_wq;
13504 
13505 		ASSERT(q != NULL);
13506 		if (q->q_flag & QFULL) {
13507 			mutex_enter(QLOCK(q));
13508 			if (q->q_flag & QFULL) {
13509 				q->q_flag &= ~QFULL;
13510 				/* set flow_stopped to false under QLOCK */
13511 				if (flow_stopped != NULL)
13512 					*flow_stopped = B_FALSE;
13513 				mutex_exit(QLOCK(q));
13514 				if (q->q_flag & QWANTW)
13515 					qbackenable(q, 0);
13516 			} else {
13517 				/* flow_stopped is left unchanged */
13518 				mutex_exit(QLOCK(q));
13519 			}
13520 		}
13521 	}
13522 
13523 	mutex_enter(&connp->conn_lock);
13524 	connp->conn_blocked = B_FALSE;
13525 	mutex_exit(&connp->conn_lock);
13526 }
13527 
13528 /*
13529  * Return the length in bytes of the IPv4 headers (base header, label, and
13530  * other IP options) that will be needed based on the
13531  * ip_pkt_t structure passed by the caller.
13532  *
13533  * The returned length does not include the length of the upper level
13534  * protocol (ULP) header.
13535  * The caller needs to check that the length doesn't exceed the max for IPv4.
13536  */
13537 int
13538 ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
13539 {
13540 	int len;
13541 
13542 	len = IP_SIMPLE_HDR_LENGTH;
13543 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13544 		ASSERT(ipp->ipp_label_len_v4 != 0);
13545 		/* We need to round up here */
13546 		len += (ipp->ipp_label_len_v4 + 3) & ~3;
13547 	}
13548 
13549 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13550 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13551 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13552 		len += ipp->ipp_ipv4_options_len;
13553 	}
13554 	return (len);
13555 }
13556 
13557 /*
13558  * All-purpose routine to build an IPv4 header with options based
13559  * on the abstract ip_pkt_t.
13560  *
13561  * The caller has to set the source and destination address as well as
13562  * ipha_length. The caller has to massage any source route and compensate
13563  * for the ULP pseudo-header checksum due to the source route.
13564  */
13565 void
13566 ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
13567     uint8_t protocol)
13568 {
13569 	ipha_t	*ipha = (ipha_t *)buf;
13570 	uint8_t *cp;
13571 
13572 	/* Initialize IPv4 header */
13573 	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
13574 	ipha->ipha_length = 0;	/* Caller will set later */
13575 	ipha->ipha_ident = 0;
13576 	ipha->ipha_fragment_offset_and_flags = 0;
13577 	ipha->ipha_ttl = ipp->ipp_unicast_hops;
13578 	ipha->ipha_protocol = protocol;
13579 	ipha->ipha_hdr_checksum = 0;
13580 
13581 	if ((ipp->ipp_fields & IPPF_ADDR) &&
13582 	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
13583 		ipha->ipha_src = ipp->ipp_addr_v4;
13584 
13585 	cp = (uint8_t *)&ipha[1];
13586 	if (ipp->ipp_fields & IPPF_LABEL_V4) {
13587 		ASSERT(ipp->ipp_label_len_v4 != 0);
13588 		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
13589 		cp += ipp->ipp_label_len_v4;
13590 		/* We need to round up here */
13591 		while ((uintptr_t)cp & 0x3) {
13592 			*cp++ = IPOPT_NOP;
13593 		}
13594 	}
13595 
13596 	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
13597 		ASSERT(ipp->ipp_ipv4_options_len != 0);
13598 		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
13599 		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
13600 		cp += ipp->ipp_ipv4_options_len;
13601 	}
13602 	ipha->ipha_version_and_hdr_length =
13603 	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);
13604 
13605 	ASSERT((int)(cp - buf) == buf_len);
13606 }
13607 
13608 /* Allocate the private structure */
13609 static int
13610 ip_priv_alloc(void **bufp)
13611 {
13612 	void	*buf;
13613 
13614 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
13615 		return (ENOMEM);
13616 
13617 	*bufp = buf;
13618 	return (0);
13619 }
13620 
13621 /* Function to delete the private structure */
13622 void
13623 ip_priv_free(void *buf)
13624 {
13625 	ASSERT(buf != NULL);
13626 	kmem_free(buf, sizeof (ip_priv_t));
13627 }
13628 
13629 /*
13630  * The entry point for IPPF processing.
13631  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
13632  * routine just returns.
13633  *
13634  * When called, ip_process generates an ipp_packet_t structure
13635  * which holds the state information for this packet and invokes the
13636  * the classifier (via ipp_packet_process). The classification, depending on
13637  * configured filters, results in a list of actions for this packet. Invoking
13638  * an action may cause the packet to be dropped, in which case we return NULL.
13639  * proc indicates the callout position for
13640  * this packet and ill is the interface this packet arrived on or will leave
13641  * on (inbound and outbound resp.).
13642  *
13643  * We do the processing on the rill (mapped to the upper if ipmp), but MIB
13644  * on the ill corrsponding to the destination IP address.
13645  */
13646 mblk_t *
13647 ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
13648 {
13649 	ip_priv_t	*priv;
13650 	ipp_action_id_t	aid;
13651 	int		rc = 0;
13652 	ipp_packet_t	*pp;
13653 
13654 	/* If the classifier is not loaded, return  */
13655 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
13656 		return (mp);
13657 	}
13658 
13659 	ASSERT(mp != NULL);
13660 
13661 	/* Allocate the packet structure */
13662 	rc = ipp_packet_alloc(&pp, "ip", aid);
13663 	if (rc != 0)
13664 		goto drop;
13665 
13666 	/* Allocate the private structure */
13667 	rc = ip_priv_alloc((void **)&priv);
13668 	if (rc != 0) {
13669 		ipp_packet_free(pp);
13670 		goto drop;
13671 	}
13672 	priv->proc = proc;
13673 	priv->ill_index = ill_get_upper_ifindex(rill);
13674 
13675 	ipp_packet_set_private(pp, priv, ip_priv_free);
13676 	ipp_packet_set_data(pp, mp);
13677 
13678 	/* Invoke the classifier */
13679 	rc = ipp_packet_process(&pp);
13680 	if (pp != NULL) {
13681 		mp = ipp_packet_get_data(pp);
13682 		ipp_packet_free(pp);
13683 		if (rc != 0)
13684 			goto drop;
13685 		return (mp);
13686 	} else {
13687 		/* No mp to trace in ip_drop_input/ip_drop_output  */
13688 		mp = NULL;
13689 	}
13690 drop:
13691 	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
13692 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13693 		ip_drop_input("ip_process", mp, ill);
13694 	} else {
13695 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
13696 		ip_drop_output("ip_process", mp, ill);
13697 	}
13698 	freemsg(mp);
13699 	return (NULL);
13700 }
13701 
13702 /*
13703  * Propagate a multicast group membership operation (add/drop) on
13704  * all the interfaces crossed by the related multirt routes.
13705  * The call is considered successful if the operation succeeds
13706  * on at least one interface.
13707  *
13708  * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
13709  * multicast addresses with the ire argument being the first one.
13710  * We walk the bucket to find all the of those.
13711  *
13712  * Common to IPv4 and IPv6.
13713  */
13714 static int
13715 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
13716     const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
13717     ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
13718     mcast_record_t fmode, const in6_addr_t *v6src)
13719 {
13720 	ire_t		*ire_gw;
13721 	irb_t		*irb;
13722 	int		ifindex;
13723 	int		error = 0;
13724 	int		result;
13725 	ip_stack_t	*ipst = ire->ire_ipst;
13726 	ipaddr_t	group;
13727 	boolean_t	isv6;
13728 	int		match_flags;
13729 
13730 	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
13731 		IN6_V4MAPPED_TO_IPADDR(v6group, group);
13732 		isv6 = B_FALSE;
13733 	} else {
13734 		isv6 = B_TRUE;
13735 	}
13736 
13737 	irb = ire->ire_bucket;
13738 	ASSERT(irb != NULL);
13739 
13740 	result = 0;
13741 	irb_refhold(irb);
13742 	for (; ire != NULL; ire = ire->ire_next) {
13743 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
13744 			continue;
13745 
13746 		/* We handle -ifp routes by matching on the ill if set */
13747 		match_flags = MATCH_IRE_TYPE;
13748 		if (ire->ire_ill != NULL)
13749 			match_flags |= MATCH_IRE_ILL;
13750 
13751 		if (isv6) {
13752 			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
13753 				continue;
13754 
13755 			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
13756 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13757 			    match_flags, 0, ipst, NULL);
13758 		} else {
13759 			if (ire->ire_addr != group)
13760 				continue;
13761 
13762 			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
13763 			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
13764 			    match_flags, 0, ipst, NULL);
13765 		}
13766 		/* No interface route exists for the gateway; skip this ire. */
13767 		if (ire_gw == NULL)
13768 			continue;
13769 		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
13770 			ire_refrele(ire_gw);
13771 			continue;
13772 		}
13773 		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
13774 		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;
13775 
13776 		/*
13777 		 * The operation is considered a success if
13778 		 * it succeeds at least once on any one interface.
13779 		 */
13780 		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
13781 		    fmode, v6src);
13782 		if (error == 0)
13783 			result = CGTP_MCAST_SUCCESS;
13784 
13785 		ire_refrele(ire_gw);
13786 	}
13787 	irb_refrele(irb);
13788 	/*
13789 	 * Consider the call as successful if we succeeded on at least
13790 	 * one interface. Otherwise, return the last encountered error.
13791 	 */
13792 	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
13793 }
13794 
13795 /*
13796  * Return the expected CGTP hooks version number.
13797  */
13798 int
13799 ip_cgtp_filter_supported(void)
13800 {
13801 	return (ip_cgtp_filter_rev);
13802 }
13803 
13804 /*
13805  * CGTP hooks can be registered by invoking this function.
13806  * Checks that the version number matches.
13807  */
13808 int
13809 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
13810 {
13811 	netstack_t *ns;
13812 	ip_stack_t *ipst;
13813 
13814 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
13815 		return (ENOTSUP);
13816 
13817 	ns = netstack_find_by_stackid(stackid);
13818 	if (ns == NULL)
13819 		return (EINVAL);
13820 	ipst = ns->netstack_ip;
13821 	ASSERT(ipst != NULL);
13822 
13823 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
13824 		netstack_rele(ns);
13825 		return (EALREADY);
13826 	}
13827 
13828 	ipst->ips_ip_cgtp_filter_ops = ops;
13829 
13830 	ill_set_inputfn_all(ipst);
13831 
13832 	netstack_rele(ns);
13833 	return (0);
13834 }
13835 
13836 /*
13837  * CGTP hooks can be unregistered by invoking this function.
13838  * Returns ENXIO if there was no registration.
13839  * Returns EBUSY if the ndd variable has not been turned off.
13840  */
13841 int
13842 ip_cgtp_filter_unregister(netstackid_t stackid)
13843 {
13844 	netstack_t *ns;
13845 	ip_stack_t *ipst;
13846 
13847 	ns = netstack_find_by_stackid(stackid);
13848 	if (ns == NULL)
13849 		return (EINVAL);
13850 	ipst = ns->netstack_ip;
13851 	ASSERT(ipst != NULL);
13852 
13853 	if (ipst->ips_ip_cgtp_filter) {
13854 		netstack_rele(ns);
13855 		return (EBUSY);
13856 	}
13857 
13858 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
13859 		netstack_rele(ns);
13860 		return (ENXIO);
13861 	}
13862 	ipst->ips_ip_cgtp_filter_ops = NULL;
13863 
13864 	ill_set_inputfn_all(ipst);
13865 
13866 	netstack_rele(ns);
13867 	return (0);
13868 }
13869 
13870 /*
13871  * Check whether there is a CGTP filter registration.
13872  * Returns non-zero if there is a registration, otherwise returns zero.
13873  * Note: returns zero if bad stackid.
13874  */
13875 int
13876 ip_cgtp_filter_is_registered(netstackid_t stackid)
13877 {
13878 	netstack_t *ns;
13879 	ip_stack_t *ipst;
13880 	int ret;
13881 
13882 	ns = netstack_find_by_stackid(stackid);
13883 	if (ns == NULL)
13884 		return (0);
13885 	ipst = ns->netstack_ip;
13886 	ASSERT(ipst != NULL);
13887 
13888 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
13889 		ret = 1;
13890 	else
13891 		ret = 0;
13892 
13893 	netstack_rele(ns);
13894 	return (ret);
13895 }
13896 
13897 static int
13898 ip_squeue_switch(int val)
13899 {
13900 	int rval;
13901 
13902 	switch (val) {
13903 	case IP_SQUEUE_ENTER_NODRAIN:
13904 		rval = SQ_NODRAIN;
13905 		break;
13906 	case IP_SQUEUE_ENTER:
13907 		rval = SQ_PROCESS;
13908 		break;
13909 	case IP_SQUEUE_FILL:
13910 	default:
13911 		rval = SQ_FILL;
13912 		break;
13913 	}
13914 	return (rval);
13915 }
13916 
13917 static void *
13918 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
13919 {
13920 	kstat_t *ksp;
13921 
13922 	ip_stat_t template = {
13923 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
13924 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
13925 		{ "ip_recv_pullup", 		KSTAT_DATA_UINT64 },
13926 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
13927 		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
13928 		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
13929 		{ "ip_opt",			KSTAT_DATA_UINT64 },
13930 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
13931 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
13932 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
13933 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
13934 		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
13935 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
13936 		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
13937 		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
13938 		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
13939 		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13940 		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
13941 		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
13942 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13943 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13944 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
13945 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
13946 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
13947 		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
13948 		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
13949 		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
13950 		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
13951 		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
13952 		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
13953 		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
13954 		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
13955 		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
13956 		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
13957 		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
13958 		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
13959 		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
13960 		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
13961 		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
13962 	};
13963 
13964 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
13965 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
13966 	    KSTAT_FLAG_VIRTUAL, stackid);
13967 
13968 	if (ksp == NULL)
13969 		return (NULL);
13970 
13971 	bcopy(&template, ip_statisticsp, sizeof (template));
13972 	ksp->ks_data = (void *)ip_statisticsp;
13973 	ksp->ks_private = (void *)(uintptr_t)stackid;
13974 
13975 	kstat_install(ksp);
13976 	return (ksp);
13977 }
13978 
13979 static void
13980 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
13981 {
13982 	if (ksp != NULL) {
13983 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
13984 		kstat_delete_netstack(ksp, stackid);
13985 	}
13986 }
13987 
13988 static void *
13989 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
13990 {
13991 	kstat_t	*ksp;
13992 
13993 	ip_named_kstat_t template = {
13994 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
13995 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
13996 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
13997 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
13998 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
13999 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
14000 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
14001 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
14002 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
14003 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
14004 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
14005 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
14006 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
14007 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
14008 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
14009 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
14010 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
14011 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
14012 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
14013 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
14014 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
14015 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
14016 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
14017 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
14018 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
14019 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
14020 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
14021 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
14022 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
14023 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
14024 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
14025 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
14026 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
14027 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
14028 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
14029 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
14030 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
14031 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
14032 	};
14033 
14034 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
14035 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
14036 	if (ksp == NULL || ksp->ks_data == NULL)
14037 		return (NULL);
14038 
14039 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
14040 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
14041 	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
14042 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
14043 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
14044 
14045 	template.netToMediaEntrySize.value.i32 =
14046 	    sizeof (mib2_ipNetToMediaEntry_t);
14047 
14048 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
14049 
14050 	bcopy(&template, ksp->ks_data, sizeof (template));
14051 	ksp->ks_update = ip_kstat_update;
14052 	ksp->ks_private = (void *)(uintptr_t)stackid;
14053 
14054 	kstat_install(ksp);
14055 	return (ksp);
14056 }
14057 
14058 static void
14059 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14060 {
14061 	if (ksp != NULL) {
14062 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14063 		kstat_delete_netstack(ksp, stackid);
14064 	}
14065 }
14066 
14067 static int
14068 ip_kstat_update(kstat_t *kp, int rw)
14069 {
14070 	ip_named_kstat_t *ipkp;
14071 	mib2_ipIfStatsEntry_t ipmib;
14072 	ill_walk_context_t ctx;
14073 	ill_t *ill;
14074 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14075 	netstack_t	*ns;
14076 	ip_stack_t	*ipst;
14077 
14078 	if (kp == NULL || kp->ks_data == NULL)
14079 		return (EIO);
14080 
14081 	if (rw == KSTAT_WRITE)
14082 		return (EACCES);
14083 
14084 	ns = netstack_find_by_stackid(stackid);
14085 	if (ns == NULL)
14086 		return (-1);
14087 	ipst = ns->netstack_ip;
14088 	if (ipst == NULL) {
14089 		netstack_rele(ns);
14090 		return (-1);
14091 	}
14092 	ipkp = (ip_named_kstat_t *)kp->ks_data;
14093 
14094 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
14095 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
14096 	ill = ILL_START_WALK_V4(&ctx, ipst);
14097 	for (; ill != NULL; ill = ill_next(&ctx, ill))
14098 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
14099 	rw_exit(&ipst->ips_ill_g_lock);
14100 
14101 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
14102 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
14103 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
14104 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
14105 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
14106 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
14107 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
14108 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
14109 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
14110 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
14111 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
14112 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
14113 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
14114 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
14115 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
14116 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
14117 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
14118 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
14119 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
14120 
14121 	ipkp->routingDiscards.value.ui32 =	0;
14122 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
14123 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
14124 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
14125 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
14126 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
14127 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
14128 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
14129 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
14130 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
14131 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
14132 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
14133 
14134 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
14135 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
14136 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
14137 
14138 	netstack_rele(ns);
14139 
14140 	return (0);
14141 }
14142 
14143 static void *
14144 icmp_kstat_init(netstackid_t stackid)
14145 {
14146 	kstat_t	*ksp;
14147 
14148 	icmp_named_kstat_t template = {
14149 		{ "inMsgs",		KSTAT_DATA_UINT32 },
14150 		{ "inErrors",		KSTAT_DATA_UINT32 },
14151 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
14152 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
14153 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
14154 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
14155 		{ "inRedirects",	KSTAT_DATA_UINT32 },
14156 		{ "inEchos",		KSTAT_DATA_UINT32 },
14157 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
14158 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
14159 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
14160 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
14161 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
14162 		{ "outMsgs",		KSTAT_DATA_UINT32 },
14163 		{ "outErrors",		KSTAT_DATA_UINT32 },
14164 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
14165 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
14166 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
14167 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
14168 		{ "outRedirects",	KSTAT_DATA_UINT32 },
14169 		{ "outEchos",		KSTAT_DATA_UINT32 },
14170 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
14171 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
14172 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
14173 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
14174 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
14175 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
14176 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
14177 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
14178 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
14179 		{ "outDrops",		KSTAT_DATA_UINT32 },
14180 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
14181 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
14182 	};
14183 
14184 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
14185 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
14186 	if (ksp == NULL || ksp->ks_data == NULL)
14187 		return (NULL);
14188 
14189 	bcopy(&template, ksp->ks_data, sizeof (template));
14190 
14191 	ksp->ks_update = icmp_kstat_update;
14192 	ksp->ks_private = (void *)(uintptr_t)stackid;
14193 
14194 	kstat_install(ksp);
14195 	return (ksp);
14196 }
14197 
14198 static void
14199 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
14200 {
14201 	if (ksp != NULL) {
14202 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
14203 		kstat_delete_netstack(ksp, stackid);
14204 	}
14205 }
14206 
14207 static int
14208 icmp_kstat_update(kstat_t *kp, int rw)
14209 {
14210 	icmp_named_kstat_t *icmpkp;
14211 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
14212 	netstack_t	*ns;
14213 	ip_stack_t	*ipst;
14214 
14215 	if ((kp == NULL) || (kp->ks_data == NULL))
14216 		return (EIO);
14217 
14218 	if (rw == KSTAT_WRITE)
14219 		return (EACCES);
14220 
14221 	ns = netstack_find_by_stackid(stackid);
14222 	if (ns == NULL)
14223 		return (-1);
14224 	ipst = ns->netstack_ip;
14225 	if (ipst == NULL) {
14226 		netstack_rele(ns);
14227 		return (-1);
14228 	}
14229 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
14230 
14231 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
14232 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
14233 	icmpkp->inDestUnreachs.value.ui32 =
14234 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
14235 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
14236 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
14237 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
14238 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
14239 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
14240 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
14241 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
14242 	icmpkp->inTimestampReps.value.ui32 =
14243 	    ipst->ips_icmp_mib.icmpInTimestampReps;
14244 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
14245 	icmpkp->inAddrMaskReps.value.ui32 =
14246 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
14247 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
14248 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
14249 	icmpkp->outDestUnreachs.value.ui32 =
14250 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
14251 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
14252 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
14253 	icmpkp->outSrcQuenchs.value.ui32 =
14254 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
14255 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
14256 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
14257 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
14258 	icmpkp->outTimestamps.value.ui32 =
14259 	    ipst->ips_icmp_mib.icmpOutTimestamps;
14260 	icmpkp->outTimestampReps.value.ui32 =
14261 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
14262 	icmpkp->outAddrMasks.value.ui32 =
14263 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
14264 	icmpkp->outAddrMaskReps.value.ui32 =
14265 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
14266 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
14267 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
14268 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
14269 	icmpkp->outFragNeeded.value.ui32 =
14270 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
14271 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
14272 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
14273 	icmpkp->inBadRedirects.value.ui32 =
14274 	    ipst->ips_icmp_mib.icmpInBadRedirects;
14275 
14276 	netstack_rele(ns);
14277 	return (0);
14278 }
14279 
14280 /*
14281  * This is the fanout function for raw socket opened for SCTP.  Note
14282  * that it is called after SCTP checks that there is no socket which
14283  * wants a packet.  Then before SCTP handles this out of the blue packet,
14284  * this function is called to see if there is any raw socket for SCTP.
14285  * If there is and it is bound to the correct address, the packet will
14286  * be sent to that socket.  Note that only one raw socket can be bound to
14287  * a port.  This is assured in ipcl_sctp_hash_insert();
14288  */
14289 void
14290 ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
14291     ip_recv_attr_t *ira)
14292 {
14293 	conn_t		*connp;
14294 	queue_t		*rq;
14295 	boolean_t	secure;
14296 	ill_t		*ill = ira->ira_ill;
14297 	ip_stack_t	*ipst = ill->ill_ipst;
14298 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
14299 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
14300 	iaflags_t	iraflags = ira->ira_flags;
14301 	ill_t		*rill = ira->ira_rill;
14302 
14303 	secure = iraflags & IRAF_IPSEC_SECURE;
14304 
14305 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
14306 	    ira, ipst);
14307 	if (connp == NULL) {
14308 		/*
14309 		 * Although raw sctp is not summed, OOB chunks must be.
14310 		 * Drop the packet here if the sctp checksum failed.
14311 		 */
14312 		if (iraflags & IRAF_SCTP_CSUM_ERR) {
14313 			SCTPS_BUMP_MIB(sctps, sctpChecksumError);
14314 			freemsg(mp);
14315 			return;
14316 		}
14317 		ira->ira_ill = ira->ira_rill = NULL;
14318 		sctp_ootb_input(mp, ira, ipst);
14319 		ira->ira_ill = ill;
14320 		ira->ira_rill = rill;
14321 		return;
14322 	}
14323 	rq = connp->conn_rq;
14324 	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
14325 		CONN_DEC_REF(connp);
14326 		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
14327 		freemsg(mp);
14328 		return;
14329 	}
14330 	if (((iraflags & IRAF_IS_IPV4) ?
14331 	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
14332 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
14333 	    secure) {
14334 		mp = ipsec_check_inbound_policy(mp, connp, ipha,
14335 		    ip6h, ira);
14336 		if (mp == NULL) {
14337 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14338 			/* Note that mp is NULL */
14339 			ip_drop_input("ipIfStatsInDiscards", mp, ill);
14340 			CONN_DEC_REF(connp);
14341 			return;
14342 		}
14343 	}
14344 
14345 	if (iraflags & IRAF_ICMP_ERROR) {
14346 		(connp->conn_recvicmp)(connp, mp, NULL, ira);
14347 	} else {
14348 		ill_t *rill = ira->ira_rill;
14349 
14350 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
14351 		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
14352 		ira->ira_ill = ira->ira_rill = NULL;
14353 		(connp->conn_recv)(connp, mp, NULL, ira);
14354 		ira->ira_ill = ill;
14355 		ira->ira_rill = rill;
14356 	}
14357 	CONN_DEC_REF(connp);
14358 }
14359 
14360 /*
14361  * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
14362  * header before the ip payload.
14363  */
14364 static void
14365 ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
14366 {
14367 	int len = (mp->b_wptr - mp->b_rptr);
14368 	mblk_t *ip_mp;
14369 
14370 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14371 	if (is_fp_mp || len != fp_mp_len) {
14372 		if (len > fp_mp_len) {
14373 			/*
14374 			 * fastpath header and ip header in the first mblk
14375 			 */
14376 			mp->b_rptr += fp_mp_len;
14377 		} else {
14378 			/*
14379 			 * ip_xmit_attach_llhdr had to prepend an mblk to
14380 			 * attach the fastpath header before ip header.
14381 			 */
14382 			ip_mp = mp->b_cont;
14383 			freeb(mp);
14384 			mp = ip_mp;
14385 			mp->b_rptr += (fp_mp_len - len);
14386 		}
14387 	} else {
14388 		ip_mp = mp->b_cont;
14389 		freeb(mp);
14390 		mp = ip_mp;
14391 	}
14392 	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
14393 	freemsg(mp);
14394 }
14395 
14396 /*
14397  * Normal post fragmentation function.
14398  *
14399  * Send a packet using the passed in nce. This handles both IPv4 and IPv6
14400  * using the same state machine.
14401  *
14402  * We return an error on failure. In particular we return EWOULDBLOCK
14403  * when the driver flow controls. In that case this ensures that ip_wsrv runs
14404  * (currently by canputnext failure resulting in backenabling from GLD.)
14405  * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
14406  * indication that they can flow control until ip_wsrv() tells then to restart.
14407  *
14408  * If the nce passed by caller is incomplete, this function
14409  * queues the packet and if necessary, sends ARP request and bails.
14410  * If the Neighbor Cache passed is fully resolved, we simply prepend
14411  * the link-layer header to the packet, do ipsec hw acceleration
14412  * work if necessary, and send the packet out on the wire.
14413  */
14414 /* ARGSUSED6 */
14415 int
14416 ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
14417     uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
14418 {
14419 	queue_t		*wq;
14420 	ill_t		*ill = nce->nce_ill;
14421 	ip_stack_t	*ipst = ill->ill_ipst;
14422 	uint64_t	delta;
14423 	boolean_t	isv6 = ill->ill_isv6;
14424 	boolean_t	fp_mp;
14425 	ncec_t		*ncec = nce->nce_common;
14426 	int64_t		now = LBOLT_FASTPATH64;
14427 	boolean_t	is_probe;
14428 
14429 	DTRACE_PROBE1(ip__xmit, nce_t *, nce);
14430 
14431 	ASSERT(mp != NULL);
14432 	ASSERT(mp->b_datap->db_type == M_DATA);
14433 	ASSERT(pkt_len == msgdsize(mp));
14434 
14435 	/*
14436 	 * If we have already been here and are coming back after ARP/ND.
14437 	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
14438 	 * in that case since they have seen the packet when it came here
14439 	 * the first time.
14440 	 */
14441 	if (ixaflags & IXAF_NO_TRACE)
14442 		goto sendit;
14443 
14444 	if (ixaflags & IXAF_IS_IPV4) {
14445 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
14446 
14447 		ASSERT(!isv6);
14448 		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
14449 		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
14450 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14451 			int	error;
14452 
14453 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14454 			    ipst->ips_ipv4firewall_physical_out,
14455 			    NULL, ill, ipha, mp, mp, 0, ipst, error);
14456 			DTRACE_PROBE1(ip4__physical__out__end,
14457 			    mblk_t *, mp);
14458 			if (mp == NULL)
14459 				return (error);
14460 
14461 			/* The length could have changed */
14462 			pkt_len = msgdsize(mp);
14463 		}
14464 		if (ipst->ips_ip4_observe.he_interested) {
14465 			/*
14466 			 * Note that for TX the zoneid is the sending
14467 			 * zone, whether or not MLP is in play.
14468 			 * Since the szone argument is the IP zoneid (i.e.,
14469 			 * zero for exclusive-IP zones) and ipobs wants
14470 			 * the system zoneid, we map it here.
14471 			 */
14472 			szone = IP_REAL_ZONEID(szone, ipst);
14473 
14474 			/*
14475 			 * On the outbound path the destination zone will be
14476 			 * unknown as we're sending this packet out on the
14477 			 * wire.
14478 			 */
14479 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14480 			    ill, ipst);
14481 		}
14482 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14483 		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
14484 		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
14485 	} else {
14486 		ip6_t *ip6h = (ip6_t *)mp->b_rptr;
14487 
14488 		ASSERT(isv6);
14489 		ASSERT(pkt_len ==
14490 		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
14491 		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
14492 		    !(ixaflags & IXAF_NO_PFHOOK)) {
14493 			int	error;
14494 
14495 			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
14496 			    ipst->ips_ipv6firewall_physical_out,
14497 			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
14498 			DTRACE_PROBE1(ip6__physical__out__end,
14499 			    mblk_t *, mp);
14500 			if (mp == NULL)
14501 				return (error);
14502 
14503 			/* The length could have changed */
14504 			pkt_len = msgdsize(mp);
14505 		}
14506 		if (ipst->ips_ip6_observe.he_interested) {
14507 			/* See above */
14508 			szone = IP_REAL_ZONEID(szone, ipst);
14509 
14510 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
14511 			    ill, ipst);
14512 		}
14513 		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
14514 		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
14515 		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
14516 	}
14517 
14518 sendit:
14519 	/*
14520 	 * We check the state without a lock because the state can never
14521 	 * move "backwards" to initial or incomplete.
14522 	 */
14523 	switch (ncec->ncec_state) {
14524 	case ND_REACHABLE:
14525 	case ND_STALE:
14526 	case ND_DELAY:
14527 	case ND_PROBE:
14528 		mp = ip_xmit_attach_llhdr(mp, nce);
14529 		if (mp == NULL) {
14530 			/*
14531 			 * ip_xmit_attach_llhdr has increased
14532 			 * ipIfStatsOutDiscards and called ip_drop_output()
14533 			 */
14534 			return (ENOBUFS);
14535 		}
14536 		/*
14537 		 * check if nce_fastpath completed and we tagged on a
14538 		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
14539 		 */
14540 		fp_mp = (mp->b_datap->db_type == M_DATA);
14541 
14542 		if (fp_mp &&
14543 		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
14544 			ill_dld_direct_t *idd;
14545 
14546 			idd = &ill->ill_dld_capab->idc_direct;
14547 			/*
14548 			 * Send the packet directly to DLD, where it
14549 			 * may be queued depending on the availability
14550 			 * of transmit resources at the media layer.
14551 			 * Return value should be taken into
14552 			 * account and flow control the TCP.
14553 			 */
14554 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14555 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14556 			    pkt_len);
14557 
14558 			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
14559 				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
14560 				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
14561 			} else {
14562 				uintptr_t cookie;
14563 
14564 				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
14565 				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
14566 					if (ixacookie != NULL)
14567 						*ixacookie = cookie;
14568 					return (EWOULDBLOCK);
14569 				}
14570 			}
14571 		} else {
14572 			wq = ill->ill_wq;
14573 
14574 			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
14575 			    !canputnext(wq)) {
14576 				if (ixacookie != NULL)
14577 					*ixacookie = 0;
14578 				ip_xmit_flowctl_drop(ill, mp, fp_mp,
14579 				    nce->nce_fp_mp != NULL ?
14580 				    MBLKL(nce->nce_fp_mp) : 0);
14581 				return (EWOULDBLOCK);
14582 			}
14583 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14584 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
14585 			    pkt_len);
14586 			putnext(wq, mp);
14587 		}
14588 
14589 		/*
14590 		 * The rest of this function implements Neighbor Unreachability
14591 		 * detection. Determine if the ncec is eligible for NUD.
14592 		 */
14593 		if (ncec->ncec_flags & NCE_F_NONUD)
14594 			return (0);
14595 
14596 		ASSERT(ncec->ncec_state != ND_INCOMPLETE);
14597 
14598 		/*
14599 		 * Check for upper layer advice
14600 		 */
14601 		if (ixaflags & IXAF_REACH_CONF) {
14602 			timeout_id_t tid;
14603 
14604 			/*
14605 			 * It should be o.k. to check the state without
14606 			 * a lock here, at most we lose an advice.
14607 			 */
14608 			ncec->ncec_last = TICK_TO_MSEC(now);
14609 			if (ncec->ncec_state != ND_REACHABLE) {
14610 				mutex_enter(&ncec->ncec_lock);
14611 				ncec->ncec_state = ND_REACHABLE;
14612 				tid = ncec->ncec_timeout_id;
14613 				ncec->ncec_timeout_id = 0;
14614 				mutex_exit(&ncec->ncec_lock);
14615 				(void) untimeout(tid);
14616 				if (ip_debug > 2) {
14617 					/* ip1dbg */
14618 					pr_addr_dbg("ip_xmit: state"
14619 					    " for %s changed to"
14620 					    " REACHABLE\n", AF_INET6,
14621 					    &ncec->ncec_addr);
14622 				}
14623 			}
14624 			return (0);
14625 		}
14626 
14627 		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
14628 		ip1dbg(("ip_xmit: delta = %" PRId64
14629 		    " ill_reachable_time = %d \n", delta,
14630 		    ill->ill_reachable_time));
14631 		if (delta > (uint64_t)ill->ill_reachable_time) {
14632 			mutex_enter(&ncec->ncec_lock);
14633 			switch (ncec->ncec_state) {
14634 			case ND_REACHABLE:
14635 				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
14636 				/* FALLTHROUGH */
14637 			case ND_STALE:
14638 				/*
14639 				 * ND_REACHABLE is identical to
14640 				 * ND_STALE in this specific case. If
14641 				 * reachable time has expired for this
14642 				 * neighbor (delta is greater than
14643 				 * reachable time), conceptually, the
14644 				 * neighbor cache is no longer in
14645 				 * REACHABLE state, but already in
14646 				 * STALE state.  So the correct
14647 				 * transition here is to ND_DELAY.
14648 				 */
14649 				ncec->ncec_state = ND_DELAY;
14650 				mutex_exit(&ncec->ncec_lock);
14651 				nce_restart_timer(ncec,
14652 				    ipst->ips_delay_first_probe_time);
14653 				if (ip_debug > 3) {
14654 					/* ip2dbg */
14655 					pr_addr_dbg("ip_xmit: state"
14656 					    " for %s changed to"
14657 					    " DELAY\n", AF_INET6,
14658 					    &ncec->ncec_addr);
14659 				}
14660 				break;
14661 			case ND_DELAY:
14662 			case ND_PROBE:
14663 				mutex_exit(&ncec->ncec_lock);
14664 				/* Timers have already started */
14665 				break;
14666 			case ND_UNREACHABLE:
14667 				/*
14668 				 * nce_timer has detected that this ncec
14669 				 * is unreachable and initiated deleting
14670 				 * this ncec.
14671 				 * This is a harmless race where we found the
14672 				 * ncec before it was deleted and have
14673 				 * just sent out a packet using this
14674 				 * unreachable ncec.
14675 				 */
14676 				mutex_exit(&ncec->ncec_lock);
14677 				break;
14678 			default:
14679 				ASSERT(0);
14680 				mutex_exit(&ncec->ncec_lock);
14681 			}
14682 		}
14683 		return (0);
14684 
14685 	case ND_INCOMPLETE:
14686 		/*
14687 		 * the state could have changed since we didn't hold the lock.
14688 		 * Re-verify state under lock.
14689 		 */
14690 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14691 		mutex_enter(&ncec->ncec_lock);
14692 		if (NCE_ISREACHABLE(ncec)) {
14693 			mutex_exit(&ncec->ncec_lock);
14694 			goto sendit;
14695 		}
14696 		/* queue the packet */
14697 		nce_queue_mp(ncec, mp, is_probe);
14698 		mutex_exit(&ncec->ncec_lock);
14699 		DTRACE_PROBE2(ip__xmit__incomplete,
14700 		    (ncec_t *), ncec, (mblk_t *), mp);
14701 		return (0);
14702 
14703 	case ND_INITIAL:
14704 		/*
14705 		 * State could have changed since we didn't hold the lock, so
14706 		 * re-verify state.
14707 		 */
14708 		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
14709 		mutex_enter(&ncec->ncec_lock);
14710 		if (NCE_ISREACHABLE(ncec))  {
14711 			mutex_exit(&ncec->ncec_lock);
14712 			goto sendit;
14713 		}
14714 		nce_queue_mp(ncec, mp, is_probe);
14715 		if (ncec->ncec_state == ND_INITIAL) {
14716 			ncec->ncec_state = ND_INCOMPLETE;
14717 			mutex_exit(&ncec->ncec_lock);
14718 			/*
14719 			 * figure out the source we want to use
14720 			 * and resolve it.
14721 			 */
14722 			ip_ndp_resolve(ncec);
14723 		} else  {
14724 			mutex_exit(&ncec->ncec_lock);
14725 		}
14726 		return (0);
14727 
14728 	case ND_UNREACHABLE:
14729 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14730 		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
14731 		    mp, ill);
14732 		freemsg(mp);
14733 		return (0);
14734 
14735 	default:
14736 		ASSERT(0);
14737 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
14738 		ip_drop_output("ipIfStatsOutDiscards - ND_other",
14739 		    mp, ill);
14740 		freemsg(mp);
14741 		return (ENETUNREACH);
14742 	}
14743 }
14744 
14745 /*
14746  * Return B_TRUE if the buffers differ in length or content.
14747  * This is used for comparing extension header buffers.
14748  * Note that an extension header would be declared different
14749  * even if all that changed was the next header value in that header i.e.
14750  * what really changed is the next extension header.
14751  */
14752 boolean_t
14753 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
14754     uint_t blen)
14755 {
14756 	if (!b_valid)
14757 		blen = 0;
14758 
14759 	if (alen != blen)
14760 		return (B_TRUE);
14761 	if (alen == 0)
14762 		return (B_FALSE);	/* Both zero length */
14763 	return (bcmp(abuf, bbuf, alen));
14764 }
14765 
14766 /*
14767  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
14768  * Return B_FALSE if memory allocation fails - don't change any state!
14769  */
14770 boolean_t
14771 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14772     const void *src, uint_t srclen)
14773 {
14774 	void *dst;
14775 
14776 	if (!src_valid)
14777 		srclen = 0;
14778 
14779 	ASSERT(*dstlenp == 0);
14780 	if (src != NULL && srclen != 0) {
14781 		dst = mi_alloc(srclen, BPRI_MED);
14782 		if (dst == NULL)
14783 			return (B_FALSE);
14784 	} else {
14785 		dst = NULL;
14786 	}
14787 	if (*dstp != NULL)
14788 		mi_free(*dstp);
14789 	*dstp = dst;
14790 	*dstlenp = dst == NULL ? 0 : srclen;
14791 	return (B_TRUE);
14792 }
14793 
14794 /*
14795  * Replace what is in *dst, *dstlen with the source.
14796  * Assumes ip_allocbuf has already been called.
14797  */
14798 void
14799 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
14800     const void *src, uint_t srclen)
14801 {
14802 	if (!src_valid)
14803 		srclen = 0;
14804 
14805 	ASSERT(*dstlenp == srclen);
14806 	if (src != NULL && srclen != 0)
14807 		bcopy(src, *dstp, srclen);
14808 }
14809 
14810 /*
14811  * Free the storage pointed to by the members of an ip_pkt_t.
14812  */
14813 void
14814 ip_pkt_free(ip_pkt_t *ipp)
14815 {
14816 	uint_t	fields = ipp->ipp_fields;
14817 
14818 	if (fields & IPPF_HOPOPTS) {
14819 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
14820 		ipp->ipp_hopopts = NULL;
14821 		ipp->ipp_hopoptslen = 0;
14822 	}
14823 	if (fields & IPPF_RTHDRDSTOPTS) {
14824 		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
14825 		ipp->ipp_rthdrdstopts = NULL;
14826 		ipp->ipp_rthdrdstoptslen = 0;
14827 	}
14828 	if (fields & IPPF_DSTOPTS) {
14829 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
14830 		ipp->ipp_dstopts = NULL;
14831 		ipp->ipp_dstoptslen = 0;
14832 	}
14833 	if (fields & IPPF_RTHDR) {
14834 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
14835 		ipp->ipp_rthdr = NULL;
14836 		ipp->ipp_rthdrlen = 0;
14837 	}
14838 	if (fields & IPPF_IPV4_OPTIONS) {
14839 		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
14840 		ipp->ipp_ipv4_options = NULL;
14841 		ipp->ipp_ipv4_options_len = 0;
14842 	}
14843 	if (fields & IPPF_LABEL_V4) {
14844 		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
14845 		ipp->ipp_label_v4 = NULL;
14846 		ipp->ipp_label_len_v4 = 0;
14847 	}
14848 	if (fields & IPPF_LABEL_V6) {
14849 		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
14850 		ipp->ipp_label_v6 = NULL;
14851 		ipp->ipp_label_len_v6 = 0;
14852 	}
14853 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14854 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14855 }
14856 
14857 /*
14858  * Copy from src to dst and allocate as needed.
14859  * Returns zero or ENOMEM.
14860  *
14861  * The caller must initialize dst to zero.
14862  */
14863 int
14864 ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
14865 {
14866 	uint_t	fields = src->ipp_fields;
14867 
14868 	/* Start with fields that don't require memory allocation */
14869 	dst->ipp_fields = fields &
14870 	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14871 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
14872 
14873 	dst->ipp_addr = src->ipp_addr;
14874 	dst->ipp_unicast_hops = src->ipp_unicast_hops;
14875 	dst->ipp_hoplimit = src->ipp_hoplimit;
14876 	dst->ipp_tclass = src->ipp_tclass;
14877 	dst->ipp_type_of_service = src->ipp_type_of_service;
14878 
14879 	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
14880 	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
14881 		return (0);
14882 
14883 	if (fields & IPPF_HOPOPTS) {
14884 		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
14885 		if (dst->ipp_hopopts == NULL) {
14886 			ip_pkt_free(dst);
14887 			return (ENOMEM);
14888 		}
14889 		dst->ipp_fields |= IPPF_HOPOPTS;
14890 		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
14891 		    src->ipp_hopoptslen);
14892 		dst->ipp_hopoptslen = src->ipp_hopoptslen;
14893 	}
14894 	if (fields & IPPF_RTHDRDSTOPTS) {
14895 		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
14896 		    kmflag);
14897 		if (dst->ipp_rthdrdstopts == NULL) {
14898 			ip_pkt_free(dst);
14899 			return (ENOMEM);
14900 		}
14901 		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
14902 		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
14903 		    src->ipp_rthdrdstoptslen);
14904 		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
14905 	}
14906 	if (fields & IPPF_DSTOPTS) {
14907 		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
14908 		if (dst->ipp_dstopts == NULL) {
14909 			ip_pkt_free(dst);
14910 			return (ENOMEM);
14911 		}
14912 		dst->ipp_fields |= IPPF_DSTOPTS;
14913 		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
14914 		    src->ipp_dstoptslen);
14915 		dst->ipp_dstoptslen = src->ipp_dstoptslen;
14916 	}
14917 	if (fields & IPPF_RTHDR) {
14918 		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
14919 		if (dst->ipp_rthdr == NULL) {
14920 			ip_pkt_free(dst);
14921 			return (ENOMEM);
14922 		}
14923 		dst->ipp_fields |= IPPF_RTHDR;
14924 		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
14925 		    src->ipp_rthdrlen);
14926 		dst->ipp_rthdrlen = src->ipp_rthdrlen;
14927 	}
14928 	if (fields & IPPF_IPV4_OPTIONS) {
14929 		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
14930 		    kmflag);
14931 		if (dst->ipp_ipv4_options == NULL) {
14932 			ip_pkt_free(dst);
14933 			return (ENOMEM);
14934 		}
14935 		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
14936 		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
14937 		    src->ipp_ipv4_options_len);
14938 		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
14939 	}
14940 	if (fields & IPPF_LABEL_V4) {
14941 		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
14942 		if (dst->ipp_label_v4 == NULL) {
14943 			ip_pkt_free(dst);
14944 			return (ENOMEM);
14945 		}
14946 		dst->ipp_fields |= IPPF_LABEL_V4;
14947 		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
14948 		    src->ipp_label_len_v4);
14949 		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
14950 	}
14951 	if (fields & IPPF_LABEL_V6) {
14952 		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
14953 		if (dst->ipp_label_v6 == NULL) {
14954 			ip_pkt_free(dst);
14955 			return (ENOMEM);
14956 		}
14957 		dst->ipp_fields |= IPPF_LABEL_V6;
14958 		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
14959 		    src->ipp_label_len_v6);
14960 		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
14961 	}
14962 	if (fields & IPPF_FRAGHDR) {
14963 		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
14964 		if (dst->ipp_fraghdr == NULL) {
14965 			ip_pkt_free(dst);
14966 			return (ENOMEM);
14967 		}
14968 		dst->ipp_fields |= IPPF_FRAGHDR;
14969 		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
14970 		    src->ipp_fraghdrlen);
14971 		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
14972 	}
14973 	return (0);
14974 }
14975 
14976 /*
14977  * Returns INADDR_ANY if no source route
14978  */
14979 ipaddr_t
14980 ip_pkt_source_route_v4(const ip_pkt_t *ipp)
14981 {
14982 	ipaddr_t	nexthop = INADDR_ANY;
14983 	ipoptp_t	opts;
14984 	uchar_t		*opt;
14985 	uint8_t		optval;
14986 	uint8_t		optlen;
14987 	uint32_t	totallen;
14988 
14989 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
14990 		return (INADDR_ANY);
14991 
14992 	totallen = ipp->ipp_ipv4_options_len;
14993 	if (totallen & 0x3)
14994 		return (INADDR_ANY);
14995 
14996 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
14997 	    optval != IPOPT_EOL;
14998 	    optval = ipoptp_next(&opts)) {
14999 		opt = opts.ipoptp_cur;
15000 		switch (optval) {
15001 			uint8_t off;
15002 		case IPOPT_SSRR:
15003 		case IPOPT_LSRR:
15004 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15005 				break;
15006 			}
15007 			optlen = opts.ipoptp_len;
15008 			off = opt[IPOPT_OFFSET];
15009 			off--;
15010 			if (optlen < IP_ADDR_LEN ||
15011 			    off > optlen - IP_ADDR_LEN) {
15012 				/* End of source route */
15013 				break;
15014 			}
15015 			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
15016 			if (nexthop == htonl(INADDR_LOOPBACK)) {
15017 				/* Ignore */
15018 				nexthop = INADDR_ANY;
15019 				break;
15020 			}
15021 			break;
15022 		}
15023 	}
15024 	return (nexthop);
15025 }
15026 
15027 /*
15028  * Reverse a source route.
15029  */
15030 void
15031 ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
15032 {
15033 	ipaddr_t	tmp;
15034 	ipoptp_t	opts;
15035 	uchar_t		*opt;
15036 	uint8_t		optval;
15037 	uint32_t	totallen;
15038 
15039 	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
15040 		return;
15041 
15042 	totallen = ipp->ipp_ipv4_options_len;
15043 	if (totallen & 0x3)
15044 		return;
15045 
15046 	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
15047 	    optval != IPOPT_EOL;
15048 	    optval = ipoptp_next(&opts)) {
15049 		uint8_t off1, off2;
15050 
15051 		opt = opts.ipoptp_cur;
15052 		switch (optval) {
15053 		case IPOPT_SSRR:
15054 		case IPOPT_LSRR:
15055 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
15056 				break;
15057 			}
15058 			off1 = IPOPT_MINOFF_SR - 1;
15059 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
15060 			while (off2 > off1) {
15061 				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
15062 				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
15063 				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
15064 				off2 -= IP_ADDR_LEN;
15065 				off1 += IP_ADDR_LEN;
15066 			}
15067 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
15068 			break;
15069 		}
15070 	}
15071 }
15072 
15073 /*
15074  * Returns NULL if no routing header
15075  */
15076 in6_addr_t *
15077 ip_pkt_source_route_v6(const ip_pkt_t *ipp)
15078 {
15079 	in6_addr_t	*nexthop = NULL;
15080 	ip6_rthdr0_t	*rthdr;
15081 
15082 	if (!(ipp->ipp_fields & IPPF_RTHDR))
15083 		return (NULL);
15084 
15085 	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
15086 	if (rthdr->ip6r0_segleft == 0)
15087 		return (NULL);
15088 
15089 	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
15090 	return (nexthop);
15091 }
15092 
15093 zoneid_t
15094 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
15095     zoneid_t lookup_zoneid)
15096 {
15097 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15098 	ire_t		*ire;
15099 	int		ire_flags = MATCH_IRE_TYPE;
15100 	zoneid_t	zoneid = ALL_ZONES;
15101 
15102 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15103 		return (ALL_ZONES);
15104 
15105 	if (lookup_zoneid != ALL_ZONES)
15106 		ire_flags |= MATCH_IRE_ZONEONLY;
15107 	ire = ire_ftable_lookup_v4(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15108 	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15109 	if (ire != NULL) {
15110 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15111 		ire_refrele(ire);
15112 	}
15113 	return (zoneid);
15114 }
15115 
15116 zoneid_t
15117 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
15118     ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
15119 {
15120 	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
15121 	ire_t		*ire;
15122 	int		ire_flags = MATCH_IRE_TYPE;
15123 	zoneid_t	zoneid = ALL_ZONES;
15124 
15125 	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
15126 		return (ALL_ZONES);
15127 
15128 	if (IN6_IS_ADDR_LINKLOCAL(addr))
15129 		ire_flags |= MATCH_IRE_ILL;
15130 
15131 	if (lookup_zoneid != ALL_ZONES)
15132 		ire_flags |= MATCH_IRE_ZONEONLY;
15133 	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
15134 	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
15135 	if (ire != NULL) {
15136 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
15137 		ire_refrele(ire);
15138 	}
15139 	return (zoneid);
15140 }
15141 
15142 /*
15143  * IP obserability hook support functions.
15144  */
15145 static void
15146 ipobs_init(ip_stack_t *ipst)
15147 {
15148 	netid_t id;
15149 
15150 	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);
15151 
15152 	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
15153 	VERIFY(ipst->ips_ip4_observe_pr != NULL);
15154 
15155 	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
15156 	VERIFY(ipst->ips_ip6_observe_pr != NULL);
15157 }
15158 
15159 static void
15160 ipobs_fini(ip_stack_t *ipst)
15161 {
15162 
15163 	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
15164 	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
15165 }
15166 
15167 /*
15168  * hook_pkt_observe_t is composed in network byte order so that the
15169  * entire mblk_t chain handed into hook_run can be used as-is.
15170  * The caveat is that use of the fields, such as the zone fields,
15171  * requires conversion into host byte order first.
15172  */
15173 void
15174 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
15175     const ill_t *ill, ip_stack_t *ipst)
15176 {
15177 	hook_pkt_observe_t *hdr;
15178 	uint64_t grifindex;
15179 	mblk_t *imp;
15180 
15181 	imp = allocb(sizeof (*hdr), BPRI_HI);
15182 	if (imp == NULL)
15183 		return;
15184 
15185 	hdr = (hook_pkt_observe_t *)imp->b_rptr;
15186 	/*
15187 	 * b_wptr is set to make the apparent size of the data in the mblk_t
15188 	 * to exclude the pointers at the end of hook_pkt_observer_t.
15189 	 */
15190 	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
15191 	imp->b_cont = mp;
15192 
15193 	ASSERT(DB_TYPE(mp) == M_DATA);
15194 
15195 	if (IS_UNDER_IPMP(ill))
15196 		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
15197 	else
15198 		grifindex = 0;
15199 
15200 	hdr->hpo_version = 1;
15201 	hdr->hpo_htype = htons(htype);
15202 	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
15203 	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
15204 	hdr->hpo_grifindex = htonl(grifindex);
15205 	hdr->hpo_zsrc = htonl(zsrc);
15206 	hdr->hpo_zdst = htonl(zdst);
15207 	hdr->hpo_pkt = imp;
15208 	hdr->hpo_ctx = ipst->ips_netstack;
15209 
15210 	if (ill->ill_isv6) {
15211 		hdr->hpo_family = AF_INET6;
15212 		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
15213 		    ipst->ips_ipv6observing, (hook_data_t)hdr);
15214 	} else {
15215 		hdr->hpo_family = AF_INET;
15216 		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
15217 		    ipst->ips_ipv4observing, (hook_data_t)hdr);
15218 	}
15219 
15220 	imp->b_cont = NULL;
15221 	freemsg(imp);
15222 }
15223 
15224 /*
15225  * Utility routine that checks if `v4srcp' is a valid address on underlying
15226  * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
15227  * associated with `v4srcp' on success.  NOTE: if this is not called from
15228  * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
15229  * group during or after this lookup.
15230  */
15231 boolean_t
15232 ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
15233 {
15234 	ipif_t *ipif;
15235 
15236 	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
15237 	if (ipif != NULL) {
15238 		if (ipifp != NULL)
15239 			*ipifp = ipif;
15240 		else
15241 			ipif_refrele(ipif);
15242 		return (B_TRUE);
15243 	}
15244 
15245 	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
15246 	    *v4srcp));
15247 	return (B_FALSE);
15248 }
15249 
15250 /*
15251  * Transport protocol call back function for CPU state change.
15252  */
15253 /* ARGSUSED */
15254 static int
15255 ip_tp_cpu_update(cpu_setup_t what, int id, void *arg)
15256 {
15257 	processorid_t cpu_seqid;
15258 	netstack_handle_t nh;
15259 	netstack_t *ns;
15260 
15261 	ASSERT(MUTEX_HELD(&cpu_lock));
15262 
15263 	switch (what) {
15264 	case CPU_CONFIG:
15265 	case CPU_ON:
15266 	case CPU_INIT:
15267 	case CPU_CPUPART_IN:
15268 		cpu_seqid = cpu[id]->cpu_seqid;
15269 		netstack_next_init(&nh);
15270 		while ((ns = netstack_next(&nh)) != NULL) {
15271 			tcp_stack_cpu_add(ns->netstack_tcp, cpu_seqid);
15272 			sctp_stack_cpu_add(ns->netstack_sctp, cpu_seqid);
15273 			udp_stack_cpu_add(ns->netstack_udp, cpu_seqid);
15274 			netstack_rele(ns);
15275 		}
15276 		netstack_next_fini(&nh);
15277 		break;
15278 	case CPU_UNCONFIG:
15279 	case CPU_OFF:
15280 	case CPU_CPUPART_OUT:
15281 		/*
15282 		 * Nothing to do.  We don't remove the per CPU stats from
15283 		 * the IP stack even when the CPU goes offline.
15284 		 */
15285 		break;
15286 	default:
15287 		break;
15288 	}
15289 	return (0);
15290 }
15291